Menu
CoddyTech

Sound on an Event

Part of the Sound and Game Feel section of Coddy's Pygame journey. Lesson 2 of 23.

A sound belongs to a moment: the coin is taken, the door opens, the enemy is hit. Your code already has a place for each moment, the if that changes the game when it happens. Play the sound inside that same if:

if player.colliderect(coin):
    score += 1
    coin_sound.play()
    coin.x = random.randint(20, 444)

The if is true for one frame only, because the coin moves away in the same frame. So the sound starts once per coin.

Played anywhere else, the sound loses its moment. In the drawing code under if score > 0: it would start again on every frame after the first coin: 60 times a second, one long buzz.

challenge icon

Challenge

Easy

Give each coin a sound.

  1. Before the loop, load assets/sounds/coin.ogg into coin_sound.
  2. Play it in the if that collects the coin, once per coin.

Press Play and collect a coin with the arrows: you hear it. Then Check.

Try it yourself

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Coins")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)

player = pygame.Rect(220, 160, 40, 40)
coin = pygame.Rect(100, 100, 16, 16)
score = 0

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        player.x -= 5
    if keys[pygame.K_RIGHT]:
        player.x += 5
    if keys[pygame.K_UP]:
        player.y -= 5
    if keys[pygame.K_DOWN]:
        player.y += 5
    player.clamp_ip(screen.get_rect())

    if player.colliderect(coin):
        score += 1
        coin.x = random.randint(20, 444)
        coin.y = random.randint(50, 324)

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (255, 210, 60), coin)
    pygame.draw.rect(screen, (90, 200, 120), player)
    score_text = font.render(f"Coins: {score}", True, (240, 240, 240))
    screen.blit(score_text, (10, 10))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sound and Game Feel

Practice on your own: Pygame playground