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
ArcadeFlyerGame
class, under thescore
field, add a newprivate bool
field namedgameOver
- Set the value of
gameOver
to befalse
to startprivate bool gameOver = false;
- In the
Update
method, find where thelife
field is decremented - Under that, create an
if
statement to check if thelife
field has gone below 1 - In the body of the
if
statement, setgameOver
totrue
if (life < 1) { gameOver = true; }
- Next, at the very top of the body of the
Update
method, create anotherif
statement - Make this
if
statement check thegameOver
field as its condition - In the body of the
if
statement, simplyreturn
from 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
ArcadeFlyer
class, find theDraw
method - At the very top of this method, create an
if
statement - Make the
if
statement check if the game is over - In the body of the
if
statement, callGraphicsDevice.Clear
and pass in an appropriate color - Under that, call
spriteBatch.Begin
- Next, create a new
Vector2
variable namedtextPosition
- Set the
textPosition
variable to a newVector2
object, passing inscreenWidth / 2
andscreenHeight / 2
- Under that, call
spriteBatch.DrawString
, and pass in the following:textFont
for theSpriteFont
object- A new string displaying a "Game Over" message, along with the final score
textPosition
for theVector2
object- An appropriate
Color
value
- Under that, call the
spriteBatch.End
method - Finally, under that,
return
early 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!