In this episode we will talk about sounds. How to add them in pygame? I found that it was a bit laggy, i.e. there was a delay between the pressing of the button to jump and the release of the sound, but I found a little trick that lets you get rid of the latency, fortunately. Here is the code for the sound. Be careful to the order of the statements, it is very important to avoid the issue I just mentioned:
1 2 3 4 5 |
pygame.mixer.pre_init(44100, -16, 1, 512) pygame.init() pygame.mixer.quit() pygame.mixer.init(22050, -16, 2, 512) pygame.mixer.set_num_channels(32) |
The trick here is to put pre_init before pygame init(). Someone also wrote on stackoverflow that he used to quit() the mixer befor the .init method. I experimented and decided to leave them both as you see above. The frequency rate… I think should be the same (44100 or 22050… maybe you should choose only one type, not like I did, but it does not cause me any problem at the moment… I will change it later on). You can also change the buffer size (512 to 1024…), experiment.
This is just to initialize the sound to play you have to load the sounds like this:
1 2 |
jump_sound = pygame.mixer.Sound('data/audio/jump.wav') grass_sound = pygame.mixer.Sound('data/audio/grass_0.wav') |
Then, to play them effectively, you gotta place this statements where you want the sound to play:
1 |
pygame.mixer.Sound.play(jump_sound) |
The soundtrack in background
To load and play a soundtrack continuosly:
1 2 |
pygame.mixer.music.load('data/audio/music2.wav') pygame.mixer.music.play(-1) |
The whole code
For the moment we will stop here. In another video I will talk about the other stuff I am changing in the game. This is the code, until now:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 |
from pygame.locals import * import pygame import time map1 =""" wssss sss sss ss ss sw w w w w w wwwwww sssss www www w s w w w w w w wwwww ssssw ww wwww w wwwwww w w w w w s www wwww w w w w w w w wwwwwwwwwwwww w w w w w wwwwwww w w w wwwwwwwwwwwwwwwwwwwwwwwwwwwww""".splitlines() map2 = """w w w w w ssswwwss sssss w wwsss w w w ww www ss w ww w w w ww ssss www sss w ww wwwsss w ww w w w w ww www ws sw w ww w w w s w w ssswsssssssss w w w s ssssss w w w wwwwwwwwwwwwwwwwwwwwwwwwwwww""".splitlines() WINDOW_SIZE = 1150, 640 game_map = map1 # The game_map contains the list with the symbols #=========== # NUSIC #=========== pygame.mixer.pre_init(44100, -16, 1, 512) pygame.init() pygame.mixer.quit() pygame.mixer.init(22050, -16, 2, 512) pygame.mixer.set_num_channels(32) # =================================== jump_sound = pygame.mixer.Sound('data/audio/jump.wav') grass_sound = pygame.mixer.Sound('data/audio/grass_0.wav') # ======== Continuous music in background pygame.mixer.music.load('data/audio/music2.wav') pygame.mixer.music.play(-1) # ======== Game init, Clock and global vars === pygame.display.set_caption('Game') screen = pygame.display.set_mode(WINDOW_SIZE, 0, 32) display = pygame.Surface((WINDOW_SIZE[0] // 2.5, WINDOW_SIZE[1] // 2.5)) clock = pygame.time.Clock() font = pygame.font.Font(None, 32) font2 = pygame.font.Font(None, 16) # awareness of direction and position moving_right = False moving_left = False # stay_right = True gravity = 0 air_timer = 0 player_image = pygame.image.load('imgs\\player.png') player_jump = pygame.image.load('imgs\\player_up2.png') player_jumpl = pygame.transform.flip(player_jump, 1, 0) player_climb = pygame.image.load('imgs\\player_climb.png') player_climbl = pygame.transform.flip(player_climb, 1, 0) player_stand = pygame.image.load('imgs\\player_stand.png') # player_img.set_colorkey((255, 255, 255)) p_right = player_image p_left = pygame.transform.flip(player_image, 1, 0) player_img = p_right bg = pygame.image.load("imgs\\bg.png") # bg2 = pygame.image.load("imgs\\bg2.png") # Rectangles for collisions player_rect = pygame.Rect(100, 100, 5, 13) starting_pos = 100 health = pygame.image.load("imgs\\health.png") health_rect = pygame.Rect(150, 225, 16, 16) # climber 5 stamina = 100 def load_tiles(): #symbols and relative image symb_img = [ # ("o", "dirt"), # ("x", "grass"), # ("<", "grassr"), # (">", "grassl"), (" ", "space"), # ("d", "door"), ("w", "wall"), ("s", "wall_s")] dr = "imgs\\" tl = {} for i in symb_img: tl[i[0]] = pygame.image.load(f'{dr}{i[1]}.png') return tl tl = load_tiles() # ============= # Functions # ============= def collision_test(rect, tiles): "Returns the Rect of the tile with which the player collides" global stamina hit_list = [] for tile in tiles: if rect.colliderect(tile): hit_list.append(tile) if rect.colliderect(health_rect): if stamina < 100: stamina += 10 print("Recovering") return hit_list collision_types = { 'top': False, 'bottom': False, 'right': False, 'left': False} goingright = 0 def move(rect, movement, tiles): global player_img global air_timer, gravity, collision_types, moving_right, moving_left global goingright global stamina global player_altitude global starting_pos player_altitude = player_rect.y collision_types = { 'top': False, 'bottom': False, 'right': False, 'left': False} rect.x += movement[0] tile = collision_test(rect, tiles) if tile != []: tile = tile[0] # ===================> MOVE RIGHT if moving_right: rect.right = tile.left collision_types['right'] = True goingright = 1 gravity = -1 player_img = player_climb stamina -= 0.02 # ====================> MOVE LEFT elif moving_left: goingright = 0 rect.left = tile.right collision_types['left'] = True gravity = -1 player_img = player_climbl stamina -=0.02 rect.y += movement[1] hit_list = collision_test(rect, tiles) for tile in hit_list: # === DOWN: falls? === if movement[1] > 0: # If it was falling down if (rect.bottom - starting_pos) > 50: print(rect.bottom - starting_pos) stamina -= 30 pygame.mixer.Sound.play(grass_sound) time.sleep(2) starting_pos = rect.bottom rect.bottom = tile.top collision_types['bottom'] = True if not moving_left and not moving_right and gravity > 0: player_img = player_stand elif movement[1] < 0: player_img = player_jump gravity = -3 # = -1 it attaches to the wall attached = rect.top = tile.bottom stamina -= 0.03 #collision_types['top'] = False if collision_types['bottom']: air_timer = 0 gravity = 0 else: air_timer += 1 return rect def display_tiles(): "Makes the Rects for the 'physics'" tile_rects = [] y = 0 for line_of_symbols in game_map: x = 0 for symbol in line_of_symbols: if symbol == "\n": symbol = " " display.blit(tl[symbol], (x * 16, y* 16)) if symbol not in " h": pass tile_rects.append(pygame.Rect(x * 16, y * 16, 16, 15)) x += 1 y += 1 return tile_rects player_altitude = player_rect.y def display_player(pim): #player_img = p_right if stay_right else p_left display.blit(health, (150, 225)) display.blit(pim, (player_rect.x, player_rect.y)) # 500, 500, 50, 50 def display_stamina(): #player_img = p_right if stay_right else p_left print("health") def display_bg(): "Displays the background" global WINDOW_SIZE display.blit(bg, (0, 0)) def _display(fnt, what, color, where): text_to_show = font.render(what, 0, pygame.Color(color)) display.blit(text_to_show, where) def display_text(): # fps _display( font, what = str(int(clock.get_fps())), color = "white", where = (0,0)), _display(font2, what = "Wall climber", color = 'blue', where = (100,0)) _display(font2, what = "Stamina: " + str(int(stamina)), color = 'coral', where = (300,0)) _display(font2, what = "altitude: " + str(int(player_altitude)), color = 'coral', where = (300, 40)) def clear_screen(): display.fill((73, 184, 250)) VELOCITY = 1 #*falling def move_player(): global loop, player_rect, moving_right, air_timer, moving_left, gravity, collision_types, player_img, stamina player_movement = [0, 0] #*falling # if stamina < 0: # loop = 0 # MOVES THE PLAYER WHEN GOES RIGHT OR LEFT if moving_right: player_movement[0] += VELOCITY stamina += 0.005 if moving_left: player_movement[0] -= VELOCITY stamina += 0.005 player_movement[1] += gravity gravity += 0.3 if gravity > 3: gravity = 3 player_rect = move(player_rect, player_movement, tile_rects) # ============ Keyboard pressing detection for event in pygame.event.get(): if event.type == QUIT: loop = 0 if event.type == KEYDOWN: if event.key == K_RIGHT: player_img = p_right moving_right = True if event.key == K_LEFT: player_img = p_left moving_left = True # ======== # JUMP # ======== if event.key == K_UP: if air_timer < 6: gravity = -5 stamina -= 3 pygame.mixer.Sound.play(jump_sound) # ========== # DOWN # ========== if event.key == K_DOWN: if air_timer == 0: player_img = player_jump gravity = +1 elif event.type == KEYUP: if event.key == K_RIGHT: moving_right = False if event.key == K_LEFT: moving_left = False return player_img def scale_screen(): screen.blit(pygame.transform.scale(display, WINDOW_SIZE), (0, 0)) loop = 1 while loop: stamina -= 0.001 clear_screen() tile_rects = display_tiles() player_img = move_player() display_player(player_img) display_text() scale_screen() pygame.display.update() clock.tick(60) pygame.quit() print("Game over") """ ------- new in pygame: The climber tutorial 5 ----------- diplay_text shows fps, title and stamina """ |
The images
These go into imgs folder
The video about sounds in Pygame
Pygame's Platform Game
