fc64js

fc64js - Tutorial - Snake (js)

Losing the game

As things stand the snake can happily cross over itself without consequence:

In order to add an element of peril to the game, we should lose whenever the snake “bites” itself

We’ll add an isDead function to our Snake class that returns true if the snake’s head (snake.body[0]) occupies the same location as any of it it’s other body segments:

class Snake {
  ...
  isDead() {
    const head = this.body[0];
    for (let i = 1; i < this.body.length; i++) {
      if (this.body[i].equals(head)) {
        return true;
      }
    }
    return false;
  }
}

Then in romLoop, after updating the snake’s state, we’ll check if the snake isDead, and if it is reinitialise the rom by calling romInit (a simple means of restarting the game)

function romLoop() {
    ...
    snake.update();
    if (snake.isDead()) {
      romInit();
    }
    ...

Now if we refresh the browser we’ll see that the game restarts whenever we lose:

Full code at this point

Continue to the next step


Jump to step: Introduction · Project setup · Creating the snake · Drawing the snake · Moving the snake · Throttling the speed · Input handling · Placing the fruit · Eating the fruit · Losing the game · Managing state · Playing sound effects · Bug fixing · Distribution