数字Pygame倒数计时器

时间:2018-01-07 14:53:03

标签: python-3.x timer pygame

我想制作一个倒数计时器,它将使用pygame显示在屏幕上。我试过用这个:

while secs !=0:
    timer = ("time left: {}".format(secs))
    timer_ao = ("time left: {}".format(secs+1))
    display_text((timer_ao),white,(20),(20),medText)
    display_text((timer),black,(20),(20),medText)
    #pygame.display.update()
    time.sleep(1)
    secs = secs-1

然而,它一直干扰我代码的其他部分。

有没有更好的方法来制作计时器?

1 个答案:

答案 0 :(得分:1)

您无法使用whilesleep,因为它会阻止主循环。

您必须使用if secs != 0而不是while secs != 0在主循环中运行它 - mainloop将用作while,并在timepygame.time内使用if {1}}检查是否还剩1秒(1000毫秒)并更改显示时间。

像这样的东西

secs = 10

timer = "time left: {}".format(secs)
timer_ao = "time left: {}".format(secs+1)
previouse_time = pygame.time.get_ticks()

while True: # main loop

    # ... other elements ...

    current_time = pygame.time.get_ticks()

    if secs > 0:
        if previouse_time - current_time == 1000: # 1000ms = 1s
            secs -= 1
            timer = "time left: {}".format(secs)
            timer_ao = "time left: {}".format(secs+1)
            previouse_time = current_time

    display_text(timer_ao, white, 20, 20, medText)
    display_text(timer, black, 20, 20, medText)
    pygame.display.update()

您还可以使用pygame.time.set_timer每1000毫秒创建一个自己的事件,并使用它来更改显示的文本。

SECOND = pygame.USEREVENT

secs = 10

timer = "time left: {}".format(secs)
timer_ao = "time left: {}".format(secs+1)

# start timer
pygame.time.set_timer(SECOND, 1000)

while True: # main loop

    for event in pygame.event.get():

        if event.type == SECOND:
            if secs > 0:
                secs -= 1
                timer = "time left: {}".format(secs)
                timer_ao = "time left: {}".format(secs+1)
                previouse_time = current_time
            else:
                # stop timer
                pygame.time.set_timer(SECOND, 0)

    display_text(timer_ao, white, 20, 20, medText)
    display_text(timer, black, 20, 20, medText)
    pygame.display.update()