Pygame球包裹小故障

时间:2017-06-21 17:46:43

标签: python pygame wrapping

我正在尝试用pygame制作一个程序,随机包裹或反弹沙滩球的图像。弹跳起作用,但当它试图包裹球时,球沿着边缘发生故障然后消失。我检查了x和y位置,它消失后仍然在移动。这是代码:

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 个答案:

答案 0 :(得分:1)

if movement == "wrap"区块中,一旦你改变了球的位置,你还应该添加代码以将球带入窗口,即{{1}这样的线不够。让我来讨论你的代码失败的情况:例如,如果球击中窗口的右侧,你的代码会告诉你将球的x坐标设置为-90。然后,在下一个if块(x = -90)中,您的代码生成if x < 0。此外,在while循环的下一次迭代中,您的代码可能会选择反弹并检测自x = screen.get_width()以来(因为球仍在移动),x > screen.get_width()应该反转。这使球落入陷阱。

基本上,您的代码对于弹跳或包装应考虑的内容感到困惑。但是,如果球来自窗口内而不是来自外部,那么这些任何一个都应该发生。但是你的代码会执行这些操作,即使是来自外部的球,这种情况发生在你&#34; put&#34;将球送到窗户的另一侧进行包裹。弹跳是正确的,因为在这种情况下,球实际上从未离开窗口。

所以你应该这样做:

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"