Notes: 12. Show Game Over Dialog
Add detectCollision to the getNextPosition method.
In this episode, you will be using the provided showGameOverDialog method to display a game-over dialog to the user when the Snake collides with the play-area boundaries. The showGameOverDialog method is provided as part of the starter project.
Let’s begin.
In the getNextPosition method, once you have detected a collision, instead of just returning the original position, we need to invoke the showGameOverDialog method.
Offset getNextPosition(Offset position) {
...
if (detectCollision(position) == true) {
if (timer != null && timer.isActive) timer.cancel();
showGameOverDialog(); // Add this
return position;
}
...
return nextPosition;
}
Let’s a little bit of delay before we display the game-over dialog to the user after we detect the collision.
Let’s make some changes to the code we have just implemented.
First, you need to make the return type of the getNextPosition method a Future<Offset> rather than just Offset.
Next, we wrap the showGameOverDialog with a Future.delayed with a small duration of 500ms or so. Also, add an await keyword to wait for the Future to complete.
Future<Offset> getNextPosition(Offset position) async {
...
if (detectCollision(position) == true) {
if (timer != null && timer.isActive) timer.cancel();
await Future.delayed(Duration(milliseconds: 500), () => showGameOverDialog());
return position;
}
...
}
Finally, you need to make some changes where you have used getNextPosition method. Add await keyword before getNextPosition in the draw method like this.
void draw() async {
...
// Update this
positions[0] = await getNextPosition(positions[0]);
}
That’s all.
Save all the files and retstart the app completely.
If the Snake collides with the play-area boundaries, you should see a game-over dialog. Nice, right? However, if you tap on the Restart button in the dialog, it does not quite restart the game. Let’s fix that in the next episode.