You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pygame Zero中实现答对题目时播放随机成功音效

优雅实现Pygame Zero随机播放成功音效

方案一:动态获取音效属性

直接通过字符串动态获取sounds对象对应的音效属性,替代冗长的条件判断:

import random

if index == question[5]:
    print("You got it right!")
    score += 1
    print(f"Questions answered: {question_count+1}")
    # 生成随机音效名称
    sound_name = f"yes{random.randint(1,12)}"
    # 通过getattr动态获取音效并播放
    getattr(sounds, sound_name).play()

方案二:预加载音效列表(更高效)

提前将所有成功音效存入列表,后续直接随机选择播放,避免重复调用getattr:

import random

# 在游戏初始化阶段执行一次,预加载所有成功音效
success_sounds = [getattr(sounds, f"yes{i}") for i in range(1, 13)]

# 答对题目时的逻辑
if index == question[5]:
    print("You got it right!")
    score += 1
    print(f"Questions answered: {question_count+1}")
    # 随机选择列表中的音效播放
    random.choice(success_sounds).play()

为什么你的简化代码报错?

你之前的代码sounds.rand_sound.play()是在尝试访问sounds对象中名为rand_sound的属性,而不是变量rand_sound存储的字符串(比如yes5)对应的属性。getattr()函数可以通过字符串参数获取对象的属性,完美解决这个问题。

内容的提问来源于stack exchange,提问作者Ben Darvill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 20:50:17