Event Handling for Java Game Engine

I am writing a small game engine in Java and I want to know how to optimize event handling.

For event handling I have a class EventManager

, here you can register EventHandler

( EventHandler

is just a flag interface). EventManager

loops through all the methods EventHandler

, and when there is an annotated method @EventCallback

and it has exactly one parameter with a type that extends Event

, it adds that method to Map: Map<Class<? extends Event>, Set<Callback>>

(a Callback

just saves Method

that too Object

, so it Method

can be called later).

What I like about this kind of event handling is that you can name your handler methods, but you want, and you can handle different events in the same class without having to implement many interfaces.

The event handling class will look like this:

class ExampleHandler implements EventHandler {

    ExampleHandler(Game game) {
       game.getEventManager().registerHandler(this);
    }

    @EventCallback
    public void exampleKeyCallback(KeyPressEvent evt) {
        //I only care about key-pressing, not key-releasing in this class
        System.out.println(evt.getKey() + " was pressed");  
    }

    @EventCallback
    public void i_can_name_this_method_however_i_want(PlayerDeathEvent evt) {
        System.out.println(evt.getPlayer().getName() + " died");
    }

}

      

For example, when my player dies, it will send PlayerDeathEvent

to EventManager

:

//Inside the player-class
public void update() {
   if (health <= 0) {
      getGame().getEventHandler().fireEvent(new PlayerDeathEvent(this));
   }
}

      

but EventHandler

will call all callbacks for this Event

:

//Inside the eventmanager-class

private Map<Class<? extends Event>, Set<Callback>> eventCallbackMap = new HashMap<>();

public void registerEventHandler(EventHandler evt) {
   // find all the @EventCallback-Methods and find the Class-Type of their Paramater, 
   // then add the Method to the Set of Methods for this Class of Events.
   // for example: exampleKeyCallback(KeyPressEvent)
   //    it will be added to the Set for KeyPressEvent.class
}

public void fireEvent(Event evt) {
   Set<Callback> callbacks = eventCallbackMap.get(evt.getClass());

   for (Callback callback : callbacks) {
      callback.invoke(evt);
   }
}

      

Which calls i_can_name_this_method_however_i_want

using PlayerDeathEvent

and prints "*Player-Name* died"

to the console.

I want to know if this is a good way to handle events and if it will be fast enough to handle events in the game or if I have to change it. And if I need to change it, how can I make it better?

+3


source to share





All Articles