Lesson 7 of 10

Game states

Goal

One state variable and a pure transition function

01

Explanation

Every game goes through stages: it starts at the menu, then you play, then you see the game over screen, then you play again. If you manage these stages with scattered boolean variables like isPlaying, isDead and showMenu, sooner or later you'll end up in impossible states, like a player who has lost but is still scoring points.

The alternative is a state machine: a single state variable that only ever holds one of three values, and what each event means depends on that value. The 'start' event on the menu starts the game, but during play it changes nothing.

Make the transition between states a pure function, one that takes the state and the event and returns a new state without modifying the old one. That way you can test it without a screen, record events and replay them, and compare the state before and after an event.

02

Your task

Write transition(game, event) for the object { state, score, lives }. The 'start' event in the 'menu' or 'gameover' state starts a new game with a score of 0 and three lives. In the 'playing' state, the 'point' event adds one to the score and the 'hit' event takes away one life, and when the lives run out, the game moves to 'gameover'. Any other event returns the state unchanged. To try it, click the preview while the marker is inside the green box.

Checks

6 checks
  1. start takes the game from the menu to playing
  2. point adds one to the score
  3. hit takes away a life, and losing the last one ends the game
  4. Playing again starts from zero with three lives
  5. An event in the wrong state changes nothing
  6. The old state stays as it was
03

Hints

0/3
Track lessons0 of 10 done

Build a real canvas game that runs in any browser, and learn the game loop, movement, collisions and scoring along the way.

Intermediate level, 10 lessons, 2.5 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 10 done

Build a real canvas game that runs in any browser, and learn the game loop, movement, collisions and scoring along the way.

Intermediate level, 10 lessons, 2.5 hours in total.