Sound first - I currently have background music playing but I'd like to stop it and play a victory or defeat song when the user wins or loses. At the moment I am unable to get the background music to stop. I'm assuming I put the command to stop the music and play the other file in the condition. Am I correct in this?
I have tried things such as bgm_music = True while bgm_music == true: code and during the condition bgm_music = False but this stops my program from working.
EDIT - Okay, for the music just loading a new song works perfectly so I think I'm all-right with the sound section.
As for the picture. I'd like to do the same as the music essentially. I want to display a victory or defeat image on top of everything once the user wins or fails. Again, I have tried a similar boolean thing as above but to no avail.
EDIT 2 - I have managed to display the picture but I need to know how to get it on top (Currently the sprites are on top of it)
It think you should keep track of different states, example:
1: Gameplay
2: Song
3: Game Over screen
Then execute code according to the state in your main loop:
if state == 1:
# gameplay code
# if over start music and change to state 2
elif state == 2:
# song playing
# decrese song_counter
if song_counter == 0:
# stop music
# change to state 3
elif state == 3:
# blit game over image
# decrease game_over_counter
if game_over_counter == 0:
# reset game
# change to state 1
Related
I have created a Chess AI game but have become stuck on a specific problem. If I am playing against an AI and I want to undo my previous move, I am unable to do so and the AI just keeps picking another move. Here is my code:
if e.key == p.K_z:
GS.UndoMove() #Undo the last move
MoveMade = True
Animate = False #Don't animate the pieces returning to their previous positions
GameOver = False #No player has won yet
if AIThinking:
MoveFinderProcess.terminate() #Stops the AI about thinking about potential moves as we don't know what move will be played next
AIThinking = False
MoveUndone = True
Any help would be greatly appreciated. :)
I tried changing some of the boolean variables, thinking that would fix it bt that didn't work.
I have tried to repeat a song(mp3) using pygame module. The code is as follows from the site https://www.studytonight.com/tkinter/music-player-application-using-tkinter
When calling this function, it comes out only one time, of course it's natural.
def playsong(self):
# Displaying Selected Song title
self.track.set(self.playlist.get(ACTIVE))
# Displaying Status
self.status.set("-Playing")
# Loading Selected Song
pygame.mixer.music.load(self.playlist.get(ACTIVE))
# Playing Selected Song
pygame.mixer.music.play()
To repeat this sound file I added loop like this, but it plays just one time.
How can I repeat many times over and over this? Should I call the function playsound(self) many times I want to repeat?
def playsong(self):
for i in range(3):
# Displaying Selected Song title
self.track.set(self.playlist.get(ACTIVE))
# Displaying Status
self.status.set("-Playing")
# Loading Selected Song
pygame.mixer.music.load(self.playlist.get(ACTIVE))
# Playing Selected Song
pygame.mixer.music.play()
The first optional argument (loops) to pygame.mixer.music.play() tells the function how often to repeate the music.
For instance pass 1 to play the music twice (repeat once):
pygame.mixer.music.play(1)
Pass -1 to play the music infinitely:
pygame.mixer.music.play(-1)
See pygame.mixer.music.play():
play(loops=0, start=0.0, fade_ms = 0) -> None
This will play the loaded music stream. If the music is already playing it will be restarted.
loops is an optional integer argument, which is 0 by default, it tells how many times to repeat the music. The music repeats indefinately if this argument is set to -1.
I'm creating a car game, everything works completely fine except I can't get the sound effect to work properly. I'd like it to play when the car is moving, and fade when it stops, I have a short clip of an engine noise. When I run the code, the noise is very staggered and jittery. What I'm after is for the clip to play over itself and then the first to stop. This would cause a noise that stops when the button isn't pressed. Here's what I tried:
carSound = pygame.mixer.Sound('car.mp3')
effect = 0
while True:
keys = pygame.key.get_pressed()
if keys[K_w] or keys[K_UP]:
effect += 1
carSound.play()
if effect >= 10:
carSound.stop()
effect = 0
I'm not at all used to doing this and don't know how to proceed. So how would I get the sound effect to play properly?
In that case, using events would be more suitable. When the key is being pressed (keyDown-event), just start the sound playing infinitely with carSound.play(-1) and then stop it on key release (keyUp-event) with carSound.stop().
I am programming an experiment with Pygame 1.9.2 on Python 2.7. In the experiment, I display an image and ask the user to click either the left mouse button or right mouse button based on a feature of the image (I instruct them in advance when to click what). The image is displayed until the user clicks or if the time of image display exceeds a fixed duration.
Here's the code snippet.(Hope this bit is enough to understand what is being done.)
pygame.display.update()
resp = None
while 1:
dispEnd = time.time()
pygame.mouse.set_visible(True)
pygame.event.get()
ms = pygame.mouse.get_pressed()
if ms[0] or ms[2]:
rt = dispEnd - dispSt
if ms[0]:
resp = 'Yes'
else:
resp = 'No'
break
if dispEnd - dispSt >= changeDuration:
break
This piece of code is part of a bigger loop where an image is selected and displayed, so this runs several times.
What happens at unpredictable times is that the program does not wait for user input. Right after displaying the image, it enters the while loop and proceeds as if the mouse were pressed.
It's a random error and happens anytime; sometimes right at the start of the program, from the very first run of the loop; so probably it is not because of the event queue possibly not being cleared (which it is while calling pygame.event.get()) and it also cannot be defaulting to the previous mouse click; sometimes it happens after a few iterations of the loop. Either way, it is disastrous for an experiment.
Try this out:
...
while 1:
dispEnd = time.time()
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
#do something
...
In pygame is there a way to tell if a sound has finished playing? I read the set_endevent and get_endevent documentation but I can't make sense of it or find an example.
I'm trying to specifically do the following:
play a sound
While the sound is playing keep iterating on a loop
When the sound has finished playing, move on.
I did check the other questions that were asked - didnt find anything specifically targeting python / pygame.
Thanks!
The trick is that you get an object of type pygame.mixer.Channel when you call the play() method of a sound (pygame.mixer.Sound). You can test if the sound is finished playing using the channel's get_busy() method.
A simple example:
import pygame.mixer, pygame.time
mixer = pygame.mixer
mixer.init()
tada = mixer.Sound('tada.wav')
channel = tada.play()
while channel.get_busy():
pygame.time.wait(100) # ms
print "Playing..."
print "Finished."
The examples assumes you have a sound file called 'tada.wav'.
You can use some code like this:
import pygame
pygame.mixer.music.load('your_sound_file.mid')
pygame.mixer.music.play(-1, 0.0)
while pygame.mixer.music.get_busy() == True:
continue
And, it doesn't have to be a .mid file. It can be any file type pygame understands.
To use set_endevent you have to do something like this:
# You can have several User Events, so make a separate Id for each one
END_MUSIC_EVENT = pygame.USEREVENT + 0 # ID for music Event
pygame.mixer.music.set_endevent(END_MUSIC_EVENT)
running = True
# Main loop
while running:
events = pygame.event.get()
if events:
for event in events:
...
if event.type == END_MUSIC_EVENT and event.code == 0:
print "Music ended"
...
pygame.mixer.pre_init(44100, 16, 2, 4096) # setup mixer to avoid sound lag
pygame.init()
startmusic="resources\snd\SGOpeningtheme.ogg"
pygame.mixer.set_num_channels(64) # set a large number of channels so all the game sounds will play WITHOUT stopping another
pygame.mixer.music.load(startmusic)
pygame.mixer.music.set_volume(0.3)
pygame.mixer.music.play(-1) # the music will loop endlessly
once the above code is executed the music will continue to play until you stop it or fade out as per the pygame site info.
You can loop to your heart content and the music will continue. If you need the music to play twice, instead of -1 put 1. Then the music will PLAY once and REPEAT ONCE.
You can check if the stream is playing by doing pygame.mixer.music.get_busy().
If it returns True it is. False means it has finished.