Game Development Reference
In-Depth Information
values that never change. They are declared just like variables, but without the var keyword. The
following code demonstrates an example of this. The var keyword is for variables, which, by
definition, can change value when your program is executing.
The following code sets up the states the class will use. These states will control the flow of the
game. We make them const variables, so they will be considered static and can be accessed
from other classes without creating an instance of this class.
public static const STATE_INIT:int = 10;
public static const STATE_PLAY:int = 20;
public static const STATE_GAME_OVER:int = 30;
public var gameState:int = 0;
The first three statements represent the possible states that our game could execute. We set
them as constant values, because our game will depend on these values never changing since
the game will use these states to control the on-screen action. Again, this example is very simple;
your game could have many more states and, in fact, have multiple states within a single state
(see Chapters 8 and 9 for examples of these kinds of nested states).
The last statement, public var gameState:int = 0; , creates a variable to hold the current game
state that will be tested in the state loop.
The following function, gameLoop(), acts as the main game loop. It will be called repeatedly by
the game timer (see the following code). The switch statement decides what the game should do
based on the current state (held in the gameState variable).
public function gameLoop(e:Event):void {
switch(gameState) {
case STATE_INIT :
initGame();
break
case STATE_PLAY:
playGame();
break;
case STATE_GAME_OVER:
gameOver();
break;
}
}
This state loop was developed for a very specific reason. Without a state loop, you might have to
keep track of the program flow with multiple Boolean (true or false) variables. This can work for a
simple game, but for something more complex, it can become a nightmare. If just one Boolean is
not set correctly, the whole system falls apart. The state solves this problem by limiting the game
to one single state (with possible nested states) that can be executing at any one moment.
Game timer
The Game timer calls the state loop at regular intervals to check the state of the game. Notice
that the previous code has a function named gameLoop() . By its name, you'd be right in thinking
that it needs to be called iteratively to execute the game logic. The game timer provides this
functionality by calling gameLoop() every time an ENTER_FRAME event occurs. The code looks like
this:
Search WWH ::




Custom Search