Pygame球包装故障
问题描述:
我想用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()
答
内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