在pygame的页面底部创建一个计时器

2024-07-01 07:41:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始使用pygame,我想做一个简单的游戏。现在我如何在游戏屏幕上添加一个计时器,以秒为单位显示游戏的运行时间

游戏屏幕的图像:

enter image description here

github中的代码:

https://github.com/kidscancode/pygame_tutorials/blob/master/shmup/shmup-11.py


Tags: 代码https图像githubcom游戏屏幕时间
1条回答
网友
1楼 · 发布于 2024-07-01 07:41:49

在pygame中,有几种方法可以获取当前游戏时间

  • 使用time.time()获取两次之间的时差
  • 使用pygame.time.get_ticks()获取自pygame.init()以来的毫秒数

只需添加几行代码即可获得计时器

import time # add this line
....
running = True
start_time = time.time() # game start - add this line
while running:
    ......
    draw_text(screen, str(score), 18, WIDTH / 2, 10)
    draw_text(screen, str(int(time.time() - start_time)), 18, 15, HEIGHT-20) # game timer - add this line
    draw_shield_bar(screen, 5, 5, player.shield)

这里有一个更简单的解决方案,只需要一条新线路

draw_text(screen, str(score), 18, WIDTH / 2, 10)
draw_text(screen, str(int(pygame.time.get_ticks()/1000)), 18, 15, HEIGHT-20) # game timer - add this line
draw_shield_bar(screen, 5, 5, player.shield)

相关问题 更多 >

    热门问题