使用 Arcade Library 开发 2D 游戏(第10部分):播放音效

发布: (2025年12月24日 GMT+8 20:07)
6 min read
原文: Dev.to

Source: Dev.to

请提供您希望翻译的完整文本内容,我将为您翻译成简体中文并保留原有的格式、Markdown 语法以及技术术语。谢谢!

准备声音文件

创建一个新的 sounds 文件夹,并将以下声音文件放入其中。

声音文件名
下载 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)

如果没有声音,请检查:

  • 您的电脑音量或静音设置
  • 声音文件的路径是否正确

完整代码

以下是截至目前已实现的全部功能的完整代码。您可以直接复制并运行它。

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):
        # Stop movement when key is released
        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)

        # Check for collisions between player and coins
        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"SCORE: {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, "Arcade Sound Demo")
    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()

全屏控制

  • 进入全屏模式 – press F (or use the window menu).
  • 退出全屏模式 – press Esc (or use the window menu).

预期结果

游戏应能运行,并且每当收集到硬币时都会播放硬币收集音效。

游戏演示

最后思考

非常感谢阅读。

这标志着 “使用 Arcade 库入门 2D 游戏” 的结束。恭喜你完成本系列!!

我们创建的游戏非常简单,但它包含了游戏开发的所有基础要素:

  • 精灵管理
  • 键盘输入
  • 声音播放

如果你已经理解到目前为止的所有内容,你现在应该能够独立使用 Arcade 创建简单的游戏。

我强烈建议以此处学到的知识为基础,尝试制作自己的小型游戏。

我希望本系列能成为你游戏开发的起点。ޱ(ఠ皿ఠ)ว

(如果你喜欢本系列,点赞 👍 将不胜感激!)

Back to Blog

相关文章

阅读更多 »