Handling commands or events that wait for an action to be completed afterwards

Posted by virulent on Game Development See other posts from Game Development or by virulent
Published on 2012-03-24T20:02:20Z Indexed on 2012/03/24 23:40 UTC
Read the original article Hit count: 172

Filed under:
|

Say you have two events: Action1 and Action2. When you receive Action1, you want to store some arbitrary data to be used the next time Action2 rolls around. Optimally, Action1 is normally a command however it can also be other events. The idea is still the same.

The current way I am implementing this is by storing state and then simply checking when Action2 is called if that specific state is there. This is obviously a bit messy and leads to a lot of redundant code. Here is an example of how I am doing that, in pseudocode form (and broken down quite a bit, obviously):

void onAction1(event) {
    Player = event.getPlayer()
    Player.addState("my_action_to_do")
}

void onAction2(event) {
    Player = event.getPlayer()

    if not Player.hasState("my_action_to_do") {
        return
    }

    // Do something
}

When doing this for a lot of other actions it gets somewhat ugly and I wanted to know if there is something I can do to improve upon it.

I was thinking of something like this, which wouldn't require passing data around, but is this also not the right direction?

void onAction1(event) {
   Player = event.getPlayer()
   Player.onAction2(new Runnable() {

       public void run() {
           // Do something
       }

   })
}

If one wanted to take it even further, could you not simply do this?

void onPlayerEnter(event) { // When they join the server
    Player = event.getPlayer()
    Player.onAction1(new Runnable() {

       public void run() {

           // Now wait for action 2
           Player.onAction2(new Runnable() {
               // Do something
           })

       }

    }, true) // TRUE would be to repeat the event,
             // not remove it after it is called.
}

Any input would be wonderful.

© Game Development or respective owner

Related posts about java

Related posts about events