微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带 PyGame 的秒表

如何解决带 PyGame 的秒表

大家好!我想用 pygame 创建秒表。我看到了这个代码

import pygame as pg

pg.init()
screen = pg.display.set_mode((400,650))
clock = pg.time.Clock()
font = pg.font.Font(None,54)
font_color = pg.Color('springgreen')

passed_time = 0
timer_started = False
done = False

while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_SPACE:
                timer_started = not timer_started
                if timer_started:
                    start_time = pg.time.get_ticks()

    if timer_started:
        passed_time = pg.time.get_ticks() - start_time

    screen.fill((30,30,30))
    text = font.render(str(passed_time / 1000),True,font_color)
    screen.blit(text,(50,50))

    pg.display.flip()
    clock.tick(30)

pg.quit()

但是当您按空格键时,计时器会重新启动。我如何打印(在屏幕上)?

解决方法

这是更新后的代码(因为我假设您想在屏幕上打印多个结果,这就是我所做的):

import pygame as pg

pg.init()
screen = pg.display.set_mode((400,650))
clock = pg.time.Clock()
font = pg.font.Font(None,54)
font_color = pg.Color('springgreen')

passed_time = 0
start_time = None
timer_started = False
done = False

results = []

while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_SPACE:
                timer_started = not timer_started
                if timer_started:
                    start_time = pg.time.get_ticks()
                elif not timer_started:
                    results.append(passed_time)
                    if len(results) > 10:
                        results.pop(0)

    if timer_started:
        passed_time = pg.time.get_ticks() - start_time

    screen.fill((30,30,30))
    text = font.render(f'{(passed_time / 1000):.3f}',True,font_color)
    screen.blit(text,(50,50))

    for index,result in enumerate(results):
        text = font.render(f'{(result / 1000):.3f}',font_color)
        screen.blit(text,50 + 54 * (len(results) - index)))

    pg.display.flip()
    clock.tick(30)

pg.quit()

它的工作方式:如果秒表停止,它停止的值将附加到列表中。

然后在代码中读取列表中的每个项目并将其显示在屏幕上。

(50,50 + 54 * (len(results) - index)) 这可确保时间按记录时间的时间顺序显示。

还有这部分:

if len(results) > 10:
    results.pop(0)

确保列表不会被填满。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。