Game Development Reference
In-Depth Information
We also add a property called
LevelSelected
to the
LevelMenuState
class. This property
only has a
get
part, and it goes through all the
LevelButton
instances and returns the
level index belonging to the first button that was pressed. If the player did not press
any button, the property returns minus one. In order to do that, we use a casting trick.
We walk through the list of game objects and cast every one of them to a
LevelButton
instance using
as
.Ifthe
as
operator returns
null
, we ignore the object. Otherwise,
we check if the level button was pressed and if so, we return its level index. The
whole property is given as follows:
public int
LevelSelected
{
get
{
foreach
(GameObject obj
in this
.Objects)
{
LevelButton levelButton = obj
as
LevelButton;
if
(levelButton !=
null
&& levelButton.Pressed)
return
levelButton.LevelIndex;
}
return
−
1;
}
}
We can then use this property in the
HandleInput
method:
−
if
(LevelSelected !=
1)
{
// start the level
}
As you can see, adding different states to a game and switching between them
is not very hard, as long as you think about the design of the software beforehand.
By thinking beforehand about which classes are needed and how the functionality
of your game should be split up between them, you can save yourself a lot of time
later on. In the next chapter, we are going to further extend this example by reading
the levels and their status from a text file.
21.5 What You Have Learned
In this chapter, you have learned:
•
how to define different game states using a game state manager;
•
how to switch between game states depending on the player's actions.