An eventful day

Events are very important in Ophelia’s structure, because they are our way to ensure that clients run synchronously. If we run all the game code in response to events, then all clients will be in sync as long as no event message in lost on the network. But in order to code a whole game in the form of event triggers we have to place requirements on the event system. It has to be flexible and expansive, allowing users to listen to all kinds of events, and also define their own. Let’s take a look at how this is implemented in Ophelia.

There are two types of events in Ophelia; global and local events. Global events are game-wide, when they occur, it affects all objects. To listen to a global events, we simply register a callback function to the desired event and that function will be called when the event triggers.
Local events meanwhile, are events that only happen to one object, for example, an object being removed from the stage. To listen to these events, we have to register our callback on the object, as each object will contain their own list of callbacks and trigger them independently. Note that we can still register any function to be a callback for a local event, it doesn’t have to be related to the object in any way.

Java script permits us a very simple implementation of these concepts, as seen below. In this example, ‘event’ is a string used to represent the event, such as “onUpdate”.

var Events = {

	callbacks : {},

	// Register a function to be called 
	// when the event occurs
	registerCallback : function(event, callback){

		Events.callbacks[event].push(callback);
	},

	// Deregister a function to no longer be
	// called when the event occurs
	deregisterCallback : function(event, callback){

		var i = Events.callbacks[event].indexOf(callback);

		Events.callbacks[event].splice(i, 1);
	},

	// Trigger an event, calling all callbacks
	triggerEvent : function(event, eventData){

		var len = Events.callbacks[event].length;

		for(var i = 0; i < len; i++){

			Events.callbacks[event][i](eventData);
		}
	},
	
	// Register a new event, this must be done
	// before callbacks can be registered on it
	registerEvent : function(eventName){

		Events.callbacks[eventName] = [];
	}

};

This design relies on two key concepts in Javascript. Firstly, functions can be saved in an array and executed as we iterate over this array. Secondly, properties can be defined on an object during runtime, letting us define new events dynamically.

Be Sociable, Share!

Published by

Albert Öhrling

Studies computer science in Skellefteå, at Lulea University of Technology.

Leave a Reply

Your email address will not be published. Required fields are marked *