Python Forum
[PyGame] Pygame, how to run an if statement only once, help! - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Game Development (https://python-forum.io/forum-11.html)
+--- Thread: [PyGame] Pygame, how to run an if statement only once, help! (/thread-24045.html)



Pygame, how to run an if statement only once, help! - Kris1996 - Jan-28-2020

Hey guys.

I have been struggling with this problem for some time now, so i have to ask for help.
I got this game i am developing. You play as a spaceship, where your mission is to kill aliens, you get 1 point/score at each alien kill. I want to make a sound when you got a score of 10 only once. I got the score function working good and it is counting + 1 every time you kill an alien, but when the sound starts at 10 points it is playing that sound continually if i still got the score of 10. When i get 11 points it stops. I have tried with the pygame.mixer.stop after the yeah.play(), but then it isn't playing at all. Any suggestions?

My code look like this:

if score_value == 10:
yeah = pygame.mixer.Sound("PointsSound.wav")
yeah.set_volume(0.1)
yeah.play()


RE: Pygame, how to run an if statement only once, help! - michael1789 - Jan-28-2020

said_yeah = False
if score_value == 10 and said_yeah == False:
   yeah = pygame.mixer.Sound("PointsSound.wav")
   yeah.set_volume(0.1)
   yeah.play()
   said_yeah = True



RE: Pygame, how to run an if statement only once, help! - Kris1996 - Jan-28-2020

Thank you for the reply Michael. I have tried with this too, it is still the same :/


RE: Pygame, how to run an if statement only once, help! - michael1789 - Jan-28-2020

said_yeah = False  #<------- put before game loop starts.

if score_value == 10 and said_yeah == False:
   yeah = pygame.mixer.Sound("PointsSound.wav")
   yeah.set_volume(0.1)
   yeah.play()
   said_yeah = True
Ok, sorry. The said_yeah = False needs to be before the game loop starts or it will keep resetting to False on each frame. Should have stated that.


RE: Pygame, how to run an if statement only once, help! - metulburr - Jan-28-2020

we need to see more of your code to fix it


RE: Pygame, how to run an if statement only once, help! - Kris1996 - Jan-29-2020

ahh ofc, it has to be out of the game loop, stupid me! :P
It works now.

Thank you Michael! :D