Game Development Reference
In-Depth Information
19 - Sound and Images
Toggling the value in musicPlaying will ensure that the next time the user presses
the M key, it will do the opposite of what it did before.
Drawing the Player on the Window
109. # draw the block onto the surface
110. windowSurface.blit(playerStretchedImage, player)
Remember that the value stored in playerStretchedImage is a Surface object.
"Blitting" is the process of drawing the contents of one Surface object to another
Surface object. In this case, we want to draw the sprite of the player onto the window's
Surface object (which is stored in windowSurface ). (Also remember that the surface
used to display on the screen is the Surface object that is returned by
pygame.display.set_caption() .)
The second parameter to the blit() method is a Rect object that specifies where the
sprite should be blitted. The Rect object stored in player is what keeps track of the
position of the player in the window.
Checking if the Player Has Collided with Cherries
114. if player.colliderect(food):
115. foods.remove(food)
116. player = pygame.Rect(player.left, player.top,
player.width + 2, player.height + 2)
117. playerStretchedImage = pygame.transform.scale
(playerImage, (player.width, player.height))
118. if musicPlaying:
119. pickUpSound.play()
This code is similar to the code in the previous programs. But here we are adding a
couple of new lines. We want to call the play() method on the Sound object stored in the
pickUpSound variable. But we only want to do this if musicPlaying is set to True
(which tells us that the sound turned on).
When the player eats one of the cherries, we are going to enlarge the size of the player by
two pixels in height and width. On line 116, we create a new Rect object to store in the
player variable which will have the same sizes as the old Rect object stored in player.
Except the width and height of the new Rect object will be 2 pixels larger.
When the Rect object that represents the position and size of the player, but the image
of the player is stored in a playerStretchedImage as a Surface object. We want to
create a new stretched image by calling pygame.transform.scale() . Be sure to
pass the original Surface object in playerImage and not
Search WWH ::




Custom Search