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

Save for later
About this episode
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 13. Restarting the Game

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

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.

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.

Widget getScore() {
    return Positioned(
        top: 50.0,
        right: 40.0,
        child: Text(
            "Score: " + score.toString(),
            style: TextStyle(fontSize: 24.0),
        ),
    );
}
if (foodPosition == positions[0]) {
      length++;
      speed = speed + 0.25;

      // Add this
      score = score + 5;
      ...
}
void restart() {
    // Add this
    score = 0;
    ...
}
@override
  Widget build(BuildContext context) {
    ...

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