使Pygame只播放一次声音
我有一段小代码,它的功能是在满足某个条件时播放一次声音:
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 个回答
2
我想这个代码会一直重复执行,是因为if
条件一直是True
;而且可能在block_list
里有多个block
对象也满足这个条件。
你需要根据你的应用需求来修复这个问题。
在不了解整体情况的情况下,很难给出好的建议,但也许一个简单的标志位会对你有帮助:
# 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
附注:建议你在应用程序开始时只加载一次Font
,而不是在循环中反复加载。此外,你应该缓存所有用font.render
创建的表面,因为字体渲染是一个非常耗费资源的操作,可能会成为性能瓶颈。