Events - GameDevWeek/CodeBase GitHub Wiki

Events, also known as Signals in other libraries, are a way of communicating things between systems without these systems having to know about each other. It's basically a listener pattern.

Use Events for everything that must be communicated, like:

  • Death of an entity
  • Score increase
  • Level End
  • Sound to be played

These Events can either notify that something happened or cause something to happen. ("Hey, the player died" vs "Play this sound please") It is important that these events always contain all the data required to handle them.

Basic template:

package de.hochschuletrier.gdw.ws1516.events;

import com.badlogic.gdx.utils.SnapshotArray;

public class TestEvent { //TODO: change class name (Naming convention: <Name>Event)

    public static interface Listener {

        //TODO: change method name: (Naming convention: on<ClassName>
        void onTestEvent(String message); //TODO: change parameters as needed
    }

    private static final SnapshotArray<Listener> listeners = new SnapshotArray<Listener>();

    public static void emit(String message) { //TODO:  change parameters
        Object[] items = listeners.begin();
        for (int i = 0, n = listeners.size; i < n; i++) {
            ((Listener) items[i]).onTestEvent(message); //TODO: change method name and parameters
        }
        listeners.end();
    }

    public static void register(Listener listener) {
        listeners.add(listener);
    }

    public static void unregister(Listener listener) {
        listeners.removeValue(listener, true);
    }

    public static void unregisterAll() {
        listeners.clear();
    }

}

Create one of these classes per event. The parts that you need to change are marked with comments. the rest stays as it is. After creating such a class, you can emit an event like this:

TestEvent.emit("message");

And of course, you can add and remove listeners using TestEvent.register/unregister

Example SoundEvent

In this multiplayer (network) game we will examine how a sound would be played.

  • On the server something explodes.
  • After the explosion is triggered, SoundEvent.emit("explosion") is called, but the sound is not actually played here.
  • The event gets catched by two listeners on the server:
    • The AudioSystem, which gets the sound by name and plays it.
    • The ServerSystem, which relays the message to a client. (using a string for the parameter)
  • When the client receives the message, it calls SoundEvent.emit(datagram.soundName)
  • On the client, there is only one listener:
    • The AudioSystem, which gets the sound by name and plays it.

As you can see, the AudioSystem can be used on both client and server to play the sound. Even tho the explosion code never ran on the client, the sound was played.

Of course, the above example is simplified.. you might want to extend it with a position for the sound, a volume or stuff like that.

⚠️ **GitHub.com Fallback** ⚠️