I'm thinking of ways to implement the Observer pattern in a game I'm developing at the moment. I can have a Game World (local map) with Game Objects (player, NPCs, monsters etc...) inside of it. Other Game classes (like quest progression tracker for flagging triggers, location tracker for path finding, or maybe a new map need to be loaded into memory and rendered to show the new area the player just walked into) need to be notified when the player walks into a building, or fires a projectile. Also the input listener needs to be aware of when the user presses a key or clicks the mouse, and somehow transport that information to the rest of the game so that it can allow the appropriate actions to take place.
So I'm stuck at the implementation stage. I know I can use the Observer pattern, and possibly the State pattern as well. I know I'll need a Game World (Subject), Game Objects (Listeners), and Game Events (triggers the Game World to render the changes). However that could be the wrong way to go about it, any suggestions?
BTW, its a 2D JRPG tiling styled game, in the fashion of Zelda, Breadth of Fire, Pokémon, or the older Final Fantasies
Alright I've gone and done an implementation, but ran into a few minor issues, although it seems to be working properly.
public interface WorldListener {
public void OnWorldEvent(WorldEvent e);
}
Above is the Observer that listens to the subject.
public class WorldEvent {
final int WorldObjectMovedEvent = 1;
}
Above is the Event that triggers a notification.
public class World {
static WorldListener listener;
static void addWorldListener(WorldListener wl) {
listener = wl;
}
static void WorldChanged() {
listener.OnWorldEvent(new WorldEvent());
}
}
Above is the subject that only stores one subscriber at the moment, I'll make it into a list once i write a class for another observer, right now, I only have one Observer. There is no need for a list at the moment.
public void OnWorldEvent(WorldEvent e) {
System.out.println("Something has happened in the world");
}
static private void addWorldListener(WorldListener wl) {
World.addWorldListener(wl);
}
The code above goes into the object that is currently acting as an observer, when an event is fired, it triggers the world's WorldChanged()
method, which in turn fires the OnWorldEvent
of any listener.
The problem I have ran into is that I can't move the WorldEvent
, WorldListener
, or World
classes into a separate package under the moniker World.my.game
because of the static reference. So I'm not sure I'm implementing it correctly. Also if there are any suggestions on making this better, or if I'm flat out doing it wrong let me know, as I haven't delved into design patterns yet and this is my first attempt.