Game Programming: Coding for Fun 237
To add the logic for subtracting a life when the ball hits the
bottom of the screen, we have to break our if statement for hitting
the top or bottom of the screen (if picy <= 0 or picy >= 500) into
two parts, top and bottom separately. If the ball hits the top of the
screen (picy <= 0), we just want it to bounce back, so we’ll change
the direction of the ball’s speed in the y direction with -speedy:
if picy <= 0:
speedy = -speedy
If the ball bounces off the bottom (picy >= 500), we want to
deduct a life from lives and then have the ball bounce back:
if picy >= 500:
lives -= 1
speedy = -speedy
Subtracting a life is done, so now we need to add points. In
“SmileyPop, Version 1.0” on page 224, we saw that Pygame con-
tains functions that make it easier to check for collisions. But
since we’re building this Smiley Pong game from scratch, let’s see
how we can write our own code to check for collisions. The code
might come in handy in a future app, and writing it is a valuable
problem-solving exercise.
Hitting the Ball with the Paddle
To check for the ball bouncing off the paddle, we need to look at
how the ball might come into contact with the paddle. It could hit
the top-left corner of the paddle,
it could hit the top-right corner
of the paddle, or it could bounce
directly off the top of the paddle.
When you’re figuring out the
logic for detecting collisions, it
helps to draw it out on paper and
label the corners and edges where
you need to check for a possible
collision. Figure 10-4 shows a
sketch of the paddle and the
two corner collision cases with
the ball.