2014-04-29 51 views
1

我有一小段代码,如果一个if语句满足正在播放一次,它由一个声音:制作Pygame的播放声音ONCE

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

我想它一遍又一遍地播放,因为if子句的条件保持True;并可能是True多个block对象block_list

您应该以对您的应用程序有意义的方式解决该问题。

很难给出一个很好的建议,当你不知道的大局观,但也许一个简单的标志将帮助您:

# 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 

PS:在考虑加载您Font只有一次开始你的应用程序,而不是一遍又一遍地循环。此外,您应该缓存由font.render创建的所有表面,因为字体渲染也是一项非常昂贵的操作,并且可能是主要的性能瓶颈。