2017-06-21 73 views
1

我想用pygame製作一個隨機包裹或反彈沙灘球圖像的程序。彈跳效果很好,但是當它試圖包裹球時,沿着邊緣的球毛刺會消失。消失後我檢查了x和y的位置,它仍然在移動。這是代碼:Pygame球包裝故障

import pygame, sys, random 
pygame.init() 
screen = pygame.display.set_mode([640, 480]) 
screen.fill([255,255,255]) 
ball = pygame.image.load('beach_ball.png') 
x = 50 
y = 50 
xspeed = 10 
yspeed = 10 
running = True 
while running: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      running = False 
    movement = random.choice(["wrap", "bounce"]) 
    pygame.time.delay(20) 
    pygame.draw.rect(screen, [255,255,255], [x, y, 90, 90], 0) 
    x = x + xspeed 
    y = y + yspeed 
    if movement == "bounce": 
     if x > screen.get_width() - 90 or x < 0: 
      xspeed = -xspeed 
     if y > screen.get_height() - 90 or y <0: 
      yspeed = -yspeed 
    if movement == "wrap": 
     if x > screen.get_width(): 
      x = -90 
     if x < 0: 
      x = screen.get_width() 
     if y > screen.get_height(): 
      y = -90 
     if y < 0: 
      y = screen.get_width() 
    screen.blit(ball, [x, y]) 
    pygame.display.flip() 

pygame.quit() 

回答

1

if movement == "wrap"塊,一旦你改變球的現在的位置,你也應該添加代碼,使球在窗口,即,就像x = -90線不足夠。讓我來討論一下你的代碼失敗的情況:例如,如果球擊中了窗口的右側,你的代碼會告訴將球的x座標設置爲-90。然後,在下一個if塊(if x < 0)中,您的代碼將生成x = screen.get_width()。此外,在while循環的下一次迭代中,您的代碼可能會選擇反彈並檢測到因爲x > screen.get_width()(因爲球仍在移動),所以應該顛倒xspeed。這使得球落入陷阱。

基本上,你的代碼對於彈跳或包裝應該考慮什麼感到困惑。但是其中任何一種都應該只發生在球從內部出現在窗口內而不是外部。但是,即使球從外面出現,您的代碼也會執行這些動作,當您將球「放」到窗口的另一側進行包裝時會發生這種情況。反彈的發生是正確的,因爲在那種情況下,球從未真正離開窗戶。

所以,你應該這樣做:

if movement == "wrap": 
    if x > screen.get_width() and xspeed > 0: #ball coming from within the window 
     x = -90 
    if x < 0 and xspeed < 0: 
     x = screen.get_width() 
    if y > screen.get_height() and yspeed > 0: 
     y = -90 
    if y < 0 and yspeed < 0: 
     y = screen.get_width() 

同樣要在if movement == "bounce"塊進行了包裝才能正常工作:

if movement == "bounce": 
    if (x > screen.get_width() - 90 and xspeed > 0) or (x < 0 and xspeed < 0): 
     xspeed = -xspeed 
    if (y > screen.get_height() - 90 and yspeed > 0) or (y < 0 and yspeed < 0): 
     yspeed = -yspeed