Game Development Reference
In-Depth Information
19 - Sound and Images
track of where and how big the player is. The
player
variable doesn't contain the
player's image, just the player's size and location. At the beginning of the program, the top
left corner of the player will be located at (300, 100) and the player will have a height and
width of 40 pixels to start.
The second variable that represents the player will be
playerImage
. The
pygame.image.load()
function is passed a string of the filename of the image to
load. The return value of
pygame.image.load()
is a
Surface
object that has the
image in the image file drawn on its surface. We store this
Surface
object inside of
playerImage
.
The
pygame.transform.scale()
Function
On line 20, we will use a new function in the
pygame.transform
module. The
pygame.transform.scale()
function can shrink or enlarge a sprite. The first
argument is a
pygame.Surface
object with the image drawn on it. The second
argument is a tuple for the new width and height of the image in the first argument. The
pygame.transform.scale()
function returns a
pygame.Surface
object with the
image drawn at a new size. We will store the original image in the
playerImage
variable but the stretched image in the
playerStretchedImage
variable.
On line 21, we call
pygame.image.load()
again to create a
Surface
object with
the cherry image drawn on it.
Be sure that you have the
player.png
and
cherry.png
file in the same directory as the
spritesAndSounds.py
file, otherwise Pygame will not be able to find them and will give an
error.
The
Surface
objects that are stored in
playerImage
and
foodImage
are the same
as the
Surface
object we use for the window. In our game, we will blit these surfaces
onto the window's surface to create the window that the user sees. This is exactly the same
as the when we got a
Surface
object returned from the
render()
method for
Font
objects in our Hello World program. In order to actually display the text, we had to blit this
Surface
object (which the text was drawn on) to the window's
Surface
object. (And
then, of course, call the
update()
method on the window's
Surface
object.)
Setting Up the Music and Sounds
37. # set up music
38. pickUpSound = pygame.mixer.Sound('pickup.wav')
39. pygame.mixer.music.load('background.mid')
40. pygame.mixer.music.play(-1, 0.0)
41. musicPlaying = True
Next we need to load the sound files. There are two modules for sound in Pygame. The