파이썬으로 만드는 나만의 게임 개발 강좌 7강 – 배경음악과 효과음 추가하기

파이썬으로 만드는 나만의 게임 개발 강좌 7강입니다!

이전 강의에서 점수판을 만들고 실시간으로 점수를 출력하는 기능까지 구현했죠. 이번 강의에서는 게임의 분위기와 몰입도를 크게 높여줄 **사운드** 기능을 추가해보겠습니다.

이번 강의 목표

  • 배경 음악(BGM) 설정
  • 효과음(SFX) 설정 및 재생
  • 이벤트에 따라 효과음 재생하기

1. Pygame에서의 사운드 처리 방식

Pygame에서는 두 가지 주요 기능을 사용해 소리를 재생할 수 있습니다.

  • pygame.mixer.music – 배경 음악 재생
  • pygame.mixer.Sound – 효과음 재생

음원 파일 형식은 보통 **.mp3, .wav, .ogg** 등을 사용할 수 있지만, **.wav 파일이 가장 안정적으로 작동**합니다.


2. 사운드 파일 준비하기

다음과 같은 사운드 파일을 준비해주세요.

  • bgm.mp3 – 게임 전체 배경 음악
  • item.wav – 아이템 획득 효과음

위 파일들을 게임 소스와 같은 폴더에 저장하면 됩니다.


3. 전체 코드 예시

import pygame
import random

pygame.init()

# 화면 설정
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("사운드 적용 예제")

# 사운드 초기화
pygame.mixer.init()

# 배경 음악 재생 (무한 반복)
pygame.mixer.music.load("bgm.mp3")
pygame.mixer.music.play(-1)

# 효과음 로드
item_sound = pygame.mixer.Sound("item.wav")

# 이미지 불러오기
background = pygame.image.load("background.png")
character = pygame.image.load("character.png")
item = pygame.image.load("item.png")

# 캐릭터 설정
char_size = character.get_rect().size
char_w = char_size[0]
char_h = char_size[1]
char_x = (screen_width - char_w) / 2
char_y = screen_height - char_h

# 이동 속도 및 변수
to_x = 0
to_y = 0
speed = 0.5

# 아이템 위치 설정
item_size = item.get_rect().size
item_w = item_size[0]
item_h = item_size[1]
item_x = random.randint(0, screen_width - item_w)
item_y = random.randint(0, screen_height - item_h)

# 점수
score = 0
font = pygame.font.Font(None, 40)

clock = pygame.time.Clock()
running = True

while running:
    dt = clock.tick(60)

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

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                to_x -= speed
            elif event.key == pygame.K_RIGHT:
                to_x += speed
            elif event.key == pygame.K_UP:
                to_y -= speed
            elif event.key == pygame.K_DOWN:
                to_y += speed

        if event.type == pygame.KEYUP:
            if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:
                to_x = 0
            if event.key in [pygame.K_UP, pygame.K_DOWN]:
                to_y = 0

    char_x += to_x * dt
    char_y += to_y * dt
    char_x = max(0, min(screen_width - char_w, char_x))
    char_y = max(0, min(screen_height - char_h, char_y))

    char_rect = character.get_rect(topleft=(char_x, char_y))
    item_rect = item.get_rect(topleft=(item_x, item_y))

    if char_rect.colliderect(item_rect):
        score += 10
        item_sound.play()
        item_x = random.randint(0, screen_width - item_w)
        item_y = random.randint(0, screen_height - item_h)

    screen.blit(background, (0, 0))
    screen.blit(character, (char_x, char_y))
    screen.blit(item, (item_x, item_y))

    score_display = font.render(f"Score: {score}", True, (255, 255, 0))
    screen.blit(score_display, (10, 10))

    pygame.display.update()

pygame.quit()

4. 사운드 관련 팁

  • 배경 음악은 play(-1) 로 무한 반복이 가능합니다.
  • Sound.play() 는 효과음 재생 시 지연 없이 바로 동작합니다.
  • .wav 파일은 빠르게 로딩되며 호환성이 좋습니다.

5. 확장 아이디어

  • 게임 오버 시 긴장감 있는 효과음 재생
  • 키 입력 또는 충돌마다 서로 다른 효과음 지정
  • 설정창에서 사운드 ON/OFF 기능 추가

6. 다음 강의 예고

8강: 게임 시작 화면과 종료 화면 만들기 – 타이틀 및 게임 오버 UI
다음 강의에서는 게임을 시작하기 전 보여줄 타이틀 화면과, 게임이 끝난 후 보여줄 게임 오버 화면을 만들어봅니다. 디자인 요소가 더해지며 완성도 높은 게임으로 거듭나게 될 거예요!

이 강의는 Pygame 기반의 파이썬 게임 개발 시리즈입니다. 기초부터 실전까지 단계별로 함께하고 있어요!