pygame.image.load() Function
pygame.mixer .Sound Data Type
pygame.mixer .music Module
In the last two chapters, we've learned how to make
A sprite is a name for a single two-
(рис 19.1) Some examples of sprites.
This is an example of
(рис 19.2) An example of a complete scene, with sprites drawn on top of a background.
The
The next program we make will demonstrate how to play sounds and draw
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
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
This program is the same as the Keyboard and Mouse Input program from the last chapter. However, in this program we will use
If you know how to use
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)
(рис 19.3) The Sprites and Sounds game.
Most of the code in this program was explained in the previous chapter, so we will only focus on the parts that add
12. pygame.display.set_caption('Sprites and Sound')
First, let's set the caption of the ' to the pygame.display.set_caption() function.
17. # set up the block data structure
18. player = pygame.Rect(3 00, 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')
We are going to use three different variables to represent the player, unlike the previous programs that just used one. The player variable will store a Rect object that keeps 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.
On line 20, we will use a new function in the pygame.transform module. The pygame.transform.scale() function can shrink or 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 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 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.)
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 pygame. module is responsible for playing short sound effects during the game. The pygame. module is used for playing
We will call the pygame. constructor function to create a pygame. object (which we will simply call a Sound object). This object has a play() method that when called will play the sound effect.
On line 39 we load the
pygame.. The first parameter tells Pygame how many times to play the 5 will cause Pygame to play the -1 for the first parameter, the
The second parameter to pygame. tells at what point in the sound file to start playing. Passing 0.0 will play the 2.5 for the second parameter, this will cause the
Finally, we have a simple boolean variable named musicPlaying that will tell our program if it should play the
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
We will check if the user has pressed the M key. The M key will turn the musicPlaying is set to True, then that means the
pygame.. If musicPlaying is set to False, then that means the pygame.. The parameters we pass to the pygame. function are the same as we passed on line 40.
Finally, no matter what, we want to toggle the value in musicPlaying. Toggling a boolean value means we set it to the opposite of its current value. The line musicPlaying = not musicPlaying will set the variable to False if it is currently True or set it to True if it is currently False. Think of toggling as what happens when you flip a light switch on or off.
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.
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 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_mode().)
The second parameter to the method is a Rect object that specifies where the Rect object stored in player is what keeps track of the position of the player in the window.
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 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 playerStretchedImage. Stretching an image often distorts it a little. If we keep restretching a stretched image over and over, the distortions add up quickly. But by stretching the original image to the new size, we only distort the image once. This is why we pass playerImage as the first argument for pygame.transform.scale().
121. # draw the food 122. for food in foods: 123. windowSurface.blit(foodImage, food)
In our previous programs, we called the pygame.draw.rect() function to draw a green square for each Rect object stored in the foods list. However, in this program w want to draw the cherry method and pass the Surface object stored in foodImage. (This is the surface that has the image of cherri drawn on it.)
We only use the food variable (which contains each of the Rect objects in foods o each iteration through the for loop) to tell the method where to draw the foodImage.
This game has added even more advanced graphics and introduced using sound in our games. The images (called
Now that we know how to create a GUI window, display
Для получения официальных документов о завершении программы дополнительного профессионального образования (удостоверения о повышении квалификации, дипломов о профессиональной переподготовке и MBA) необходимо предоставить:
Внимание! Вы можете не заказывать доставку бумажной версии официального документы, а скачать его в электронном виде и распечатать самостоятельно. Информация о выданном документе в течение 1 месяца загружается в Федеральную информационную систему «Федеральный реестр сведений о документах об образовании и (или) о квалификации, документах об обучении» - ФИС ФРДО.
Доступ на новый сайт осуществляется с использованием адреса электронной почты, который был указан вами при регистрации на "старом". Мы постарались перенести все ваши данные с прежнего ресурса, однако не исключена вероятность потери части информации.
При возникновении проблемы со входом, воспользуйтесь функцией сброса пароля
Если вы обнаружите несоответствия, пожалуйста, сообщите нам.