暂停时间。时间流程

时间:2017-06-02 21:43:16

标签: python pygame pygame-clock

我使用Python和Pygame制作游戏,并且我使用time.time来定时用户浏览关卡。但是,我也有一个暂停菜单。当暂停菜单打开时,我怎么能这样做,time.time不会继续?

1 个答案:

答案 0 :(得分: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()