To implement an FSM neatly, employ the State design pattern [1].
From a base class state, derive the different states that an object/agent may occupy (e.g. for a Pacman ghost these might be Flee and Chase). The agent is given a state variable that is typed as one of these state objects. Each time the agent's update() method is called, the state is tested to see if its transition conditions are met.
If the transition conditions are met, the state object must indicate to the agent whatever is appropriate as its next state. E.g. if Pacman eats a Power-Up and the ghost is in Chase state, a transition must be made by the ghost to the Flee state. The Chase state must notify the ghost of this desired transition. A disadvantage of this is that the states must be aware of at least one other state (the state to which they transition) introducing dependencies between classes. You might use C++ friend to allow the State objects to gain access to their agent's state variable.
[1] Gamma et al, "Design Patterns, Elements of Reusable Object-Oriented Software", Addison-Wesley, 1995
Sunday, March 21, 2010
Subscribe to:
Post Comments (Atom)
Also, see the "Strategy" design pattern. This might be used as a way to encode the different algorithms that an AI employs as its state is changed.
ReplyDelete