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

(singke) #1

Before you add sound to your game, make sure the sound output is working properly on your
Raspberry Pi. If you have your Raspberry Pi hooked up to a television or a computer monitor with
built-in speakers through HDMI, then sound will be traveling over the HDMI cable. If you don’t have
either one of those options, you can hook up a set of computer speakers to the standard 3.5 mm audio-
out port. (Review Hour 1, “Setting Up the Raspberry Pi,” for more help with this setup.)


To test your sound, you can use one of the sound files from the pre-installed Python games in the
/home/pi/python_games directory. A nice loud one is the match1.wav file. At the
command line, type sudo aplay /home/pi/python_games/match1.wav. You should
hear a sound. If you don’t, you may need to adjust your volume or conduct other sound troubleshooting
techniques.


To add a sound to your game, you use the pygame.mixer module to create a Sound object
variable, as in this example:


Click here to view code image


# Setup Game Sound ######
ClickSound=pygame.mixer.Sound('/home/pi/python_games/match1.wav')

Once you have your Sound object created, you can play it by using the .play method, as shown
here:


#
ClickSound.play()
time.sleep(.25)

Notice that in the example, after the sound is played, the time.sleep method is used, with a sleep
time of 1/4 second that adds a little delay to the game. (Without this delay, you might not hear the
sound play due to buffering issues.)


A better way to handle the needed delay in a game script, so that a sound can be heard, is to use the
pygame.time.delay method. This method is superior in that you do not have to load the time
module (which slows down the game), and you can finely tune the delay time. The
pygame.time.delay method uses milliseconds as its arguments instead of seconds. Thus, to play
a sound, you use code like this:


#
ClickSound.play()
pygame.time.delay(300)

Notice that this example delays the game by 300 milliseconds. Now your sound will play, and the
game will be a little bit faster.


Dealing with PyGame Action


At this point, you have text, an image, and sound in your game script. You’re now ready to get things
moving.


Moving Graphics Around the Game Screen


Like a motion picture, graphics moving around your screen are an illusion. What happens “behind the
scene” is that the images are redrawn quickly enough to give the appearance of movement. To
simulate the appearance of movement in a Python script, you can use the Surface object’s

Free download pdf