Add Movement to the Snake

Learn how to use arrays to add movement to the snake by modifying the array containing the coordinates of each block of the snake.

Introduction

In the previous lesson, we created the snake and the board for our game. However, a stationary snake is of no use. Let us now move to the next step in building the game. We will add a movement to the snake. When the game loads, we would by default set the snake to move horizontally to the right on the screen. Later on, we will add keyboard movements to the game. You can see in the below output that the snake moves in the right-hand direction.

Implement: Add the snake's movement to the right

The snake, which was drawn while initializing the game, had 2 blocks. We must pop the last coordinates inserted in the cells array to move the snake in the right-hand direction. Then we need to add the co-ordinates in the cells array by incrementing the x-coordinate by 1 while making no change in the y-coordinate.

We will write a function to update the snake by one cell to the right. To implement this functionality, we will follow the steps mentioned below:

  1. Remove the last inserted coordinate from the cells array, which will point to the leftmost block of the snake.

  2. Store the coordinates of the rightmost block of the snake.

  3. Increment the x value of the rightmost coordinate by 1 while making no change in the y value (because we are moving the snake horizontally to the right).

  4. Add the new coordinates in the cells array to draw a block of the snake with these new coordinates.

Now let's write a function to move the snake to the right.

Get hands-on with 1200+ tech skills courses.