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

(vip2019) #1
User Interaction: Get into the Game 221

The update() function takes one parameter—the sprite object
itself, self—and the code for moving the sprite looks a lot like our
animation code from SmileyBounce2.py. The only real difference
is that we refer to the sprite’s (x, y) location with self.rect.x and
self.rect.y, and the x- and y-velocities as self.xvel and self.yvel.
Our collision detections for the boundaries of the screen also make
use of screen.get_width() and screen.get_height() so they can func-
tion for any size window.

Bigger and Smaller Smileys


The last feature we’ll add to this first version of the app is
changing the scale, or size, of the image. We’ll make this modi-
fication to our __init__() function right after setting self.image
to pic. First, we’ll change our object’s scale variable to a random
number between 10 and 100 (for a finished smiley sprite that
measures between 10×10 and 100×100 pixels in size). We’ll apply
this change in scale, also known as a transformation, by using
the pygame.transform.scale() function, as follows:

self.scale = random.randrange(10,100)
self.image = pygame.transform.scale(self.image, (self.scale,self.scale))


Pygame’s transform.scale() function takes an image (our
self.image of the smiley graphic) and the new dimensions (our
new random self.scale value as the width and height of the trans-
formed image), and it returns the scaled (up or down, bigger or
smaller) image, which we’re storing as the new self.image.
With this last change, we should now be able to use our Smiley
sprite class to draw smiley faces of random sizes and speeds all
over our screen with drawing code similar to our DragDots.py
drawing app, plus a few changes.
Free download pdf