These additional methods are only called when a Miner changes state.
When a state transition occurs, the
Miner::ChangeState method first calls
Exit method of the current state, then it assigns the new state to the cur
rent state, and finishes by calling the
Enter method of the new state (which
is now the current state). I think code is clearer than words in this instance,
so here’s the listing for the
void Miner::ChangeState(State* pNewState)
//make sure both states are valid before attempting to
//call their methods
assert (m_pCurrentState && pNewState);
//call the exit method of the existing state
//change state to the new state
m_pCurrentState = pNewState;
//call the entry method of the new state
Notice how a Miner passes the this pointer to each state, enabling the state
to use the
Miner interface to access any relevant data.
TIP The state design pattern is also useful for structuring the main components
of your game flow. For example, you could have a menu state, a save state, a
paused state, an options state, a run state, etc.
Each of the four possible states a Miner may access are derived from the
State class, giving us these concrete classes: EnterMineAndDigForNugget,
VisitBankAndDepositGold, GoHomeAndSleepTilRested, and QuenchThirst.
Miner::m_pCurrentState pointer is able to point to any of these states.
Update method of Miner is called, it in turn calls the Execute
method of the currently active state with the this pointer as a parameter.
These class relationships may be easier to understand if you examine the
simplified UML class diagram shown in Figure 2.3.
Each concrete state is implemented as a singleton object. This is to
ensure that there is only one instance of each state, which agents share
(those of you unsure of what a singleton is, please read the sidebar on page
58). Using singletons makes the design more efficient because they remove
the need to allocate and deallocate memory every time a state change is
made. This is particularly important if you have many agents sharing a
complex FSM and/or you are developing for a machine with limited
56 | Chapter 2
The West World Project