Arcade 라이브러리를 사용한 2D 게임 시작하기 (Part 10): 사운드 효과 재생

발행: (2025년 12월 24일 오후 09:07 GMT+9)
7 min read
원문: Dev.to

Source: Dev.to

Source:

사운드 파일 준비

새로운 sounds 폴더를 만들고 그 안에 다음 사운드 파일을 넣으세요.

소리파일 이름
Download se_coin.oggse_coin.ogg

GitHub에서 파일을 직접 다운로드할 수 없는 경우, 페이지 오른쪽 상단에 있는 Download 버튼을 사용하세요.

폴더 구조는 다음과 같이 보여야 합니다:

# Folder structure
working_directory/
├─ main.py
├─ sprite.py
├─ images/
└─ sounds/        # Folder for sound files
   └─ se_coin.ogg

사운드 객체 만들기

arcade.Sound()에 사운드 파일 경로를 전달하면 사운드 객체를 생성할 수 있습니다.

# main.py (excerpt)

# Sound object
self.se_coin = arcade.Sound("sounds/se_coin.ogg")

사운드 재생

생성한 사운드 객체를 arcade.play_sound()에 전달하여 재생할 수 있습니다.

# main.py (excerpt)

# Play the sound
arcade.play_sound(self.se_coin)

소리가 들리지 않을 경우, 다음을 확인하십시오:

  • PC 볼륨 또는 음소거 설정
  • 사운드 파일 경로가 올바른지 여부

전체 코드

아래는 지금까지 구현된 모든 기능을 포함한 전체 코드입니다. 그대로 복사해서 실행할 수 있습니다.

sprite.py (완전)

import arcade
import math

class BaseSprite(arcade.Sprite):
    def __init__(self, filename, x, y):
        super().__init__(filename)
        # Position
        self.center_x = x
        self.center_y = y
        # Velocity
        self.vx = 0
        self.vy = 0
        # Animation
        self.anim_counter = 0
        self.anim_interval = 4
        self.anim_index = 0
        self.anim = []

    def update(self, delta_time):
        """Update position and animation."""
        self.center_x += self.vx * delta_time
        self.center_y += self.vy * delta_time
        self.update_animation()

    def move(self, spd, deg):
        """Move sprite."""
        rad = deg * math.pi / 180
        self.vx = spd * math.cos(rad)
        self.vy = spd * math.sin(rad)

    def stop(self):
        """Stop sprite."""
        self.vx = 0
        self.vy = 0

    def update_animation(self):
        """Handle frame animation."""
        if not self.anim:
            return
        self.anim_counter += 1
        if self.anim_counter < self.anim_interval:
            return
        self.anim_counter = 0
        self.anim_index = (self.anim_index + 1) % len(self.anim)
        self.texture = self.anim[self.anim_index]

class Player(BaseSprite):
    def __init__(self, filename, x, y):
        super().__init__(filename, x, y)

        self.anim.extend([
            arcade.load_texture("images/ninja/front_01.png"),
            arcade.load_texture("images/ninja/front_02.png"),
            arcade.load_texture("images/ninja/front_03.png"),
            arcade.load_texture("images/ninja/front_04.png"),
            arcade.load_texture("images/ninja/front_05.png"),
        ])

class Coin(BaseSprite):
    def __init__(self, filename, x, y):
        super().__init__(filename, x, y)

        self.anim.extend([
            arcade.load_texture("images/coin/coin_01.png"),
            arcade.load_texture("images/coin/coin_02.png"),
            arcade.load_texture("images/coin/coin_03.png"),
            arcade.load_texture("images/coin/coin_04.png"),
            arcade.load_texture("images/coin/coin_05.png"),
        ])

main.py (완전)

import arcade
import random
import sprite

class GameView(arcade.View):
    def __init__(self, window):
        super().__init__()
        self.window = window
        self.w = self.window.width
        self.h = self.window.height

        # Background color
        self.background_color = arcade.color.PAYNE_GREY

        # Background sprites
        self.backgrounds = arcade.SpriteList()
        bkg = arcade.Sprite("images/bg_temple.png")
        bkg.center_x = self.w / 2
        bkg.center_y = self.h / 2
        self.backgrounds.append(bkg)

        # Player sprite
        self.players = arcade.SpriteList()
        self.player = sprite.Player(
            "images/ninja/front_01.png",
            x=self.w / 2,
            y=self.h / 2,
        )
        self.players.append(self.player)

        # Coin sprites
        self.coins = arcade.SpriteList()
        for _ in range(10):
            x = random.random() * self.w
            y = random.random() * self.h
            coin = sprite.Coin(
                "images/coin/coin_01.png",
                x=x,
                y=y,
            )
            self.coins.append(coin)

        # Score
        self.score = 0
        self.score_text = arcade.Text(
            f"SCORE: {self.score}",
            self.w / 2,
            self.h - 20,
            arcade.color.BLACK,
            16,
            anchor_x="center",
            anchor_y="top",
        )

        # Sound object
        self.se_coin = arcade.Sound("sounds/se_coin.ogg")

    def on_key_press(self, key, key_modifiers):
        # Move (WASD)
        if key == arcade.key.W:
            self.player.move(90, 90)
        if key == arcade.key.A:
    self.player.move(90, 180)
        if key == arcade.key.S:
            self.player.move(90, 270)
        if key == arcade.key.D:
            self.player.move(90, 0)

    def on_key_release(self, key, key_modifiers):
        # 키를 놓을 때 움직임을 멈춤
        if key in (arcade.key.W, arcade.key.A, arcade.key.S, arcade.key.D):
            self.player.stop()

    def on_update(self, delta_time):
        self.players.update(delta_time)
        self.coins.update(delta_time)

        # 플레이어와 코인 간 충돌 확인
        hit_list = arcade.check_for_collision_with_list(self.player, self.coins)
        for coin in hit_list:
            self.coins.remove(coin)
            self.score += 1
            self.score_text.text = f"점수: {self.score}"
            arcade.play_sound(self.se_coin)

    def on_draw(self):
        arcade.start_render()
        self.backgrounds.draw()
        self.players.draw()
        self.coins.draw()
        self.score_text.draw()

def main():
    window = arcade.Window(800, 600, "아케이드 사운드 데모")
    game_view = GameView(window)
    window.show_view(game_view)
    arcade.run()

if __name__ == "__main__":
    main()

전체 코드 예제

import arcade

class GameView(arcade.View):
    def __init__(self, window):
        super().__init__(window)

        # --- Sprite lists ---
        self.players = arcade.SpriteList()
        self.coins = arcade.SpriteList()
        self.backgrounds = arcade.SpriteList()

        # --- Player sprite ---
        self.player = arcade.Sprite("images/player.png", scale=0.5)
        self.player.center_x = 240
        self.player.center_y = 160
        self.players.append(self.player)

        # --- Coin sprites ---
        for i in range(10):
            coin = arcade.Sprite("images/coin.png", scale=0.3)
            coin.center_x = arcade.rand_in_range(0, 480)
            coin.center_y = arcade.rand_in_range(0, 320)
            self.coins.append(coin)

        # --- Background ---
        bg = arcade.Sprite("images/background.png", scale=1.0)
        self.backgrounds.append(bg)

        # --- Score ---
        self.score = 0
        self.score_text = arcade.Text(
            f"SCORE: {self.score}",
            start_x=10,
            start_y=300,
            color=arcade.color.WHITE,
            font_size=14,
        )

        # --- Sound ---
        self.se_coin = arcade.load_sound("sounds/coin.wav")

    def on_key_press(self, key, key_modifiers):
        if key == arcade.key.W:
            self.player.move(0, 90)
        if key == arcade.key.S:
            self.player.move(0, -90)
        if key == arcade.key.A:
            self.player.move(-90, 0)
        if key == arcade.key.D:
            self.player.move(90, 0)

    def on_key_release(self, key, key_modifiers):
        self.player.stop()

    def on_update(self, delta_time):
        self.players.update(delta_time)
        self.coins.update(delta_time)

        # Check for collisions between the player and any coin
        hit_coins = arcade.check_for_collision_with_list(
            self.player,
            self.coins
        )
        for coin in hit_coins:
            coin.remove_from_sprite_lists()
            # Update score
            self.score += 1
            self.score_text.text = f"SCORE: {self.score}"
            # Play sound
            arcade.play_sound(self.se_coin)

    def on_draw(self):
        self.clear()                     # Clear the screen
        self.backgrounds.draw()
        self.players.draw()
        self.coins.draw()
        self.score_text.draw()

def main():
    """Main process."""
    window = arcade.Window(480, 320, "Hello, Arcade!!")
    game = GameView(window)
    window.show_view(game)
    arcade.run()

if __name__ == "__main__":
    main()

전체 화면 제어

  • 전체 화면 모드 진입F 키를 누르세요 (또는 창 메뉴 사용).
  • 전체 화면 모드 종료Esc 키를 누르세요 (또는 창 메뉴 사용).

예상 결과

게임이 실행되어야 하며, 동전을 수집할 때마다 동전 수집 사운드가 재생됩니다.

Gameplay demo

최종 생각

읽어 주셔서 대단히 감사합니다.

이것으로 “Arcade 라이브러리를 사용한 2D 게임 시작하기” 가 마무리됩니다. 시리즈를 끝까지 마친 것을 축하합니다!!

우리가 만든 게임은 매우 간단하지만, 게임 개발의 기본 요소들을 모두 포함하고 있습니다:

  • 스프라이트 관리
  • 키보드 입력
  • 사운드 재생

지금까지의 내용을 모두 이해했다면, 이제 스스로 Arcade로 간단한 게임을 만들 수 있을 것입니다.

여기서 배운 내용을 기반으로 삼아 직접 작은 게임을 만들어 보시길 강력히 권장합니다.

이 시리즈가 게임 개발을 위한 출발점이 되길 바랍니다. ޱ(ఠ皿ఠ)ว

(재미있으셨다면 👍 한 번 눌러주시면 감사하겠습니다!)

Back to Blog

관련 글

더 보기 »