Making the Snake Grow

Grow snake by one segment at a time (47:50)

Now that the snake can successfully locate and consume the food, let's move on to the next step. The snake's growth is an important aspect of the game, and we need to code the behavior that allows the snake to grow by one segment or cell each time it eats food.

Before we implement the snake's growth behavior, let's consider how it should work.

When the snake eats food, we want it to increase in size by adding an additional segment to its body. It's important to note that this segment should be added to the beginning of the snake's body, as this creates a more natural visual effect. Additionally, when the snake grows, we should not move it at the same time as this can create an unnatural, jumpy appearance. In summary, when the snake eats food, we will add a new segment to the beginning of its body and not move the snake for that call of the update method. So, the update method of the snake class must know if it has to add a segment to the snake or to move the snake. For this let’s create a new attribute to the snake class: call it add_segment and set it to False. Now, in the update method we check the value of this attribute.

if self.add_segment == True: 

We have to add another segment to the snake

else:

We move the snake so we just indent the code which is responsible for moving the snake.

Now let’s write code to add a segment to the snake body. Adding a segment to the snake’s body is very easy.

We have to insert a new element to the body list, so we are going to use the insert method of the list self.body.insert()

We need to enter a new element at the beginning so the first argument is 0, now we need to add another element next to the head of the snake.

So to find the position of the next element we first get the position of the head of the snake which is self.body[0] and now we have to add the direction of the movement of the snake like this: self.direction That’s all we have to do. Now that the snake has increased in size we have to set the add_segment attribute to False.

Now if we look closely at this method we can see that we have written the same line of code twice. It is a good idea to remove any duplicate code. So, let’s re-write this block of code to avoid this.

We are going to move this line of code outside of the if statement and remove it from here.

That’s it, no more duplicate code. We can move on. At the check_collision_with_food method of the game class we have to write this line of code: self.snake.add_segment = True to notify the snake object that it needs to grow in size.

Now we are ready to test our code. As you can see, the snake moves as before and everytime it collides with a food object it grows in size by one segment.