Pygame 中的倒数计时器

新手上路,请多包涵

我开始使用 pygame,我想做简单的游戏。我需要的元素之一是倒数计时器。我如何在 PyGame 中进行倒计时(例如 10 秒)?

原文由 adamo94 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2k
2 个回答

在此页面上,您会找到所需的内容 http://www.pygame.org/docs/ref/time.html#pygame.time.get_ticks

您在开始倒计时之前下载一次刻度(这可以是游戏中的触发器 - 关键事件,无论如何)。例如:

 start_ticks=pygame.time.get_ticks() #starter tick
while mainloop: # mainloop
    seconds=(pygame.time.get_ticks()-start_ticks)/1000 #calculate how many seconds
    if seconds>10: # if more than 10 seconds close the game
        break
    print (seconds) #print how many seconds

原文由 DanteVoronoi 发布,翻译遵循 CC BY-SA 3.0 许可协议

另一种简单的方法是简单地使用 pygame 的事件系统。

这是一个简单的例子:

 import pygame
pygame.init()
screen = pygame.display.set_mode((128, 128))
clock = pygame.time.Clock()

counter, text = 10, '10'.rjust(3)
pygame.time.set_timer(pygame.USEREVENT, 1000)
font = pygame.font.SysFont('Consolas', 30)

run = True
while run:
    for e in pygame.event.get():
        if e.type == pygame.USEREVENT:
            counter -= 1
            text = str(counter).rjust(3) if counter > 0 else 'boom!'
        if e.type == pygame.QUIT:
            run = False

    screen.fill((255, 255, 255))
    screen.blit(font.render(text, True, (0, 0, 0)), (32, 48))
    pygame.display.flip()
    clock.tick(60)

在此处输入图像描述

原文由 sloth 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题