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

(vip2019) #1

200 Chapter 8


picx += speedx
picy += speedy

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

screen.fill(BLACK)
screen.blit(pic, (picx, picy))
pygame.display.update()
timer.tick(60)

pygame.quit() # Exit

The rebounds look realistic. If the smiley is coming toward the
bottom edge at a 45-degree angle down and to the right, it bounces
off at a 45-degree angle up and to the right. You can experiment
with different values of speedx and speedy (say, 3 and 5 , or 7 and 4 ) to
see the angles change for every bounce.
Just for fun, you can comment out the line screen.fill(BLACK) in
SmileyBounce2.py to see the path traveled by our smiley face as it
bounces off each edge of the screen. When you comment out a line,
you turn it into a comment by putting a hash mark at the begin-
ning, as follows:

# screen.fill(BLACK)

This tells the program to ignore the instruction on that line.
Now the screen is not erased after each smiley face is drawn, and
you’ll see a pattern created by the trail your animation is leaving
behind, like in Figure 8-9. Because each new smiley is drawn over
the previous one, the result looks like cool, retro 3-D screensaver
artwork as it draws.
Our collision-detection logic has allowed us to create the illusion
of a solid smiley face bouncing off all four edges of a solid drawing
screen. This is an improvement over our original version, which
let the smiley slide off into oblivion. When we create games that
allow the user to interact with pieces on the screen, and that allow
those pieces to look as if they’re interacting with one another—like
in Tetris, for example—we’re using the same kind of collision detec-
tion and boundary checking that we built here.
Free download pdf