Game Development Reference
In-Depth Information
In the examples you've seen until now, there was always some kind of game world class; it was
called
PainterGameWorld
,
JewelJamGameWorld
, or
PenguinPairsGameWorld
, depending on the game
you were building. Looking at it from the view of game states, each of these worlds represents a
single (playing) game state. You need to define such a class for each different state. The nice thing
is that you already have a lot of code in place that helps you do this. The
GameObjectList
class
is particularly useful because it represents a list of game objects, which is a sufficient basis for
representing a game state. In the previous games, the classes that represented the game world
inherited from the
GameObjectList
class. In the remaining examples in this topic, classes that
represent a
game state
will also inherit from
GameObjectList
. So, if you have an options menu, a
title screen, a level-selection screen, and a help menu, you make a separate class for each of these
game states. The only thing you still need to provide is a way to manage the various game states in
the game. You do this by creating a
game-state manager
.
The Game-State Manager
In this section, you create a class called
GameStateManager
. Because there should be only a
single game-state manager in a game, you follow the
singleton design pattern
, where the class
is called
GameStateManager_Singleton
, and you store the (single) instance in a global variable
GameStateManager
, just as you did for classes such as
Canvas2D
and
Game
:
var GameStateManager = new GameStateManager_Singleton();
You set up this class in such a way that it allows you to store different game states (that is, different
GameObjectList
instances), that you can select what the current game state is, and that the manager
then automatically calls the game-loop methods on the currently active game state.
To store the various game states, you need an array. You also define an additional variable to keep
track of the currently active game state. As a result, this is the constructor of the game-state manager:
function GameStateManager_Singleton() {
this._gameStates = [];
this._currentGameState = null;
}
Now you need to define a method that adds a game state to the array. In that method, you use
push
to add an element to the end of array. You also set the currently active game state to the state you
just added. Here is the complete
add
method:
GameStateManager_Singleton.prototype.add = function (gamestate) {
this._gameStates.push(gamestate);
this._currentGameState = gamestate;
return this._gameStates.length - 1;
};
Search WWH ::
Custom Search