Pygame platform game 5: sounds and mixer

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:

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:

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:

pygame.mixer.Sound.play(jump_sound)

The soundtrack in background

To load and play a soundtrack continuosly:

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:

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


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.