如何解决计数器闪烁问题

时间:2019-06-15 21:23:15

标签: python pygame

我正在创建一个非常简单的游戏来尝试轻松进行游戏,但是很早就遇到了问题。

我尝试在更新计时器的位置重新定位,但它只是一直闪烁。

def update_timer():
    global timer, timerrect
    # make timer text
    displaytext(f"{counter}", 50, 50)
    # dispay timer
    pygame.display.flip()
    return timer, timerrect

def displaytext(text, a, b):
    x = font.render(text, True, BLACK, WHITE)
    xrect = x.get_rect()
    xrect.center = (a, b)
    screen.blit(x, xrect)
    pygame.display.flip()

for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.USEREVENT:
            counter-=1
            update_timer()

    # not-so-elegant displaying of timer
    try:
        screen.blit(timer, timerrect)
        pygame.display.flip()
    except:
        pygame.display.flip()

    # some more code here   

    # draw all sprites
    all_sprites.draw(screen)

    # fps
    clock.tick(60)


    # update screen
    pygame.display.flip()

正如我所说,计时器一直在闪烁。我希望它不会诱发癫痫发作。

1 个答案:

答案 0 :(得分:2)

在大多数情况下,当Pygame中的某些事物闪烁时,有一个原因:您每帧多次呼叫pygame.display.flip()

您应该删除对pygame.display.flip()的所有呼叫,但主循环中的呼叫(已注释# update screen的呼叫)除外。这意味着显示每帧仅更新一次。

如果还有其他flip个屏幕,屏幕将自动更新,并且某些帧可能不会显示计时器。

此外,如果您删除了额外的update_timer,则您的flip函数也可以正常工作。然后,您将不需要尝试调试此问题时使用的“不太优雅”的代码。

相关问题