Notes: 19. Challenge: Create a Game Over Overlay
Hint: Use isGameOver from GameManager to check for when the game has ended.
Use what you’ve learned to create a GameOver overlay.
You can copy MainMenu’s contents and use it as a starting point if you like. Just remember to adjust the overlay to display a title, the final score and a button to play again.
Try to implement this overlay by yourself.
Pause the video and try the challenge… Then keep watching for the solution.
Solution
GameOver
Let’s start with a basic stateless widget.
class GameOver extends StatelessWidget {
}
Add a name and constructor in the same way that you did for MainMenu.
static const String overlayName = 'GameOver';
// Reference to parent game.
final MeteormaniaGame game;
const GameOver({super.key, required this.game});
Now, override build to implement the overlay. A good approach is to use the same basis as MainMenu.
@override
Widget build(BuildContext context) {
return Material(
color: Colors.transparent,
child: Center(
child: Container(
padding: const EdgeInsets.all(16.0),
height: 250,
decoration: BoxDecoration(
color: const Color.fromRGBO(255, 255, 255, 0.15),
border: Border.all(
color: Colors.white,
width: 4,
),
borderRadius: const BorderRadius.all(
Radius.circular(20),
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [],
),
),
),
);
}
Now, add a Text for the title:
const Text(
'Game Over',
style: TextStyle(
fontFamily: 'PressStart2P',
color: Colors.white,
fontSize: 24,
),
),
Let’s add some spacing and then another Text for the score.
const SizedBox(height: 24),
Text(
'Score: ${game.manager.points} pts',
style: const TextStyle(
fontFamily: 'PressStart2P',
color: Colors.white,
fontSize: 16,
),
),
Add more spacing and a SizedBox for the OutlinedButton to play again.
const SizedBox(height: 32),
SizedBox(
width: 200,
height: 52,
child: OutlinedButton(
onPressed: () {
},
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: const BorderSide(width: 3.0, color: Colors.white),
),
child: const Text(
'Play again',
style: TextStyle(
fontSize: 16,
fontFamily: 'PressStart2P',
),
),
),
),
Play Again should remove the overlays and also reset the game like so.
game.overlays.remove(overlayName);
game.reset();
MeteormaniaGame
Since reset does not currently exist, let’s go ahead and add it to MeteormaniaGame.
void reset() {
}
All that reset should do is call reset on manager and call initializeGame again to add the necessary components to the game loop.
manager.reset();
initializeGame();
Now let’s change the call that adds MainMenu overlay and switch it to GameOver.
overlays.add(GameOver.overlayName);
Main
As the last step, add the new overlay to GameWidget in main.dart
GameOver.overlayName: (_, game) => GameOver(game: game),
Build and run the game. Play until you lose all lives.
Now Meteormania is complete with a main screen, a game screen with a heads up display and a game over screen. Great job!