Snake in CreateJS Tutorial Part 3

This is the last part of the “Snake in CreateJS Tutorial”. Here you can check the other ones: Part 1 and Part 2.

In this part, we are going to implement a scoring system and add new views – main menu and game over.

The code can be found in the repository: Repository.

Implementation of score

The score is a really simple thing. You just need to add the points every time when the snake eats food and draw a new score on the screen.

So, let’s add a score field to World class:

// source/objects/World.js

export class World {
  constructor(stage) {
    this.stage = stage;
    this.score = 0;

    ...
  }

  ...
}

And increase it by 10 every time when the snake eats food:

// source/objects/World.js

export class World {
  render() {
    ...

    if (this.checkFoodCollision()) {
      this.score += 10;

      this.snake.grow();
      this.food.generateRandomPosition();
      this.drawFood();
    }

    ...
  }
}
Continue reading

Snake in CreateJS Tutorial Part 2

This is the second part of the “Snake in CreateJS Tutorial”. Here you can check the first one: Part 1.

In this part of the tutorial, we are going to implement collisions between the snake and borders, the snake with food, and the snake’s self-collision. We are also going to implement a food generation and snake growing system.

The code can be found in the repository: Repository.

Snake limited by the game borders

In order to check the collision between the snake and borders we need to check if the position of the snake is higher or lower than canvas dimensions:

// source/objects/World.js

export class World {
  ...

  checkBordersCollision() {
    return (
      this.snake.head.x > CONFIG.canvasWidth ||
      this.snake.head.x < 0 ||
      this.snake.head.y > CONFIG.canvasHeight ||
      this.snake.head.y < 0
    );
  }

  checkSnakeCollision() {
    return this.checkBordersCollision();
  }

  render() {
    this.stage.update();

    if (this.isPaused) {
      return;
    }

    if (!this.checkSnakeCollision()) {
      this.snake.move();
      this.drawSnake();
    } else {
      this.snake.stop();
      document.removeEventListener("keydown", this.handleKeydown.bind(this));
    }
  }
}
Continue reading