PVG
7. Event System — Program Video Games

7. Event System

Every quest completed, every item collected, every cut-scene triggered, is the result of the Event System.

There are various ways to create event systems. In this lesson, we will start by creating a single event queue, and then consider whether we need specialised ones at a later time.

The Fractal Code Cycle Applied to Event System

Recall our fundamental pattern:

Input → Processing → Output

For our event system:

  • Input: Event type, data payload
  • Processing: Depends on event type, and listener
  • Output: Some state change

What Are Event Systems Good For?

Event systems are useful for communication across system boundaries while avoiding tight coupling.

For example, the Quest system may want to update when picking up an item. Rather than hard-coding this into the item pickup code, an event can be fired any the quest system can listen for it, updating the quest.

on_special_gem_pickup :: proc(event: Event) {
    if event.payload.(Item_Pickup_Event_Payload).type == .Item_Special_Gem {
        if quest_is_active(.Gather_Special_Gems) {
            // update the quest
        } else {
            // Start the quest and add to the player's journal
            // Display some text on screen to indicate that
        }
    }
}

// Register the event
event_type_subscribe(.Item_Pickup, on_special_gem_pickup)

Event System in the System Stack

The Event System is unique. It exists outside the stack, and is used as a facilitator of system-to-system communication.

Design Considerations

Due to the unpredictable memory patterns of a typical event system, they should be considered a slow path. That is, any performance critical code should not be utilising the event system and should instead have some bespoke way of doing things.

For example, physics/collisions, particle systems, or player input (to an extent), should have their own custom paths.

Something that has not been added yet are timed events. Events that are "ready" to be processed:

  • At a particular time of day
  • After some time duration has passed

The event system will be expanded when this comes up. With that, will need to have some way of keeping events around until they are ready.

The Big Idea

Events are a way to communicate between systems without coupling them together. Systems only need to know that the event system exists in order to communicate - they don't need to know about each other.