Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1

246 Chapter 10


Game Over


Version 1.0 never stopped playing because we didn’t add logic to
handle the game being over. We know the condition to test for: the
game is over when the player has no lives left. Now we need to fig-
ure out what to do when the player loses their last life.
The first thing we want to do is stop the game. We don’t want
to close the program, but we do want to stop the ball. The sec-
ond thing we want to do is change the text on the screen to tell
the player that the game is over and give them their score. We
can accomplish both tasks with an if statement right after the
draw_string declaration for lives and points.

if lives < 1:
speedx = speedy = 0
draw_string = "Game Over. Your score was: " + str(points)
draw_string += ". Press F1 to play again. "

By changing speedx and speedy (the horizontal and vertical
speed of the ball, respectively) to zero, we’ve stopped the ball
from moving. The user can still move the paddle on the screen,
but we’ve ended the gameplay visually to let the user know the
game is over. The text makes this even clearer, plus it tells the
user how well they did this round.
Right now, we’re telling the user to press F1 to play again, but
pressing the key doesn’t do anything yet. We need logic to handle
the keypress event and start the game over.

Play Again


We want to let the user play a new game when they’ve run out of
lives. We’ve added text to the screen to tell the user to press the
F1 key to play again, so let’s add code to detect that keypress and
start the game over. First, we’ll check if a key was pressed and if
that key was F1:

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_F1: # F1 = New Game

In the event handler for loop inside our game loop, we add an
if statement to check if there was a KEYDOWN event. If so, we check
the key pressed in that event (event.key) to see if it’s equal to the
Free download pdf