Timers and Animation: What Would Disney Do? 189
of frames per second our program draws.
Currently, we’re moving the smiley image
only 1 pixel down and 1 pixel to the right
each time through the game loop, but
our computer can draw this simple scene
so fast that it can produce hundreds of
frames per second, causing our smiley to
fly off the screen in an instant.
Smooth animation is possible with
30 to 60 frames of animation per second,
so we don’t need the hundreds of frames
zooming past us every second.
Pygame has a tool that can help us control the speed of our
animation: the Clock class. A class is like a template that can be
used to create objects of a certain type, with functions and values
that help those objects behave in a certain way. Think of a class
as being like a cookie cutter and objects as the cookies: when we
want to create cookies of a certain shape, we build a cookie cutter
that can be reused anytime we want another cookie of the same
shape. In the same way that functions help us package reusable
code together, classes allow us to package data and functions into
a reusable template that we can use to create objects for future
programs.
We can add an object of the Clock class to our program setup
with this line:
timer = pygame.time.Clock()
This creates a variable called timer linked to a Clock object. This
timer will allow us to gently pause each time through the game loop
and wait just long enough to make sure we’re not drawing more
than a certain number of frames per second.
Adding the following line to our game loop will keep the frame
rate at 60 fps by telling our Clock named timer to “tick” just 60 times
per second:
timer.tick(60)
The following code, SmileyMove.py, shows the whole app put
together. It gives us a smooth, steady animated smiley face slowly
gliding off the lower right of the screen.