Games are full of things that happen on a schedule: an enemy every two seconds, a power-up that lasts five, a 30 second round. Pygame has two tools for this:
pygame.time.set_timer(event, ms)posts an event everymsmilliseconds. Good for repeating things.pygame.time.get_ticks()returns the milliseconds sincepygame.init(). Compare two values for cooldowns and countdowns.
Repeating events: set_timer
A new star appears every half second. The timer keeps running until you stop it:
pygame.time.set_timer(SPAWN, 0) # stop
pygame.time.set_timer(SPAWN, 2000, loops=1) # fire once, in two seconds
pygame.time.set_timer(SPAWN, 250) # restart faster (replaces the old timer)
Each event type has one timer; calling set_timer again with the same type replaces it. pygame.event.custom_type() gives you a new type for each timer, so a game can have one for spawning, one for the clock, one for flashing text.
Cooldowns with get_ticks
A cooldown stops the player from firing too fast. Remember when they last fired and only allow it again after enough milliseconds:
Press Play, click the game and hold Space: shots come out at most every 0.4 seconds, and the cannon turns gray while it reloads.
A countdown
Store when the round ends, and work out what is left each frame:
(left_ms + 999) // 1000 rounds up, so the display shows 10 for the whole first second and reaches 0 only when the time is really up.
Do not sleep
time.sleep(1) or pygame.time.wait(1000) inside the loop pauses everything: no drawing, no input, and after a few seconds the window is reported as not responding. A game waits by checking the time each frame and doing nothing until it has passed. pygame.time.delay() and wait() are for small scripts, not game loops.
Frequently Asked Questions
How do I make a timer in pygame?
Make an event type, SPAWN = pygame.event.custom_type(), and start it: pygame.time.set_timer(SPAWN, 1000). A SPAWN event then arrives in the event loop every 1000 milliseconds.
How do I make a countdown in pygame?
Store the end time, end = pygame.time.get_ticks() + 30000, and each frame compute left = max(0, end - pygame.time.get_ticks()) // 1000 seconds. When it reaches 0 the time is up.
How do I stop a pygame timer?
Call pygame.time.set_timer(EVENT, 0). To fire only once, pass loops=1: pygame.time.set_timer(EVENT, 2000, loops=1).
Can I use time.sleep() in a pygame game?
Not inside the game loop. time.sleep() stops the whole loop, so the window stops drawing and reading input. Use a timer event or compare get_ticks() values instead.