Pygame 中的计时器

Timer in Pygame

我是 Python 的新手,我正在尝试在这个游戏中设置一个计时器...其他一切都很好,但这个计时器令人头疼。 我只会 post 与计时器相关的部分,以使其更容易。

frame_count = 0
second = 0
minute = 5
hour = 1
time = "1 5. 0" 

然后在我的主循环中。

font = pygame.font.SysFont('DS-Digital', 50, False, False)
text = font.render(time,True,red)
display.blit(text, [302, 50]) 

frame_count += 1  

if frame_count == 60:
    frame_count = 0
    second -= 1
elif second == 0:
    second = 9
    minute -= 1
elif minute == 0:
    minute = 9
    hour -= 1
elif second == 0 and minute == 0 and hour == 0:
    second = 0
    minute = 0
    hour = 0

hour = time[0]
minute = time[2]
second = time[5]  

clock.tick(60)

这让我返回了错误类型的错误,但我尝试转换为 int,反之亦然...真令人沮丧...

我看了很多例子,但大多数例子都是实际的分钟和秒。

我需要我的正确数字从 9 到 0 倒计时然后减去中间数字等等。

删除这些行:

hour = time[0]
minute = time[2]
second = time[5]

没有它们应该也能正常工作。然后问你想用它们做什么

当您将时间中的元素分配给时、分、秒变量时,将它们转换为 int,如下所示:

hour = int(time[0])
minute = int(time[2]
second = int(time[5])

如果这是你的整个代码,那么你没有导入 pygame。 (import pygame) 在开头,你应该循环它,例如:

import pygame
while True:
    ...
    Your code
    ...

请详细说明你的问题,我看到你应该使用 if insted of elif 因为一旦它达到 1 1 0 它将变成 1 0 9 然后在两帧中变成 0 9 9。

elif second == 0 and minute == 0 and hour == 0:
    second = 0
    minute = 0
    hour = 0

这真的没有意义,就像你计算一样 如果我有 a = 0 然后做 a = 0 如果你知道我的意思(它什么都不做)。

编辑: 有工作代码,您可以编辑它并用它替换旧代码。

import pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))
red = (255, 0, 0)
bg_color = (0, 0, 0)

frame_count = 0
time = "1 5. 0"

while True:
    pygame.time.Clock().tick(60)
    frame_count += 1

    hour = int(time[0])
    minute = int(time[2])
    second = int(time[5])

    if second > 0 and frame_count == 20:
        frame_count = 0
        second -= 1
    if second == 0 and minute > 0 and frame_count == 20:
        frame_count = 0
        second = 9
        minute -= 1
    if minute == 0 and hour > 0 and frame_count == 20:
        frame_count = 0
        minute = 9
        second = 9
        hour -= 1

    time = str(hour) + " " + str(minute) + ". " + str(second)

    font = pygame.font.SysFont('DS-Digital', 50, False, False)
    text = font.render(time, True, red)
    screen.fill(bg_color)
    screen.blit(text, (302, 50)) 

    pygame.display.update()

我很确定有更简单的解决方案或更 pythonic 的解决方案,但它有效,这是最重要的。

这是我的解决方案,用于在每次迭代结束时休眠以获得所需更新率的剩余时间的简单方法

from timeit import default_timer as timer
from time import sleep as sleep

class loop_timer():
    """ simple game loop timer that sleeps for leftover time (if any) at end of each iteration"""
    LOG_INTERVAL_SEC=10
    def __init__(self, rate_hz:float):
        ''' :param rate_hz: the target loop rate'''
        self.rate_hz=rate_hz
        self.start_loop()
        self.loop_counter=0
        self.last_log_time=0

    def start_loop(self):
        """ can be called to initialize the timer"""
        self.last_iteration_start_time=timer()

    def sleep_leftover_time(self):
        """ call at start or end of each iteration """
        now=timer()
        max_sleep=1./self.rate_hz
        leftover_time=max_sleep-(now-self.last_iteration_start_time)
        if leftover_time>0:
            sleep(leftover_time)
        self.start_loop()
        self.loop_counter+=1
        if now-self.last_log_time>self.LOG_INTERVAL_SEC:
            self.last_log_time=now
            if leftover_time>0:
                print('loop_timer slept for {:.1f}ms leftover time for desired loop interval {:.1f}ms'.format(leftover_time*1000,max_sleep*1000))
            else:
                print('loop_timer cannot achieve desired rate {}Hz, time ran over by {}ms compared with allowed time {}ms'.format(self.rate_hz, -leftover_time*1000, max_sleep*1000))

这样使用

    looper=loop_timer(MODEL_UPDATE_RATE_HZ)
    while not self.exit:
       # do your stuff here

        try:
            looper.sleep_leftover_time()
        except KeyboardInterrupt:
            logger.info('KeyboardInterrupt, stopping')
            self.exit=True
            continue