点击鼠标在 Pygame Zero 中播放随机声音

问题描述 投票:0回答:1

我希望我正在编写的游戏能够在用户得到正确答案时播放随机的“成功”噪音。我无法让 pygame 0 优雅地完成此操作(目前我的代码很冗长)

感觉这应该可以通过调用随机列表元素或随机化声音文件的字符串来实现。我尝试创建声音文件列表并选择随机元素,但 pygame 0 不喜欢这样。我还尝试了下面这个问题底部的简单解决方案。

以下确实有效,但我想要一种更优雅的编码方式:

if index == question[5]:
                print("You got it right!")
                score += 1
                print("Questions answered: " + str(question_count+1))
                rand_sound = randint(1,12)
                if rand_sound == 1:
                    sounds.yes1.play()
                elif rand_sound == 2:
                    sounds.yes2.play()
                elif rand_sound == 3:
                    sounds.yes3.play()
                elif rand_sound == 4:
                    sounds.yes4.play()
                elif rand_sound == 5:
                    sounds.yes5.play()
                elif rand_sound == 6:
                    sounds.yes6.play()
                elif rand_sound == 7:
                    sounds.yes7.play()
                elif rand_sound == 8:
                    sounds.yes8.play()
                elif rand_sound == 9:
                    sounds.yes9.play()
                elif rand_sound == 10:
                    sounds.yes10.play()
                elif rand_sound == 11:
                    sounds.yes11.play()
                elif rand_sound == 12:
                    sounds.yes12.play()

然而以下内容不起作用(我收到错误消息“AttributeError:找不到像'rand_sound'这样的声音。您确定声音存在吗?”)

rand_sound = "yes" + str(randint(1,12))
sounds.rand_sound.play()
python pgzero
1个回答
0
投票

官方文档中没有,但您可以使用

sounds.load(name)
方法通过将名称作为字符串传递来获取声音对象。 (Actor 类使用相同的方法来加载图像)。

这是一个最小的例子:

import pgzrun
import random

def on_mouse_down(pos):
    rand_sound = random.randint(1,3)
    sound_name = "sound" + str(rand_sound)
    sounds.load(sound_name).play()

pgzrun.go()
© www.soinside.com 2019 - 2024. All rights reserved.