为什么python会跳过这些代码行?

时间:2014-01-30 23:03:34

标签: python pygame

我正在尝试绘制一些pygame圆圈并显示它们,当用户点击一个键时,它会更新这些计数器的位置。当用户按下键时,它将在屏幕上以新位置绘制一个圆圈,但它不显示第一个图像。所以它应该显示一个圆圈,当它们按下一个键时它会改变圆圈的位置。它没有绘制起始圆圈。

第一个圈子(这些圈子没有出现):

#Draw counters using pygame draw line function. These are the default counters on the start position. These don't move.
    countY = 750
    count1 = pygame.draw.circle(window, (black),(150, countY), 25, 0)
    count2 = pygame.draw.circle(window, (black),(250, countY), 25, 0)
    count3 = pygame.draw.circle(window, (255, 255, 255),(450, countY), 25, 0)
    count4 = pygame.draw.circle(window, (255, 255, 255),(550, countY), 25, 0)
    print("Should draw start counters")
    pygame.display.update()

输入密钥后绘制的圆圈:

while game:
    for event in pygame.event.get():
        pygame.event.get()

        #Counter 1 movement
        if event.type == pygame.KEYDOWN and event.key == pygame.K_a:
            diceRoll = random.randint(1, 4)

            window.fill(grey)
            grid()

            count1 = pygame.draw.circle(window, (black),(150, countY - 72 * diceRoll), 25, 0)

1 个答案:

答案 0 :(得分:1)

按下某个键后,用灰色填充背景图层:

if event.type == pygame.KEYDOWN and event.key == pygame.K_a:
    diceRoll = random.randint(1, 4)

    window.fill(grey) # <--- fills the entire surface with a solid color!

并且您不会再画圆圈。

一个简单的解决方法是保留所有圈子的列表,并在每一帧中绘制它们(有更有效的方法,但为了这个问题/答案,让我们保持简单)。

circles = []
countY = 750
circles.append((pygame.color.Color('black'), (150, countY), 25, 0))
circles.append((pygame.color.Color('black'), (250, countY), 25, 0))
circles.append((pygame.color.Color('white'), (450, countY), 25, 0))
circles.append((pygame.color.Color('white'), (550, countY), 25, 0))

while game:
    window.fill(grey)
    for event in pygame.event.get():
        # pygame.event.get() don't call pygame.event.get() twice

        if event.type == pygame.KEYDOWN and event.key == pygame.K_a:
            diceRoll = random.randint(1, 4)
            circles.append((pygame.color.Color('black'), (150, countY - 72 * diceRoll), 25, 0))

    for (color, pos, rad, w) in circles:
        pygame.draw.circle(window, color, pos, rad, w)
    pygame.display.flip()