User Interaction: Get into the Game 219
set up all the starting values we
need in our sprite object. The
two underscores on either side
of the __init__() function name
have special meaning in Python.
In this case, __init__() is the spe-
cial function name that is used to
initialize a class. We tell Python
how each Smiley object should be
initialized in this function, and
every time we create a Smiley,
this special __init__() function
does its job behind the scenes,
setting up variables and more
for each Smiley object.
There are a number of items we need to set up in our __init__()
function. First, we’ll determine what parameters we need to pass
to our __init__() function. For our random smiley faces, we might
pass in a position and the starting x- and y-velocities. Because
our Smiley is a class and all our smiley face sprites will be objects
of the Smiley type, the first parameter in all the functions in the
class will be the smiley sprite object itself. We label this parameter
self, because it connects __init__() and the other functions to the
object’s own data. Look at the code for our __init__() function:
def init(self, pos, xvel, yvel):
u pygame.sprite.Sprite.init(self)
v self.image = pic
self.rect = self.image.get_rect()
w self.pos = pos
x self.rect.x = pos[0] - self.scale/2
self.rect.y = pos[1] - self.scale/2
y self.xvel = xvel
self.yvel = yvel
The four parameters for our __init__() function are the object
itself, self; the position where we want the smiley to appear, pos;
and xvel and yvel, its horizontal and vertical speed values. Next,
at u, we call the initialization function for the main Sprite class
so that our object can take advantage of the properties of sprite