Опубликован: 12.07.2013 | Доступ: свободный | Студентов: 733 / 20 | Длительность: 37:41:00
Лекция 19:

Sound and Images

< Лекция 18 || Лекция 19: 12 || Лекция 20 >
Аннотация: In this chapter, we will learn how to show pictures and images (called sprites) and play sounds and music in our games.

Topics Covered In This Chapter:

  • Image and Sound Files
  • Drawing Sprites
  • The pygame.image.load() Function
  • The pygame.mixer.Sound Data Type
  • The pygame.mixer.music Module

In the last two chapters, we've learned how to make GUI programs that have graphics and can accept input from the keyboard and mouse. We've also learned how to draw shapes in different colors on the screen. In this chapter, we will learn how to show pictures and images (called sprites) and play sounds and music in our games.

A sprite is a name for a single two-dimensional image that is used as part of the graphics on the screen. Here are some example sprites:

Some examples of sprites.

Рис. 19.1. Some examples of sprites.

This is an example of sprites being used in a complete scene.

An example of a complete scene, with sprites drawn on top of a background.

Рис. 19.2. An example of a complete scene, with sprites drawn on top of a background.

The sprite images are drawn on top of the background. Notice that we can flip the sprite image horizontally so that the sprites are facing the other way. We can draw the same sprite image multiple times on the same window. We can also resize the sprites to be larger or smaller than the original sprite image. The background image can also be considered one large sprite.

The next program we make will demonstrate how to play sounds and draw sprites using Pygame.

Image and Sound Files

Sprites are stored in image files on your computer. There are several different image formats that Pygame can use. You can tell what format an image file uses by looking at the end of the file name. For example, the file happy.png is in the PNG format. The image formats Pygame supports include BMP, PNG, JPG (and JPEG), and GIF.

You can download images from your web browser. On most web browsers, you just have to right-click on the image in the web page and select Save from the menu that appears. Remember where on the hard drive you saved the image file. You can also create your own images with a drawing program like MS Paint or Tux Paint.

The sound file formats that Pygame supports are MID, WAV, and MP3. You can download sound effects from the Internet just like image files, as long as the sound effects are in one of these three formats. If you have a microphone, you can also record sounds with your computer and use them in your games.

Sprites and Sounds Program

This program is the same as the Keyboard and Mouse Input program from the last chapter. However, in this program we will use sprites instead of plain looking squares. We will use a sprite of a little man instead of the white player square, and a sprite of cherries instead of the green food squares. We also play background music and a sound effect when the player sprite eats one of the cherry sprites.

The Sprites and Sounds Program's Source Code

If you know how to use graphics software such as Photoshop or MS Paint, you can draw your own images and use the image files in your games. If you don't know how to use these programs, you can just download graphics from websites and use those image files instead. The same applies for music and sound files. You can also find images on web sites or images from a digital camera. You can download the image and sound files from this book's website at http://inventwithpython.com/resources/. You can download the source code in this chapter from the URL http://inventwithpython.com/chapter19.

spritesAndSounds.py

This code can be downloaded from http://inventwithpython.com/spritesAndSounds.py If you get errors after typing this code in, compare it to the book's code with the online diff tool at http://inventwithpython.com/diff or email the author at al@inventwithpython.com

1. import pygame, sys, time, random
2. from pygame.locals import * 3.
4. # set up pygame
5. pygame.init()
6. mainClock = pygame.time.Clock() 7.
8. # set up the window
9. WINDOWWIDTH = 400
10. WINDOWHEIGHT = 400
11. windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
12. pygame.display.set_caption('Sprites and Sound') 13.
14. # set up the colors
15. BLACK = (0, 0, 0) 16.
17. # set up the block data structure
18. player = pygame.Rect(300, 100, 40, 40)
19. playerImage = pygame.image.load('player.png')
20. playerStretchedImage = pygame.transform.scale(playerImage, (40, 40))
21. foodImage = pygame.image.load('cherry.png')
22. foods = []
23. for i in range(20):
24.     foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))
25.
26. foodCounter = 0
27. NEWFOOD = 40 28.
29. # set up keyboard variables
30. moveLeft = False
31. moveRight = False
32. moveUp = False
33. moveDown = False 34.
35. MOVESPEED = 6 36.
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 42.
43. # run the game loop
44. while True:
45.     # check for the QUIT event
46.     for event in pygame.event.get():
47.         if event.type == QUIT:
48.             pygame.quit()
49.             sys.exit()
50.         if event.type == KEYDOWN:
51.             # change the keyboard variables
52.             if event.key == K_LEFT or event.key == ord ('a'):
53.                 moveRight = False
54.                 moveLeft = True
55.             if event.key == K_RIGHT or event.key == ord ('d'):
56.                 moveLeft = False
57.                 moveRight = True
58.             if event.key == K_UP or event.key == ord('w'):
59.                 moveDown = False
60.                 moveUp = True
61.             if event.key == K_DOWN or event.key == ord ('s'):
62.                 moveUp = False
63.                 moveDown = True
64.         if event.type == KEYUP:
65.             if event.key == K_ESCAPE:
66.                 pygame.quit()
67.                 sys.exit()
68.             if event.key == K_LEFT or event.key == ord ('a'):
69.                 moveLeft = False
70.             if event.key == K_RIGHT or event.key == ord ('d'):
71.                 moveRight = False
72.             if event.key == K_UP or event.key == ord('w'):
73.                 moveUp = False
74.             if event.key == K_DOWN or event.key == ord ('s'):
75.                 moveDown = False
76.             if event.key == ord('x'):
77.                 player.top = random.randint(0, WINDOWHEIGHT - player.height)
78.                 player.left = random.randint(0, WINDOWWIDTH - player.width)
79.             if event.key == ord('m'):
80.                 if musicPlaying:
81.                     pygame.mixer.music.stop()
82.                 else:
83.                     pygame.mixer.music.play(-1, 0.0)
84.                 musicPlaying = not musicPlaying 85.
86.         if event.type == MOUSEBUTTONUP:
87.             foods.append(pygame.Rect(event.pos[0] - 10, event.pos[1] - 10, 20, 20))
88.
89.     foodCounter += 1
90.     if  foodCounter >= NEWFOOD:
91.         # add new food
92.         foodCounter = 0
93.         foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))
94.
95.     # draw the black background onto the surface
96.     windowSurface.fill(BLACK) 97 .
98.     # move the player
99.      if moveDown and player.bottom < WINDOWHEIGHT:
100.         player.top += MOVESPEED
101.      if moveUp and player.top > 0:
102.         player.top -= MOVESPEED
103.      if moveLeft and player.left > 0:
104.         player.left -= MOVESPEED
105.      if moveRight and player.right < WINDOWWIDTH:
106.         player.right += MOVESPEED
107 .
108 .
109.     # draw the block onto the surface
110.     windowSurface.blit(playerStretchedImage, player)
111.
112.     # check if the block has intersected with any food squares.
113.      for food in foods[:]:
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() 120 .
121.     # draw the food
122.      for food in foods:
123.         windowSurface.blit(foodImage, food) 124 .
125.     # draw the window onto the screen
126.     pygame.display.update()
127.     mainClock.tick(40)
The Sprites and Sounds game.

Рис. 19.3. The Sprites and Sounds game.
< Лекция 18 || Лекция 19: 12 || Лекция 20 >
Асмик Гаряка
Асмик Гаряка
Армения, Ереван