Timers and Animation: What Would Disney Do? 197
With this first version of the program, we have created what
looks like a smoothly animated smiley face bouncing back and
forth between two corners of a square drawing window. We are
able to achieve this effect precisely because the window is a per-
fect square, 600×600 pixels in size, and because we always change
our picx and picy values by the same amount (speed)—our smiley
face travels only on the diagonal line where x = y. By keeping our
image on this simple path, we only have to check whether picx
goes past the boundary values at the left and right edges of the
screen.
What if we want to bounce off all four edges (top, bottom, left,
and right) of the screen, in a window that isn’t a perfect square—
say, 800×600? We’ll need to add some logic to check our picy variable
to see if it passes an upper or lower boundary (the top or bottom of
the screen), and we’ll need to keep track of horizontal and vertical
speed separately. We’ll do that next.
Bouncing a Smiley Off Four Walls
In SmileyBounce1.py, we kept the horizontal (left-right) and ver-
tical (up-down) motion locked so that whenever the image was
moving right, it was also moving down, and when it was moving
left, it was also moving up. This worked well for our square win-
dow because the width and height of the screen were the same.
Let’s build on that example to create a bouncing animation that
rebounds realistically off all four sides of the drawing window.
We’ll make the window 800×600 pixels in size with screen =
pygame.display.set_mode([800,600]) to make the animation more
interesting.
h orizontal and Vertical speed
First, let’s separate the horizontal and vertical components of the
speed. In other words, let’s create one speed variable, speedx, for
the horizontal speed (how fast the image is moving to the right or
left), and another speed variable, speedy, for the vertical speed (how
fast the image is moving down or up). We can accomplish this by
changing the speed = 5 entry in the setup section of our app to ini-
tialize a speedx and speedy as follows:
speedx = 5
speedy = 5