I usually implement a state-machine similar to this:
StateMachine
+ changeState(State)
+ getCurrentState()
+ update()
State
+ enter(StateMachine)
+ update(StateMachine)
+ exit()
When a state becomes the active state, the StateMachine
calls the enter
method. The StateMachine
continiously calls update
on the active state. When the state changes, exit
will be called on the currently active state. The StateMachine
passes itself as parameter to the enter
and update
methods, so that the State can initiate a state-change by itself.
Here's a pseudo-code example.
StateMachine:
// example for the StateMachine
Game implements StateMachine
{
void changeState(State newState){
if(currentState){
currentState.exit();
}
currentState = newState;
if(currentState){
currentState.enter(this);
}
}
State getCurrentState(){
return currentState;
}
void update(){
if(currentState){
currentState.update(this);
}
}
}
Example State:
// example for a state implementation
IntroState implements State
{
void enter(StateMachine sm){
// start the intro
}
void update(StateMachine sm){
if(introComplete){
// change the state!
sm.changeState(new GameState());
} else {
// play the intro
}
}
void exit(){
// nothing to do.. maybe free some stuff?
}
}
Main:
// the main method that starts everything up..
main(){
Game game = new Game();
game.changeState(new IntroState());
while(runGame){
game.update();
}
}
This architecture doesn't need switch
or lengthy if
statements. It's also really easy to change the flow of the states or add in new states. Imagine you wanted to start the MainMenuState
after the IntroState
? Change one line to: sm.changeState(new MainMenuState());
. Then in the MenuState
you could branch into whatever State
you want, depending on which buttons have been pressed etc.