The Game State Machine

A state machine is a programming construct that allows for our game to be in only a single application state at any one time. We will create a state machine for our game, called application state, which will include seven basic states (we will use constants to refer to these states):

  • GAME_STATE_TITLE

  • GAME_STATE_NEW_GAME

  • GAME_STATE_NEW_LEVEL

  • GAME_STATE_PLAYER_START

  • GAME_STATE_PLAY_LEVEL

  • GAME_STATE_PLAYER_DIE

  • GAME_STATE_GAME_OVER

We will create a function object for each state that will contain game logic necessary for the state to function and to change to a new state when appropriate. By doing this, we can use the same structure for each game we create by simply changing out the content of each state function (as we will refer to them).

Let’s take a look at a very basic version of this in action. We will use a function reference variable called currentGameStateFunction, as well as an integer variable called currentGameState that will hold the current application state constant value:

var currentGameState = 0;
var currentGameStateFunction = null;

We will create a function called switchAppState() that will be called only when we want to switch to a new state:

function switchGameState(newState) {
   currentGameState = newState;
   switch (currentGameState) {

      case GAME_STATE_TITLE:
         currentGameStateFunction = gameStateTitle;
         break;

      case GAME_STATE_PLAY_LEVEL:
         currentGameStateFunctionappStatePlayeLevel;
         break;

      case GAME_STATE_GAME_OVER:
         currentGameStateFunction = gameStateGameOver ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.