HTML and CSS Reference
In-Depth Information
Turn-Based Game Flow and the State Machine
Our game logic and flow is separated into 16 discrete states. The entire application runs on a
40
-frames-per-second interval timer:
switchGameState
(
GAME_STATE_INIT
);
var
var
FRAME_RATE
=
40
;
var
var
intervalTime
=
1000
/
FRAME_RATE
;
setInterval
(
runGame
,
intervalTime
)
As with the other games, in
Chapter 8
and earlier in this chapter, we use a function reference
statemachinetorunourcurrentgamestate.The
switchGameState()
functiontransitionstoa
newgamestate.Let'sdiscussthisfunctionbrieflyandthenmovethroughtherestofthegame
functions.
NOTE
Wedonotreprinteachlineofcodeordissect itindetail here.Usethissection asaguideforperusing
the entire set of game code included at the end of this chapter (in
Example 9-2
). By now, you have
seen most of the code and ideas that create this game logic. We break out the new ideas and code in
the sections that follow.
GAME_STATE_INIT
This state loads the assets we need for our game. We are loading only a single tile sheet and
no sounds for
Micro Tank Maze
.
Aftertheinitialload,itsendsthestatemachinetothe
GAME_STATE_WAIT_FOR_LOAD
stateuntil
the load event has occurred.
GAME_STATE_WAIT_FOR_LOAD
This state simply makes sure that all the items in
GAME_STATE_INIT
have loaded properly. It
then sends the state machine to the
GAME_STATE_TITLE
state.
GAME_STATE_TITLE
Thisstateshowsthetitlescreenandthenwaitsforthespacebartobepressed.Whenthishap-
pens, it sends the state machine to
GAME_STATE_NEW_GAME
.
GAME_STATE_NEW_GAME
This state resets all the game arrays and objects and then calls the
createPlayField()
func-
tion. The
createPlayField()
function creates the
playField
and
enemy
arrays for the new