Timers and Animation: What Would Disney Do? 199
Let’s do the same thing with picy:
if picy <= 0 or picy + pic.get_height() >= 600:
speedy = -speedy
To test whether our smiley has hit the top edge of the screen,
we use picy <= 0, which is similar to picx <= 0 for the left edge. To
figure out whether our smiley has hit the bottom edge of the screen,
we need to know both the height of the drawing window (600 pixels)
and the height of the image (pic.get_height()), and we need to see if
the top of our image, picy, plus the image’s height, pic.get_height(),
totals more than the height of our screen, 600 pixels.
If picy goes outside these top and bottom boundaries, we need
to change the direction of the vertical speed (speedy = -speedy). This
makes the smiley face look like it’s bouncing off the bottom edge of
the window and heading back up, or bouncing off the top and head-
ing back down.
Putting it all Together
When we put the whole program together in SmileyBounce2.py, we
get a convincing bouncing ball that is able to rebound off all four
edges of the screen for as long as we run the app.
SmileyBounce2.py
import pygame # Setup
pygame.init()
screen = pygame.display.set_mode([800,600])
keep_going = True
pic = pygame.image.load("CrazySmile.bmp")
colorkey = pic.get_at((0,0))
pic.set_colorkey(colorkey)
picx = 0
picy = 0
BLACK = (0,0,0)
timer = pygame.time.Clock()
speedx = 5
speedy = 5
while keep_going: # Game loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
keep_going = False