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

14. Adding Game Score

Episode complete

About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 13. Restarting the Game

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 14. Adding Game Score

Implement getScore and add it to the build method. To learn more about game development in Flutter using Flame, you can read this Beginning Flame article

Transcript: 14. Adding Game Score

We have the game-over dialog but the score it shows is always 0. In this episode, you will be implementing the scoring feature in the game.

Let’s begin.

In the getScore method, add the following code.

Widget getScore() {
    return Positioned(
        top: 50.0,
        right: 40.0,
        child: Text(
            "Score: " + score.toString(),
            style: TextStyle(fontSize: 24.0),
        ),
    );
}

In the above code, we are simply creating a Positioned widget positioned on the top-right corner of the screen with the Text widget which displays the score as text.

Next, we need to update the value of score whenever the Snake eats the food and reset it to 0 whenever the game restarts.

Update the drawFood method.

if (foodPosition == positions[0]) {
      length++;
      speed = speed + 0.25;

      // Add this
      score = score + 5;
      ...
}

Here we are increasing the score by 5 every time the Snake eats a food.

Next, reset the score to 0 in restart method.

void restart() {
    // Add this
    score = 0;
    ...
}

Finally, add the getScore() to the build method inside the Stack.

@override
  Widget build(BuildContext context) {
    ...

    return Scaffold(
      body: Container(
        color: Color(0XFFF5BB00),
        child: Stack(
          children: [
            ...
            getScore(), // Add this
          ],
        ),
      ),
    );
  }

Save the file and restart the app.

As the game restarts, you will rightaway notice that the score is displayed on the top-right corner. As the game progresses and the Snake eats food, the score increases. And if the player messes up and collides with any of the play-area boundary, the game is over.

The game-over dialog displays the user’s score and also allows the user to restart the game.

That’s all. Congratulations! Now you have your very own Snake game built in Flutter.