As of now, if you try to eat the food by navigating the Snake to pass through the food, nothing happens. The food does not go away and the Snake is not affected either. That’s exactly the voids that you are going to fill in this episode.
The way you are going to implement this is that you will check, on every step that the Snake takes, if the head of the Snake overlaps with the food.
When the Snake eats the food, we do the following.
- Increase the length of the Snake by one.
- Increase the speed of the Snake.
- Create a new food at a new random position.
We do this altering a few variables in the game.
The length of the Snake is controlled by the length variable and the speed of the snake’s movement is controlled by the speed variable. We will change this variables and re-initialize the timer. In addition to that, we will also render the food again, at a new position.
Let’s begin.
The head of the Snake is at the position which is stored at 0th index in the positions list and the food’s position is stored in foodPosition. If those match or overlap, you can assume that the Snake has eaten the food successfully.
Let’s add this code to the drawFood method right after the first if block.
void drawFood() {
if (foodPosition == null) {
foodPosition = getRandomPositionWithinRange();
}
// Add this
if (foodPosition == positions[0]) {
// Snake and food overlap
}
...
}
The code above simply checks if foodPosition and positions[0] are equal. Dart is smart enough to compare two Offset objects. If the dx and dy values both match, the positions match.
Once we know if the Snake has eaten the food, we will change the speed and length variables.
void drawFood() {
...
if (foodPosition == positions[0]) {
length++;
speed = speed + 0.25;
changeSpeed();
}
...
}
Here, we are simply increasing the value of length by 1 and of speed by 0.25. These values are arbitrary and you can play around with these if you want to change the game behavior.
We also need to call the changeSpeed method so the timer takes the new value of speed into account. This will update the UI faster and the snake will apear to be moving faster.
After the changing the variables, we need to update the foodPosition.
Let’s add the code to do that as well within the same if-block.
void drawFood() {
...
if (foodPosition == positions[0]) {
length++;
speed = speed + 0.25;
changeSpeed();
// Add this
foodPosition = getRandomPositionWithinRange();
}
...
}
Here we are updating the foodPosition with a new randomly generated position on the screen.
That’s all. Save the file and restart the application. You should see food. Try to navigate the Snake to eat the food. Once the Snake eats the food, you will see the length and speed of the Snake increase. You should also see a new food rendered at a new position. And this continues. Forever!