Game Development Reference
In-Depth Information
21.3 Adding States and Switching Between Them
Now that we have our game state manager, we can start adding different states to
it. A very basic game state is the title menu state. In the PenguinPairs3 example, we
added a class TitleMenuState to the project that represents this state. Since this state
contains a couple of different game objects, we let it inherit from the GameObjectList
class. In the constructor of this class, we add the game objects that are required
for this state: a background, and three buttons. We reuse the Button class that we
developed earlier for the Jewel Jam game.
Because we need to do something when a button is pressed, we have to override
the HandleInput method. In that method, we check for each of the buttons if they are
pressed, and if so, we switch to another state. For instance, if the player presses the
'play game' button, we need to switch to the level menu:
if (playButton.Pressed)
PenguinPairs.GameStateManager.SwitchTo("levelMenu");
We add similar alternatives for the other two buttons. Now our title menu state is
basically done (for the complete class, see Listing 21.2 ). In the PenguinPairs class,
the only thing we need to do is make an instance of TitleMenuState and add it to the
game state manager. We also do this for all the other states that are in the game.
After that we set the current state to be the title menu, so that the player sees the title
menu when the game starts:
gameStateManager.AddGameState("titleMenu", new TitleMenuState());
gameStateManager.AddGameState("optionsMenu", new OptionsMenuState());
gameStateManager.AddGameState("levelMenu", new LevelMenuState());
gameStateManager.AddGameState("helpState", new HelpState());
gameStateManager.SwitchTo("titleMenu");
The help and option menu states are done in a similar fashion. In the construc-
tor of the class, we add our game objects to the game world, and we override the
HandleInput method to switch between different states. For example, both the help
and option menu state contain a 'back' button that returns us to the title screen:
public override void HandleInput(InputHelper inputHelper)
{
base .HandleInput(inputHelper);
if (backButton.Pressed)
PenguinPairs.GameStateManager.SwitchTo("titleMenu");
}
21.4 The Level Menu State
A slightly more complicated game state is the level menu. We want the player to be
able to select a level from a grid of level buttons. Although we will not implement
Search WWH ::




Custom Search