Add Food for the Snake

Implement adding the food object for the snake and display the current score to the user on the web page.

Introduction

In the previous lesson, we moved the snake using the keyboard input. Now, we will move to the next step of adding food for the snake and incrementing the score each time the snake eats the food object. Whenever the snake eats food from the board, the size of the snake is increased by 1 block. We will add an image of the food and display it randomly on the board for the snake to eat.

Implement: Add the food randomly on the board and increment the score

To add the food and increase the length of the snake by 1 block each time the snake eats the food, we need to follow the steps mentioned below:

  • Create a function to generate the random coordinates for the food object to be displayed at on the canvas.

  • Modify the updateSnake() function to increment a variable score that keeps track of the number of food objects eaten by the snake and adjust the snake length.

First let's see the function to generate the food object coordinates randomly. While doing so, we must ensure that the coordinates generated are within the canvas height and width range.

Get hands-on with 1400+ tech skills courses.