StateManager

Motivation

You want to adopt the finite state machine pattern because your game has many states and it becoming difficult to maintain.

Description

This is the second half of the finite state machine pattern. This class is the actual proxy for your states. In addition to acting as a proxy for concrete states the state manager facilitates transitioning between different states.

Example

public class StateManager {
    private LinkedList<State> states;
    private State currentState;
    public StateManager() {
        states = new LinkedList<State>();
    }
    public void add(State s) {
        states.add(s);
        if (currentState == null) {
            currentState = s;
            currentState.enter();
        }
    }
    /** Transition to the designated state. */
    public void enter(Object o) {
        for (State s : states) {
            if (s.equals(o)) {
                currentState = s;
                currentState.enter();
            }
        }
    }
    /** Useful if you need to know what state you are currently in. */
    public Object currentState() {
        return currentState;
    }
    public void update(StateBasedGame game, int delta) {
        currentState.update(game, delta);
    }
    public void onCollision(Entity obstacle) {
        currentState.onCollision(obstacle);
    }
    public void render(Graphics g) {
        currentState.render(g);
    }
}
design_pattern/statemanager.txt · Last modified: 2008/10/19 18:45 by aschearer
Back to top
Creative Commons License Valid CSS Recent changes RSS feed Valid XHTML 1.0