Friday, April 20, 2012

Planning the Observer Pattern

Lets open this one up to all you readers out there. I'm trying to implement the observer pattern into my simulation. What I have is 'players' that travel to different locations (the movement methods have not been created yet, but in theory they move :D) locations are subclassed to 2 different kinds of types, land and water. Land is then divided between 2 continents with each continent having a different set of 'states'. I want my players to be added to the state they enter and leave the one they just left, then get the ownership of the new state. While in this state I want them to be added to observer the 'Zone'. the Zone is a medium for notifications. So, what I was thinking is setting this class as an extender of Observable and then putting different notifications into a strategy pattern through it. For instance, I want it to notify other players that a new player entered and of what 'Faction' (Friendly or enemy). It will also notify of a state being taken over (which will then cause a defending player to attack the attacking player and stop the overtaking.

I think that in theory this is a good idea, but I can't seem to get the classe setup to make the work.

2 comments:

  1. Hey Curtis,

    If I understand correctly, both Players and Zones are observable/observers, such that Zones observe whether players set a flag, and Players observe whether a flag has been set in a zone? Like a chain of notifications so to speak. If this is correct, the pattern should work. When a player enters a zone, you can add the player as an observer of the zone, and add the zone as an observer of the player. Sort of a two-way observer pattern.

    I noticed a few issues with your current status of observer patterns. For one, having defined your own Observer interface might clobber your project into thinking that you want to use that interface and not Java's built-in Observer interface. Two, I see where Players send notifications (when they set a flag), but where do Zones send notifications (by call ownerChanged())?

    As to your bug, it's caused by the Array LOC never being instantiated in the Player constructor..causing the nullpointerexception in Bishop in the method:

    public int[] setLocation(int x, int y) {
    LOC[0] = x; //PROBLEM! LOC not initialized
    LOC[1] = y;
    return LOC;
    }

    As to movement, start basic with arbitrary movement (all players move left or right), and worry about the randomness or AI later. Hope this helps.

    GTF PAUL

    ReplyDelete
    Replies
    1. Also you need a blog about observer pattern recipe.

      Delete