2013-06-21 102 views
2

我打算創建一個太空射擊遊戲,我希望我的背景恆星不斷向下移動。你可以在下面看到我的代碼。圖片http://tinypic.com/r/9a8tj4/5如何使Pygame不斷滾動背景?

import pygame 
import sys 
import pygame.sprite as sprite 

theClock = pygame.time.Clock() 

background = pygame.image.load('background.gif') 

background_size = background.get_size() 
background_rect = background.get_rect() 
screen = pygame.display.set_mode(background_size) 
x = 0 
y = 0 
w,h = background_size 
running = True 

while running: 
    screen.blit(background,background_rect) 
    pygame.display.update() 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      running = False 
    if(y > h): 
     y = 0 
    else: 
     y += 5 
    screen.blit(background,(x,y)) 
    pygame.display.flip() 
    pygame.display.update() 
    theClock.tick(10) 
+1

你能描述一下當你現在運行你的代碼時會發生什麼,以及它與你希望發生的事情有何不同? –

+0

背景只是向下滾動,但它填補了整個屏幕它只是留下一個靜態背景 –

回答

3

這裏就是我會做:

BLIT與背景圖像表面兩次一個在(0,0),另一個在(0, - img.height),然後將它們移動當它們中的任何一個都位於pos(0,img.heigth)時,它再次位於pos(0, - img.height)。

import pygame 
import sys 
import pygame.sprite as sprite 

theClock = pygame.time.Clock() 

background = pygame.image.load('background.gif') 

background_size = background.get_size() 
background_rect = background.get_rect() 
screen = pygame.display.set_mode(background_size) 
w,h = background_size 
x = 0 
y = 0 

x1 = 0 
y1 = -h 

running = True 

while running: 
    screen.blit(background,background_rect) 
    pygame.display.update() 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      running = False 
    y1 += 5 
    y += 5 
    screen.blit(background,(x,y)) 
    screen.blit(background,(x1,y1)) 
    if y > h: 
     y = -h 
    if y1 > h: 
     y1 = -h 
    pygame.display.flip() 
    pygame.display.update() 
    theClock.tick(10) 
+0

只是把它包裝成一個功能,它將是完美的 –