Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 41 ยท Window, Loop and Events

Custom Events and Timers

Create your own Pygame events with custom_type and USEREVENT, post them to the queue, carry data in attributes, and use set_timer for spawning enemies and repeating actions.

Pygame's built-in events cover input and the window, but games have their own happenings: an enemy spawned, the player died, a level finished, a power-up wore off. You can express all of those as custom events. They travel through the same queue as keyboard and mouse events, so one for loop handles everything, and parts of your game can talk to each other without knowing about each other.

Combined with pygame.time.set_timer, custom events also give you easy repeating actions.

Defining a custom event type

Event types are integers. The numbers from pygame.USEREVENT upward are reserved for you. The recommended way to get a unique one is pygame.event.custom_type():

Python
SPAWN_ENEMY = pygame.event.custom_type()
GAME_OVER = pygame.event.custom_type()

Each call returns a new unused number, so two modules can never collide. The older style also works:

Python
SPAWN_ENEMY = pygame.USEREVENT + 1
GAME_OVER = pygame.USEREVENT + 2

Just remember that every number must be unique and USEREVENT + 1, + 2... must stay below pygame.NUMEVENTS.

Posting events

Python
event = pygame.event.Event(GAME_OVER, score=1200, reason="out of lives")
pygame.event.post(event)

Keyword arguments become attributes. Handle it later in the loop like any other:

Python
for event in pygame.event.get():
    if event.type == GAME_OVER:
        show_game_over(event.score, event.reason)

Why not just call show_game_over() immediately? Because posting decouples the code that detects the situation from the code that reacts to it. A collision function posts PLAYER_HIT; the sound system, the score display and the camera shake each listen for it separately.

Note: Posting needs the video system, which this site's browser runner does not have. The runnable examples below use a plain Python queue with the same Event objects, which behaves the same way for the logic we want to learn.

Try it: custom types and attributes

You can create custom event types and events anywhere. This shows that each type is unique and that data travels with the event.

Python Custom event types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Timers with set_timer

Python
SPAWN_ENEMY = pygame.event.custom_type()
pygame.time.set_timer(SPAWN_ENEMY, 1500)        # post SPAWN_ENEMY every 1.5 seconds

That is the entire setup. Every 1500 ms Pygame appends a SPAWN_ENEMY event to the queue, and your loop reacts:

Python
for event in pygame.event.get():
    if event.type == SPAWN_ENEMY:
        enemies.add(Enemy())

Variations:

Python
pygame.time.set_timer(SPAWN_ENEMY, 1500, loops=3)      # fire only three times (pygame 2)
pygame.time.set_timer(SPAWN_ENEMY, 0)                  # cancel the timer
pygame.time.set_timer(pygame.event.Event(SPAWN_ENEMY, kind="bat"), 1000)   # carry data

Setting a new timer for the same event type replaces the old one, which makes "faster spawns as the level rises" simple: call set_timer again with a smaller interval.

Try it: simulating timers

The following stand-in implements a miniature set_timer that works on a pretend clock. It shows the logic of a repeating timer, a limited loops timer and cancelling, and delivers events through a deque just like the real queue.

Python Stand-in: a tiny set_timer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You see three BLINK events then silence, and SPAWN events stop when the timer is cancelled.

A realistic pattern: spawning and difficulty

Python
SPAWN_ENEMY = pygame.event.custom_type()
LEVEL_UP = pygame.event.custom_type()

spawn_interval = 2000
pygame.time.set_timer(SPAWN_ENEMY, spawn_interval)
pygame.time.set_timer(LEVEL_UP, 20_000)

for event in pygame.event.get():
    if event.type == SPAWN_ENEMY:
        spawn_enemy()
    elif event.type == LEVEL_UP:
        spawn_interval = max(400, int(spawn_interval * 0.8))
        pygame.time.set_timer(SPAWN_ENEMY, spawn_interval)   # replaces the old timer

Every 20 seconds enemies appear 20 percent faster, but never faster than every 400 ms.

Timers versus timestamps

Both work. Use set_timer when something should happen regularly or once after a delay and you want the logic inside the normal event loop. Use get_ticks() timestamps (see Clock and Time) when you need to ask "has enough time passed?" at an arbitrary moment, such as a cooldown checked when the player presses a key. One important caveat: timers keep ticking while your game is paused, so cancel or re-arm them when you pause.

Common mistakes

  • Reusing the same number for two event types.
  • Forgetting to handle the event: the timer posts but nothing reacts.
  • Posting very frequent events (every 1 ms) and flooding the queue.
  • Expecting precise timing: events are delivered at the next event.get(), so the accuracy is about one frame.
  • Comparing event.type == "SPAWN" with a string: types are integers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the recommended way to create a unique custom event type?

    custom_type() hands out unused numbers, so event types never collide.
  2. 2. How do you attach data to a custom event?

    pygame.event.Event(GAME_OVER, score=100) stores score as an attribute of the event.
  3. 3. How do you cancel a timer started with set_timer?

    An interval of 0 turns that event's timer off.
  4. 4. What happens when you call set_timer again for the same event type?

    Each event type has at most one timer, so a new call replaces the previous one.

Summary

  • Custom events carry your own game happenings through the normal queue.
  • Use pygame.event.custom_type() and pass data as keyword arguments.
  • pygame.event.post() adds an event; set_timer(type, ms, loops=0) posts it repeatedly.
  • set_timer(type, 0) cancels; a new call replaces an old timer.
  • Posting decouples detecting something from reacting to it.

Next: Keyboard and Mouse Input