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

(vip2019) #1
Timers and Animation: What Would Disney Do? 193

Our CrazySmile.bmp file measures 100 pixels across (and
100 pixels down). So if our screen is currently 600 pixels wide and
the pic image needs 100 pixels to display the full image, our picx
has to stay left of 500 pixels in the x-direction. Figure 8-8 shows
these measurements.


600px

(picx,picy)

100px

Bounce!

500px

Figure 8-8: Calculating a bounce against the right side
of the window


But what if we change our image file or want to handle images
of different widths and heights? Fortunately, Pygame has a conve-
nient function in the pygame.image class that our picture variable pic
uses. The function pic.get_width() returns the width in pixels of the
image stored in the pygame.image variable pic. We can use this func-
tion instead of hardcoding our program to handle only an image
that measures 100 pixels wide. Similarly, pic.get_height() gives us
the height in pixels of the image stored in pic.
We can test whether the image
pic is going off the right side of the
screen with a statement like this:


if picx + pic.get_width() > 600:


In other words, if the starting
x-coordinate of the picture, plus
the picture’s width, is greater
than the width of the screen, we’ll
know we’ve gone off the right edge
of the screen, and we can change
the image’s direction of motion.

Free download pdf