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

(vip2019) #1

238 Chapter 10


(picx, picy)

(paddlex, paddley)

(paddlex, paddley)

paddlew

(picw/2) (picw/2)

(picx, picy)

Figure 10-4: Two collision cases between the paddle and our smiley ball

Because we want the ball to bounce realistically off the paddle,
we want to check for the cases where the bottom center of the ball
just touches the corners of the paddle at the left and right extremes.
We want to make sure the player scores a point not only when the
ball bounces directly off the top of the paddle but also whenever it
bounces off the paddle’s corners. To do this, we’ll see if the ball’s
vertical location is near the bottom of the screen where the paddle
is, and if so, we’ll check whether the ball’s horizontal location would
allow it to hit the paddle.
First, let’s figure out what range of x-coordinate values would
allow the ball to hit the paddle. Since the middle of the ball would
be half the width of the ball across from its (picx, picy) top-left
corner, we’ll add the width of the ball as a variable in the setup
section of our app:

picw = 100

As shown in Figure 10-4, the ball could hit the top-left corner
of the paddle when picx plus half the width of the picture (picw/2)
touches paddlex, the x-coordinate of the left corner of the paddle.
In code, we could test this condition as part of an if statement: picx
+ picw/2 >= paddlex.
We use the greater than or equal to condition because the ball
can be farther right (greater than paddlex in the x direction) and
still hit the paddle; the corner case is just the first pixel for which
the player gets a point for hitting the paddle. All the x-coordinate
values between the left corner and the right corner of the paddle
are valid hits, so they should award the user a point and bounce
the ball back.
To find that top-right corner case, we can see from the figure
that we’re requiring the middle of the ball, whose x-coordinate
Free download pdf