首页 文章

让 Pygame 播放声音 ONCE

提问于
浏览
1

我有一小段代码,如果满足 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()

但是,在播放“错误”声音时,它会继续循环,直到 pygame 窗口关闭。有什么方法可以编辑我的代码,以便'错误'声音效果只播放一次?

谢谢。

1 回答

  • 1

    我想它一遍又一遍地播放,因为if子句的条件保持True;并且中的多个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
    

    P.S:考虑在应用程序启动时仅加载Font一次,而不是在循环中反复加载。此外,您应该缓存使用font.render创建的所有 Surfaces,因为字体渲染也是一项非常昂贵的操作,并且可能是主要的性能瓶颈。

相关问题