Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
TABLE 19.4 A Few pygame.draw Module Methods

By the Way: Get Help
Don’t forget that help is readily available on each of the pygame.draw module’s
methods. You learned about getting help for modules in Hour 13. You can get into the
Python interactive shell by typing python3, and then you can load PyGame by typing
import pygame. You can see all the available methods for pygame.draw (or
any other module) by typing help(pygame.draw). You can get help on an
individual method, such as pygame.draw.circle, by typing
help(pygame.draw.circle). The help shows you a description and all the
needed arguments for each method. Remember to press Q to quit out of help when you
are done.

You need to do a more work to put an image on your game screen. First, be aware that the PyGame
library may not be built to support all image file formats. You can find out more by using the
pygame.image module and the .get_extended method. Listing 19.6 shows an example.


LISTING 19.6 Testing PyGame for Image Handling


Click here to view code image


>>> import pygame
>>> pygame.image.get_extended()
1
>>>

Within the Python interactive shell, if you issue the command pygame.image.get_extended
and it returns 1 (for true), then you have support for most image file types, including .png, .jpg,
.gif, and others. However, if it returns 0 (False), then you can use only uncompressed .bmp image
files. After you determine what image files your PyGame library can handle, you can choose an
image to load into a game from the appropriate image file.


To load an image into your Python game script, you need to use the pygame.image.load method.
Before you do so, it’s best to set up a variable name to contain the image file, as shown in this
example:


Click here to view code image


# Set up the Game Image Graphics
GameImage="/usr/share/raspberrypi-artwork/raspberry-pi-logo.png"
GameImageGraphic=pygame.image.load(GameImage)

This works fine, except that it can be a little slow when loading the image. In fact, it will be slow
every time the image has to be redrawn on the screen. To speed it up, you can use the .convert
method instead on the image, as shown here:


Click here to view code image


# Set up the Game Image Graphics
GameImage="/usr/share/raspberrypi-artwork/raspberry-pi-logo.png"
GameImageGraphic=pygame.image.load(GameImage).convert()
Free download pdf