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
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.