Part 9 - Game Over
The last thing the game is missing is an ending! Update the code so that the game ends when the player runs out of lives. All changes will take place in the ArcadeFlyerGame.cs file.
Tracking Game Over
Add a way to track whether or not the game has ended. If it has, stop the game from running.
- In the
ArcadeFlyerGameclass, under thescorefield, add a newprivate boolfield namedgameOver - Set the value of
gameOverto befalseto startprivate bool gameOver = false; - In the
Updatemethod, find where thelifefield is decremented - Under that, create an
ifstatement to check if thelifefield has gone below 1 - In the body of the
ifstatement, setgameOvertotrueif (life < 1) { gameOver = true; } - Next, at the very top of the body of the
Updatemethod, create anotherifstatement - Make this
ifstatement check thegameOverfield as its condition - In the body of the
ifstatement, simplyreturnfrom the method so no updates will continueif (gameOver) { return; }
Run the code and see what happens! The game should freeze when the player has zero lives remaining.
Displaying a Final Message
The program properly freezes when the game ends, but it's not entirely clear what's happening. When the game is over, everything should disappear except a final message near the center of the screen.
- In the
ArcadeFlyerclass, find theDrawmethod - At the very top of this method, create an
ifstatement - Make the
ifstatement check if the game is over - In the body of the
ifstatement, callGraphicsDevice.Clearand pass in an appropriate color - Under that, call
spriteBatch.Begin - Next, create a new
Vector2variable namedtextPosition - Set the
textPositionvariable to a newVector2object, passing inscreenWidth / 2andscreenHeight / 2 - Under that, call
spriteBatch.DrawString, and pass in the following:textFontfor theSpriteFontobject- A new string displaying a "Game Over" message, along with the final score
textPositionfor theVector2object- An appropriate
Colorvalue
- Under that, call the
spriteBatch.Endmethod - Finally, under that,
returnearly from the method so nothing else is drawn
Code
if (gameOver)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
Vector2 textPosition = new Vector2(screenWidth / 2, screenHeight / 2);
spriteBatch.DrawString(textFont, $"Game Over :(\nFinal Score: {score}", textPosition, Color.White);
spriteBatch.End();
return;
}
Run the game again, and it should display a message when the game is over!
Final Code
The final code for this walkthrough is available on GitHub.
Next Steps
Beyond this, take a look at the Enhancement Ideas to try to make the game even better!