How to Create a 2D Snake Game in Flutter

Jan 17 2023 Dart 2.17, Flutter 3.0, Android Studio or VS Code

Part 1: How to Create a 2D Snake Game in Flutter

10. Consuming & Regenerating the Food

Episode complete

Play next episode

Next
Save for later
About this episode
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 9. Displaying the Food on Screen Next episode: 11. Detecting Collisions

This video Consuming & Regenerating the Food was last updated on Jan 17 2023

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

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.

void drawFood() {
    if (foodPosition == null) {
      foodPosition = getRandomPositionWithinRange();
    }

    // Add this
    if (foodPosition == positions[0]) {
      // Snake and food overlap
    }

    ...
  }
void drawFood() {
    ...
    if (foodPosition == positions[0]) {
        length++;
        speed = speed + 0.25;
        changeSpeed();
    }
    ...
  }
void drawFood() {
    ...
    if (foodPosition == positions[0]) {
        length++;
        speed = speed + 0.25;
        changeSpeed();

        // Add this
        foodPosition = getRandomPositionWithinRange();
    }
    ...
  }