Question

I have a small snippet of code which consists of a sound being played once if an if statement is met:

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()

However upon playing the 'error' sound, it continues to loop until the pygame window is closed. Is there any way I can edit my code so that the 'error' sound effect is only played once?

Thank you.

Was it helpful?

Solution

I guess it's played over and over again because the condition of the if clause stays True; and probably it's True for multiple block objects in block_list.

You should fix that in a way that makes sense for your application.

It's hard to give a good advice when you don't know the bigger picture, but maybe a simple flag will help you:

# 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.: consider loading your Font only once at the start of your application, not over and over again in a loop. Also, you should cache all Surfaces created with font.render, since font rendering is also a very expensive operation and can be a major performance bottleneck.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top