弹跳球不会回来

时间:2019-03-05 11:02:01

标签: python pygame

import pygame

pygame.init()
width = 400
hight = 600
screen = pygame.display.set_mode((width, hight))
pygame.display.set_caption("Engine")
dot = pygame.image.load("KreisSchwarz.png")
clock = pygame.time.Clock()
running = True
WHITE = (255, 255, 255)

# Set (x, y) for Dot
def updateDot(x, y):
    screen.blit(dot, (x, y))

# Display Dot at (x, y)
def update(fps=30):
    screen.fill(WHITE)
    updateDot(x, y)
    pygame.display.flip()
    return clock.tick(fps)

# Quit if User closes the window
def evHandler():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            running = False

yKoords = []
(x, y) = (300, 200)
t = 1 # time variable
a = 2 # acceleration constant
tol = 40 # tolerance
i = 0 # just some iterator

# MAIN LOOP
while running:
    evHandler()
    update()
    y += a * (t ^ 2)
    t += 1
    yKoords.append(int(y))
    i += 1

    if (y < (hight + tol)) and (y > (hight - tol)):
        y = 580
        yKoords.reverse()
        update()

        for q in range(i):
            evHandler()
            y = yKoords[q]
            update()
            if q == i - 1: # Because i didn't write the Part for the Dot coming back down
                running = False

这是我的球加速然后跳回的代码。 我的问题是,直到if语句,代码才能正常工作。那里,程序仅显示yKoords中最后一个球,并等待for循环结束。如果我删除了for循环,则球会显示为y = 580并停止,但这没问题。

请帮助我不知道这是怎么回事。

1 个答案:

答案 0 :(得分:0)

不要在主循环中执行单独的过程循环。

当球在地面上反弹(abs(y - hight))或球到达顶部(t == 0)时,反转方向就足够了。

direction = 1
while running:
    evHandler()
    update()
    y += (a * (t ^ 2)) * direction
    t += direction

    if abs(y - hight) < tol:
        y = 580
        t -= 1
        direction *= -1
    elif t == 0:
        direction *= -1