Notes: 13. Restarting the Game
Reinitialize all the variables in the restart method.
We have the game-over dialog showing up whenever the Snake collides with the play-area boundaries. However, tapping on the Restart button does not restart the game from scratch.
In this episode, you will be writing the code to reset all the variables back to their original value which will automatically retstart the game.
Let’s begin.
In the restart method, add the following code.
void restart() {
length = 5;
positions = [];
direction = getRandomDirection();
speed = 1;
changeSpeed();
}
In the above code, we are
- reseting the
lengthto5so that Snake’s length is reset. - clearing the
positionslist - setting the
directionto a new random direction usinggetRandomDirection - reseting the
speedto1so the Snake’s speed is reset.
That was simple, right? Let’s save the changes and restart the app.
Play the game and when you unfortunately collide with any of the play-area boundary, you will see the game-over dialog.
In the dialog, when you tap the Restart button in the dialog, the game should restart from scratch and the Snake should start from a new random position in a new random direction.
One thing that you would notice is that the dialog always shows score as 0. That’s because we have not yet implemented the scoring feature. Let’s do that in the next episode.