1

I making a game with Python and Pygame, and I'm using time.time to time the users going through levels. However, I also have a pause menu. How can I make so when the pause menu is open, time.time won't continue?

Will6316
  • 71
  • 7
  • You don't need to pause `time.time` itself to pause the in-game timer. – user2357112 Jun 02 '17 at 21:55
  • What if you capture the current time and subtract it from the total time, and then when the player resumes the game you start the timer again for the remaining amount? – ATLUS Jun 02 '17 at 22:18

1 Answers1

0

I think I'd do something like this: Use the time that clock.tick() returns to increase a timer each frame if the game is not paused, and when the user pauses and unpauses the game call it without an argument to discard the time that passed while the game was paused.

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()
skrx
  • 19,980
  • 5
  • 34
  • 48