Game Development Reference
In-Depth Information
Inside the constructor, we initially assign
null
to the current game state, since no
game state can be selected yet. We then add a few methods and properties to add
and retrieve game states based on their string identifier. Since these methods are
quite straightforward, we will not discuss the details here, but you can have a look
at the code by opening the
PenguinPairs3
program in the solution belonging to this
chapter.
The main method used for switching between game states is the
SwitchTo
method.
This method takes a string as a parameter and switches to the corresponding game
state. This is the complete method:
public void
SwitchTo(
string
name)
{
if
(gameStates.ContainsKey(name))
currentGameState = gameStates[name];
}
Inside this method, we check if the provided key exists. If it does, we set the current
game state to the state associated with that key.
As you can see, it is relatively easy to check if a dictionary contains a key or not.
What if we wanted to check if a dictionary contains a certain
value
? In that case, we
have to do a search ourselves using the
foreach
-instruction. The kind of object that
foreach
provides while traversing a dictionary is a
KeyValuePair<>
. This type contains
the properties
Key
and
Value
to access the key and value in the pair. Once we find the
current game state, we are done. Suppose that we are looking for the name of the
state
currentGameState
. This piece of code returns the key associated with that game
state:
foreach
(KeyValuePair<
string
, IGameLoopObject> pair
in
gameStates)
{
if
(pair.Value == currentGameState)
return
pair.Key;
}
return
"";
Going back to our game example, we still have to handle the different game loop
methods. This is actually relatively simple. If a game state is currently selected, we
simply call the game loop methods on the game state. For example, the
HandleInput
method is given as follows:
public void
HandleInput(InputHelper inputHelper)
{
if
(currentGameState !=
null
)
currentGameState.HandleInput(inputHelper);
}
We follow a similar procedure for the other game loop methods.
![](Learning-C-by-Programming-Games_images/img-gen1817.png)
![](Learning-C-by-Programming-Games_images/img-gen1818.png)