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

(vip2019) #1

198 Chapter 8


We can then modify our image position updates in the
game loop:

picx += speedx
picy += speedy

We change picx (the horizontal or x-position) by speedx (the
horizontal speed) and picy (the vertical or y-position) by speedy (the
vertical speed).

h tting Four Wallsi
The last part to figure out is the boundary collision detection for
each of the four edges of the screen (top and bottom in addition to
right and left). First, let’s modify the left and right boundaries to
match the new screen size (800 pixels wide) and to use the new
horizontal speed speedx:

if picx <= 0 or picx + pic.get_width() >= 800:
speedx = -speedx

Notice that our left-edge-boundary case remains the same
at picx <= 0, because 0 is still the left boundary value when picx is at
the left of the screen. This time, though, our right-edge-boundary
case has changed to picx + pic.get_width() >= 800, because our screen
is now 800 pixels wide, and our image still starts at picx and then
draws its full width to the right. So when picx + pic.get_width()
equals 800 , our smiley face looks like it is touching the right side of
the drawing window.
We slightly changed the action that our left and right boundar-
ies trigger, from speed = -speed to speedx = -speedx. We now have two
components of our speed, and speedx will control the left and right
directions and speeds (negative
values of speedx will move the
smiley face left; positive values
will move it right). So when the
smiley hits the right edge of the
screen, we turn speedx negative to
make the image go back toward
the left, and when it hits the
left edge of the screen, we turn
speedx back to a positive value to
rebound the image to the right.
Free download pdf