216 Chapter 9
Pygame includes support for sprite graphics through its pygame
.sprite.Sprite class. Remember from Chapter 8 that a class is like
a template that can be used to create reusable objects, each with
its own full set of functions and properties. In SmileyMove.py on
page 190, we used the Clock
class, along with its tick()
method, to make our animations
smooth and predictable. In the
smiley explosion app, we’ll use a
few handy Pygame classes, and
we’ll build a class of our own to
keep track of each individual smi-
ley face as it moves around the
screen.
m ore on classes and objects
In Chapter 8 you learned that classes are like cookie cutters, and
objects are like the cookies we create using a particular cookie
cutter. Whenever we need several items with similar functions and
characteristics (like moving smiley face images with various sizes
and locations), and especially when we need each item to contain
different information (like the size, location, and speed of each
smiley), a class can provide the template to create as many objects
of that type as we need. We say that objects are instances of a par-
ticular class.
The Pygame library has dozens of reusable classes, and each
class has its own methods (what we call a class’s functions) and
attributes or data, the variables and values stored in each object.
In the Clock class in Chapter 8, the tick() method was our func-
tion for making animation happen at a certain frame rate. For the
floating smiley Sprite objects in this app, the attributes we care
about are each smiley’s location on the screen, its size, and the
speed it’s moving in the x- and y-directions, so we’ll create a Smiley
class with those attributes. We can create our own classes when-
ever we need a reusable template.
Breaking a problem or program down into objects, and then
building classes that create those objects, is the foundation of
object-oriented programming. Object-oriented programming is a
way of solving problems using objects. It is one of the most popular
approaches used in software development, and one reason for that
popularity is the concept of code reuse. Reusability means that