ARTICLE AD BOX
You cant pause pygame.time.get_ticks() because it is a global clock that constantly measures time since pygame.init() was called.
To implement a pause feature, you must manage a custom game timer that only increments when the game is in a "running" state.
Recommended Approach: Using Delta Time (dt) The cleanest way is to use clock.tick() to calculate the time elapsed since the last frame (dt) and add that to a running total only if the game is not paused.
python import pygame pygame.init() screen = pygame.display.set_mode((800, 600)) clock = pygame.time.Clock() running = True paused = False game_time = 0 # Track total milliseconds spent in-game while running: # Get milliseconds since last frame dt = clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN and event.key == pygame.K_p: paused = not paused if not paused: # Only add elapsed time if not paused game_time += dt # Use game_time for your logic seconds = game_time / 1000 pygame.display.set_caption(f"Elapsed game time: {seconds:.2f}s") screen.fill((0, 0, 0)) pygame.display.flip() pygame.quit()Alternative: Adjusting Start Time If you prefer to use get_ticks() to calculate the time, you must account for the duration of the pause. When you unpause, you need to calculate how long the game was paused and adjust your starting reference point:
Record the start_ticks when the game begins.
When paused: Stop updating your time calculation.
When unpaused: Add the duration of the pause to your start_ticks reference so that the time calculation "jumps" forward by the length of the pause.
Using the dt approach above is generally preferred for game development because it is more robust and prevents complex arithmetic errors when handling multiple pause events.
