1

我用 Python 和 Pygame 制作了一个游戏,我正在使用 time.time 来为用户通过关卡计时。但是,我也有一个暂停菜单。当暂停菜单打开时,我怎么能这样做,time.time 不会继续?

4

1 回答 1

0

我想我会做这样的事情:clock.tick()如果游戏没有暂停,则使用返回的时间来增加每帧的计时器,并且当用户暂停和取消暂停游戏时调用它而不带参数来丢弃过去的时间游戏暂停。

import sys
import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
font = pg.font.Font(None, 30)
timer = 0
dt = 0
paused = False
running = True

while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
        elif event.type == pg.KEYDOWN:
            paused = not paused
            # This is needed to discard the time that
            # passed while the game was paused.
            clock.tick()

    if not paused:
        timer += dt  # Add delta time to increase the timer.

        screen.fill((30, 30, 30))
        txt = font.render(str(round(timer, 2)), True, (90, 120, 40))
        screen.blit(txt, (20, 20))

        pg.display.flip()
        dt = clock.tick(30) / 1000  # dt = time in seconds since last tick.

pg.quit()
sys.exit()
于 2017-06-04T04:02:31.070 回答