How to stop the music when the s key is pressed? - python

My program plays music when I press the space bar. How to stop music when the s key is pressed?
import pygame, sys
from pygame.locals import QUIT
def main():
pygame.init()
#Intalise
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Drop Shadow!')
#load sound
beep_sound = pygame.mixer.Sound('Joy.wav')
#load music
pygame.mixer.music.load('Joy.wav')
# Game Clock
game_clock = pygame.time.Clock()
#Game Loop
running = True
while running:
#Update Section
#Update delta_time
delta_time = game_clock.tick(60) / 100
#Handle events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
#play sound
pygame.mixer.Sound.play(beep_sound)
if event.key == pygame.K_p:
#play music
pygame.mixer.music.play(-1)
#Draw Section
DISPLAYSURF.fill((128, 128, 128))
pygame.display.flip()
if __name__ == "__main__":
main()

You can use the pygame.mixer.music.stop():
Stops the music playback if it is currently playing. endevent will be triggered, if set. It won't unload the music.
Conditionally call it in your event-loop when pygame.K_s is pressed, like so:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
#play sound
pygame.mixer.Sound.play(beep_sound)
if event.key == pygame.K_p:
#play music
pygame.mixer.music.play(-1)
if event.key == pygame.K_s:
#stop music
pygame.mixer.music.stop()

Related

How to move an image on pygame?

I am new to pygame. I've coded on Python before but never in pygame.
I've made a code which plays a sound when certain keys are clicked and now I tried to make in image moving every time that the user click with his mouse.
import pygame, os, sys
pygame.init()
screen = pygame.display.set_mode((1300,1300))
screen.fill((250,250,250))
img = pygame.image.load(os.path.join(sys.path[0],"fonddecran.v1.jpg"))
screen.blit(img, (0, 0))
pygame.display.flip()
barrel=pygame.image.load(os.path.join(sys.path[0],"barrel-man.jpg"))
pygame.display.flip()
pygame.mixer.init()
it = true
while it:
for event in pygame.event.get():
if event.type == pygame.QUIT:
it=False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 3:
pygame.mixer.music.load(os.path.join(sys.path[0],"Mi-mineur.mp3"))
pygame.mixer.music.play()
elif event.button == 1:
screen.blit(barrel,event.pos)
pygame.display.flip()
elif event.type == pygame.KEYUP:
if event.key == ord('b'):
pygame.mixer.music.load(os.path.join(sys.path[0],"Mi-mineur.mp3"))
pygame.mixer.music.play()
pygame.quit()
Unfortunately, the image just appears one more time every time. How can I delete it so it looks like it has moved?
To be able to "move" the image, you have to redraw the scene in each frame. Add a variable that stores the position of the image. Change the variable to the mouse position when you click the mouse:
import pygame, os, sys
pygame.init()
screen = pygame.display.set_mode((1300,1300))
img = pygame.image.load(os.path.join(sys.path[0],"fonddecran.v1.jpg"))
barrel=pygame.image.load(os.path.join(sys.path[0],"barrel-man.jpg"))
pygame.mixer.init()
barrel_pos = None
it = True
while it:
for event in pygame.event.get():
if event.type == pygame.QUIT:
it=False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 3:
pygame.mixer.music.load(os.path.join(sys.path[0],"Mi-mineur.mp3"))
pygame.mixer.music.play()
elif event.button == 1:
barrel_pos = event.pos
elif event.type == pygame.KEYUP:
if event.key == ord('b'):
pygame.mixer.music.load(os.path.join(sys.path[0],"Mi-mineur.mp3"))
pygame.mixer.music.play()
screen.fill((250,250,250))
screen.blit(img, (0, 0))
if barrel_pos:
screen.blit(barrel, barrel_pos)
pygame.display.flip()
pygame.quit()

PyGame exceptions and freezes when trying to render to window

Can someone tell me what's wrong with this Python code? I'm using Python 3.8.2.
This code is from the book Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming. The original code uses pygame.display.flip() instead of pygame.display.update(), the original code will produce this error code: pygame.error: Window surface is invalid, please call SDL_GetWindowSurface() to get a new surface
However, after I changed it to pygame.display.update(), it just freezes my PC with blank PyGame window.
import pygame
from settings import Settings
from ship import Ship
class AlienInvasion:
""" overall class to manage game assets and behavior."""
def __init__(self):
"""Initialize the game, and create game resources."""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height
pygame.display.set_caption("Alien Invasion")
self.ship = Ship(self)
def run_game(self):
"""Start the main loop for the game."""
while True:
self._check_events()
self.ship.update()
self._update_screen()
def _check_events(self):
"""respond to keyboard and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
elif event.type == pygame.K_q:
sys.exit()
def _check_keydown_events(self, event):
"""Respond to keypresses."""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
if event.key == pygame.K_LEFT:
self.ship.moving_left = True
if event.key == pygame.K_UP:
self.ship.moving_up = True
if event.key == pygame.K_DOWN:
self.ship.moving_down = True
def _check_keyup_events(self, event):
"""Respond to key releases."""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
if event.key == pygame.K_LEFT:
self.ship.moving_left = False
if event.key == pygame.K_UP:
self.ship.moving_up = False
if event.key == pygame.K_DOWN:
self.ship.moving_down = False
def _update_screen(self):
"""Update images on the screen, and flip to the new screen."""
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
pygame.display.update()
if __name__ == '__main__':
#make a game instance, and run the game.
ai = AlienInvasion()
ai.run_game()
You typed the program in incorrectly. I found the source code for the entire book at https://github.com/ehmatthes/pcc_2e and this particular example is https://github.com/ehmatthes/pcc_2e/blob/master/chapter_12/piloting_the_ship/alien_invasion.py
Your program runs the same way for me - I get a blank frozen screen too. As shown above, your program is ignoring the pygame.K_q keypress because you entered that line of code in the _check_events() function, instead of _check_keydown_events(). That's what's making it seem like your computer is frozen.
The author's source code on github (linked above) runs fine for me. I recommend you download or copy/paste that code instead of trying to type it in by hand.

How to make music play when pressing the space bar?

I want to create a really simple application that starts a song while you press the SPACE bar, but when I start the application and press the space bar, I just hear a "pop" sound, and nothing starts. No music.
Here is the code:
import pygame
from pygame.locals import *
pygame.init()
backimage = pygame.display.set_mode((395, 702), RESIZABLE)
fond = pygame.image.load("background.jpg").convert()
backimage.blit(fond, (0,0))
pygame.display.flip()
pygame.mixer.pre_init(42000,-16,1,2048)
pygame.mixer.init()
musik = pygame.mixer.Sound(b'musik.wav')
continuer = 1
while continuer == 1:
for event in pygame.event.get():
if event.type == QUIT:
continuer = 0
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_SPACE:
musik.play()
Ok, thank you so much guys ! It works perfectly now.
Here is the final code if someone has the same problem as me:
import pygame
from pygame.locals import *
pygame.init()
backimage = pygame.display.set_mode((395, 702), RESIZABLE)
fond = pygame.image.load("background.jpg").convert()
backimage.blit(fond, (0,0))
pygame.display.flip()
pygame.mixer.init()
pygame.mixer.music.load(b'musik.mp3')
pygame.event.clear()
while True:
event = pygame.event.wait()
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN and event.key == K_SPACE:
pygame.mixer.music.play()
elif event.type == KEYUP and event.key == K_SPACE:
pygame.mixer.music.stop()
I don't know why the code doesn't work, but I know it does work if you use a mp3 file. try this:
import pygame
from pygame.locals import *
pygame.init()
backimage = pygame.display.set_mode((395, 702), RESIZABLE)
fond = pygame.image.load("background.jpg").convert()
backimage.blit(fond, (0,0))
pygame.display.flip()
pygame.mixer.init()
pygame.mixer.music.load(b'musik.mp3')
continuer = 1
while continuer == 1:
for event in pygame.event.get():
if event.type == QUIT:
continuer = 0
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_SPACE:
pygame.mixer.music.play()
If you want to use your .wav file you can find .wav to .mp3 online
I think that you misunderstood the use for pygame.event. You should try with pygame.event.wait() :
pygame.event.clear()
while True:
# wait until new event happens - blocking instruction
event = pygame.event.wait()
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN and event.key = K_SPACE:
musik.play()

Pygame not restoring from pause

I'm trying to pause my game by pressing the 'p' key, but after it pauses it does not unpause when p is pressed again. Here are the relevant segments of my code, I'd like to know how to fix this and/or if there are better alternative methods of implementing a game pause.
pause = False
while True:
if not pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#game code
keys = pygame.key.get_pressed()
#if key up
elif keys[pygame.K_p]:
pause = True #appears to work correctly, screen freezes and
#prints "PAUSED" every tick.
#more game code
pygame.display.update()
fpsClock.tick(FPS)
else:
print("PAUSED")
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.type == pygame.K_p:
pause = False
pygame.display.update()
fpsClock.tick(FPS)
The code below does the trick.
I have added in if not pause: ... else: section also a handler for a keypress because without it there will be no chance to come out of the pause (the part if not pause won't never ever be run without this keypress check if once paused).
import pygame
pygame.init() # start PyGame (necessary because 'import pygame' doesn't start PyGame)
colorWhite = (255, 255, 255) # RGB color for later use in PyGame commands (valueRed=255, valueGreen=255, valueBlue=255)
colorWhite = (255, 255, 255) # RGB color for later use in PyGame commands (valueRed=255, valueGreen=255, valueBlue=255)
winDisplay = pygame.display.set_mode((1024, 768)) # set PyGame window size to 1024x768 pixel
pygame.display.set_caption("Minimal PyGame Test Script")
winDisplay.fill(colorWhite)
fpsClock = pygame.time.Clock()
FPS = 15
pause = False
pauseCounter = 0
while True:
if not pause:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_p:
pause = not pause
#game code
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#more game code
pygame.display.update()
fpsClock.tick(FPS)
else:
pauseCounter += 1
print(pauseCounter, "PAUSED")
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_p:
pause = not pause
#more game code
pygame.display.update()
fpsClock.tick(FPS)

Why does Pygame Movie Rewind Only on Event Input

I'm working on a small script in Python 2.7.9 and Pygame that would be a small display for our IT department. The idea is that there are several toggle switches that indicate our current status (in, out, etc) , some information about our program at the school, and play a short video that repeats with images of the IT staff etc. I have an older version of Pygame compiled that still allows for pygame.movie to function.
All of the parts of the script work, but when it gets to the end of the .mpg, the movie will not replay until there is an EVENT, like switching our status or moving the mouse. I have tried to define a variable with movie.get_time and call to rewind at a certain time, but the movie will not rewind (currently commented out) . Is there a way to play the movie on repeat without requiring an event, or maybe I could spoof an event after a certain length of time (note that the documentation for pygame.movie is outdated, the loops function does not work) ?
Thank you for the help!
import pygame, sys, os, time, random
from pygame.locals import *
pygame.init()
windowSurface = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
pygame.display.set_caption("DA IT Welcome Sign")
pygame.font.get_default_font()
bg = pygame.image.load('da.jpg')
in_img = pygame.image.load('in.png')
out_img = pygame.image.load('out.png')
etc_img = pygame.image.load('etc.png')
present = in_img
done = False
img = 1
clock = pygame.time.Clock()
movie = pygame.movie.Movie('wallace.mpg')
movie_screen = pygame.Surface(movie.get_size()).convert()
playing = movie.get_busy()
movie.set_display(movie_screen)
length = movie.get_length()
currenttime = movie.get_time()
movie.play()
while not done:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
if event.type == pygame.QUIT:
movie.stop()
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_1:
img = 1
if event.type == pygame.KEYDOWN and event.key == pygame.K_2:
img = 2
if event.type == pygame.KEYDOWN and event.key == pygame.K_3:
img = 3
if event.type == pygame.KEYDOWN and event.key == K_w:
pygame.display.set_mode((800, 600))
if event.type == pygame.KEYDOWN and event.key == K_f:
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
if img == 1:
present = in_img
if img == 2:
present = out_img
if img == 3:
present = etc_img
if not(movie.get_busy()):
movie.rewind()
movie.play()
#movie.get_time()
#if currenttime == 25.0:
# movie.stop()
# movie.rewind()
# movie.play()
windowSurface.blit(bg, (0, 0))
windowSurface.blit(movie_screen,(550,175))
windowSurface.blit(present, (0,0))
pygame.display.flip()
You need to take the code for replaying the movie out of the for loop that gets current events. Do this for that code and any other code you want to happen continuously without waiting for an event by moving the code 4 spaces to the left.
Like so:
while not done:
for event in pygame.event.get(): #gets most recent event, only executes code below when there is an event
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
if event.type == pygame.QUIT:
movie.stop()
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_1:
img = 1
if event.type == pygame.KEYDOWN and event.key == pygame.K_2:
img = 2
if event.type == pygame.KEYDOWN and event.key == pygame.K_3:
img = 3
if event.type == pygame.KEYDOWN and event.key == K_w:
pygame.display.set_mode((800, 600))
if event.type == pygame.KEYDOWN and event.key == K_f:
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
#code below is out of the event for loop and thus executes whenever the while loop runs through
if img == 1:
present = in_img
if img == 2:
present = out_img
if img == 3:
present = etc_img
if not(movie.get_busy()):
movie.rewind()
movie.play()
#movie.get_time()
#if currenttime == 25.0:
# movie.stop()
# movie.rewind()
# movie.play()
windowSurface.blit(bg, (0, 0))
windowSurface.blit(movie_screen,(550,175))
windowSurface.blit(present, (0,0))
pygame.display.flip()
I have run into this problem too while trying to do things with pygame, it seems to be a common error.

Categories