Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1

220 Chapter 9


graphics without coding them from scratch. At v, we set the image
of the sprite object (self.image) to the pic graphic that we loaded
from disk (CrazySmile.bmp—you’ll need to make sure that file
is still in the same folder as this new program), and we get the
dimensions of the rectangle that contains the 100×100 picture.
At w, the statement self.pos = pos stores the position that
was passed into the __init__() function in the object’s own pos
variable. Then, at x, we set the x- and y-coordinates of the
sprite’s drawing rectangle to the x- and y-coordinates stored in
pos, shifted by half the size of the image (self.scale/2) so that
the smiley is centered on the spot the user clicked with the
mouse. Finally, we store the x- and y-velocities that were passed
to the __init__() function in the object’s xvel and yvel variables
(self.xvel and self.yvel) at y.
This __init__() constructor function will set up everything
we need for drawing each smiley face on the screen, but it doesn’t
handle the animation needed to move our sprites around the screen.
For that, we’ll add another handy function for our sprites, update().

Updating Sprites


Sprites are built for animation, and we’ve learned that animation
means updating the location of a graphic each frame (each time
we pass through the game loop). Pygame sprites have an update()
function built in, and we can override, or customize, this function
to program the behavior that we want from our custom sprites.
Our update() function is pretty simple; the only updates to our
bouncing smiley sprites for each frame are changing the position
of each sprite according to its speed and checking to see whether it
has collided with the edge of the screen:

def update(self):
self.rect.x += self.xvel
self.rect.y += self.yvel
if self.rect.x <= 0 or self.rect.x > screen.get_width() - self.scale:
self.xvel = -self.xvel
if self.rect.y <= 0 or self.rect.y > screen.get_height() - self.scale:
self.yvel = -self.yvel

Free download pdf