2013-07-10 92 views
0

你好,我是相當新的與pygame的編程和我有這樣的代碼:爲什麼有一個以上的球,我該如何解決?

import sys, pygame 

pygame.init() 
screen = pygame.display.set_mode((800, 368)) 
background = pygame.image.load("background.png") 
background.convert() 
screen.blit(background, (0, 0)) 

speed = [1, 1] 
width = 800 
height = 368 

ball = pygame.image.load("ball.bmp") 
ballrect = ball.get_rect() 
player1 = pygame.image.load("player1.png") 
player1rect = player1.get_rect() 

while 1: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      sys.exit()    

    ballrect = ballrect.move(speed) 
    if ballrect.left < 0 or ballrect.right > width: 
     speed[0] = -speed[0] 
    if ballrect.top < 0 or ballrect.bottom > height: 
     speed[1] = -speed[1] 

    screen.blit(ball, ballrect) 
    screen.blit(player1, player1rect) 
    pygame.display.update() 

但是當我運行它,總會有太多的球,應該只有一個球。並且出現越來越多的球。

+3

您是否正在清除新的圖像? –

+0

最適合你的選擇是使用一個具有__del__方法的類 –

+0

我不是blitting – user2565140

回答

1

Fredrik Håård是正確的重新繪製背景。

screen充當圖像,當您撥打screen.blit()時,您將繪製該圖像的一部分。當while 1:循環重複時,您的圖像上已經有一個或多個球的副本,並且您的當前代碼只是將球的另一個圖像繪製到screen上。

您可以在移動球之前繪製背景,從而避免添加一個新變量來保存之前的球位置。

... 
while 1: 
for event in pygame.event.get(): 
    if event.type == pygame.QUIT: 
     sys.exit() 

    screen.blit(background, ballrect, ballrect) #redraw background over old ball location 
    ballrect = ballrect.move(speed) 
    if ballrect.left < 0 or ballrect.right > width: 
     speed[0] = -speed[0] 
    if ballrect.top < 0 or ballrect.bottom > height: 
     speed[1] = -speed[1] 

    screen.blit(ball, ballrect) 
    screen.blit(player1, player1rect) 
    pygame.display.update() 

或者,可以重建整個screen每次,通過上文screen.blit(background, (0, 0)),這確保了背景是爲每個「幀」是正確的,但是顯著較慢替換screen.blit(background, ballrect, ballrect)

我的首選方法是注意您可以通過pygame.display.update()矩形列表,這使得回調更快。請確保在進入while循環之前進行初始的全屏顯示更新:

... 
pygame.display.update() 

while 1: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      sys.exit() 

    old_ballrect = ballrect 
    screen.blit(background, old_ballrect, old_ballrect) #redraw background over old ball location 
    ballrect = ballrect.move(speed) 
    if ballrect.left < 0 or ballrect.right > width: 
     speed[0] = -speed[0] 
    if ballrect.top < 0 or ballrect.bottom > height: 
     speed[1] = -speed[1] 

    screen.blit(ball, ballrect) 
    screen.blit(player1, player1rect) 
    pygame.display.update([old_ballrect, ballrect]) 
1

不是作爲一個專家Pygame的,我想你需要做類似

new_ball_rect = ballrect.move(speed) 
... 
screen.blit(background, ballrect, ballrect) #redraw background over old ball location 
screen.blit(ball, new_ball_rect) 

重新畫過老球圖片的背景。

相關問題