Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 让Pygame播放声音一次_Python_Loops_Audio_Pygame - Fatal编程技术网

Python 让Pygame播放声音一次

Python 让Pygame播放声音一次,python,loops,audio,pygame,Python,Loops,Audio,Pygame,我有一小段代码,其中包括在满足if语句时播放一次的声音: for block in block_list: if block.rect.y >= 650 and health >=25 and score < 70: player_list.remove(player) all_sprites_list.remove(player) font = pygame.font.Font("freesansbold.ttf", 3

我有一小段代码,其中包括在满足if语句时播放一次的声音:

for block in block_list:
    if block.rect.y >= 650 and health >=25 and score < 70:
        player_list.remove(player)
        all_sprites_list.remove(player)
        font = pygame.font.Font("freesansbold.ttf", 30)
        label = font.render("SCORE TARGET NOT MET", 1, YELLOW)
        labelRect = label.get_rect()
        labelRect.center = (400, 250)

        error.play()
        laser.stop()
块列表中的块的
:
如果block.rect.y>=650,运行状况>=25,得分<70:
玩家列表。移除(玩家)
所有精灵列表。移除(玩家)
font=pygame.font.font(“freesansbold.ttf”,30)
label=font.render(“未达到分数目标”,1,黄色)
labelRect=label.get_rect()
labelRect.center=(400250)
错误。播放()
激光。停止()
但是,在播放“错误”声音时,它会继续循环,直到pygame窗口关闭。有没有办法编辑代码,使“错误”音效只播放一次


谢谢。

我猜它被反复播放,因为
if
子句的条件保持为
True
;对于
block\u列表中的多个
block
对象,可能是
True

您应该以对您的应用程序有意义的方式修复该问题

当你不知道全局时,很难给出一个好的建议,但也许一个简单的标志会帮助你:

# somewhere
play_error_sound = True

...

for block in block_list:
    if block.rect.y >= 650 and health >=25 and score < 70:
        ...
        if play_error_sound:
            play_error_sound = False
            error.play()

# set play_error_sound to True once it is allowed to be played again
#某处
播放错误声音=真
...
对于块列表中的块:
如果block.rect.y>=650,运行状况>=25,得分<70:
...
如果播放错误声音:
播放错误声音=错误
错误。播放()
#一旦允许再次播放,请将播放错误声音设置为真

请考虑在应用程序开始时只加载一次“代码”>字体>代码,而不是一次又一次地在循环中加载。此外,您应该缓存使用
font.render
创建的所有曲面,因为字体渲染也是一项非常昂贵的操作,可能是一个主要的性能瓶颈