why doesn't my window close when I press the escape key - python

why doesn't my window close when I press the escape key:
import pygame
pygame.display.init()
pygame.display.set_mode(size=(500, 500))
pygame.display.set_caption("hi")
x = 1
while True:
if pygame.key.get_mods() & pygame.K_ESCAPE:
x = 2
if x == 2:
pygame.quit()

You need an event-loop in your while-loop like so:
import pygame
pygame.display.init()
pygame.display.set_mode(size=(500, 500))
pygame.display.set_caption("hi")
x = 1
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: # uses the small 'x' on the top right to close the window
pygame.quit()
if event.type == pygame.KEYDOWN: # processes all the Keydown events
if event.key == pygame.K_ESCAPE: # processes the Escape event (K_A would process the event that the key 'A' is hit
x = 2
if x == 2:
pygame.quit()
pygame.display.update()
I also added pygame.display.update(), which should normally be in your code.

Related

My pause statement is not working for pygame loop

My collide_rect function is not working as I expect to be. The problem is when press the key 'r', it should be able to reset everything and continue the game. But when I actually press the key 'r', it does not change anything when I add in the pause statement. I want to have the game pause when two of the sprites I have(ball, obstacle) collide. After the user inputs the letter 'r', it should go back to running and reset position for both sprites. The error I am getting is when I press the key 'r', it does not change anything on the surface.
This is my while loop:
paused = False
def display_text(text):
font = pygame.freetype.Font('helvetica.ttc', 32)
text_attributed = font.render_to(gameDisplay, (300,300), text, black)
while not crashed:
time = pygame.time.get_ticks()
obstacle.change_x()
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
ball.jump_true()
if event.key == pygame.K_SPACE:
ball.jump_true()
if event.key == pygame.K_r:
paused = not paused
if ball.collide == True:
gameDisplay.fill(white)
display_text('You Lost! type "R" to restart')
paused = True
if paused == True:
ball.reset_position()
obstacle.reset_position()
pygame.display.flip()
clock.tick(20)
else:
ball.jump()
ball.test_collision(obstacle)
gameDisplay.fill(white)
ball.update()
obstacle.update()
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
Don't overcomplicate things. You don't need multiple event loops. Use 1 main loop, 1 event loop and a state which indicates if the game is paused. e.g.:
paused = False
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r
# Toggle pause
paused = not paused
if paused:
# "pause" mode
# [...]
else
# "run" mode
# [...]
# update display etc.
# [...]

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

My game won't work when I use the controls, how do I fix it?

I can not get the controls to work, I try to press escape to open a menu I made but it will not open and I do not know if I am checking for events correctly, is there a way I am SUPPOSED to do it?
I tried using the functions for checking for different keys and I went to the spread-sheet that displays all the event names so you can map them at pygame.org but it will not open when I use the escape or also known as:
elif event.type == pygame.K_ESCAPE:
Frame.blit('Textures/GUI/loom.png', (0,0))
Heres the full code:
import pygame
#Textures/Blocks/loom_side.png
pygame.init()
Screen = "None"
DB = 0
Width = 800
Height = 600
Frame = pygame.display.set_mode((Width,Height))
pygame.display.set_caption("HypoPixel")
FPS = pygame.time.Clock()
def Raycast(TTR, RayXPos, RayYPos, RaySizeX, RaySizeY):
RaycastThis = pygame.image.load(TTR)
RaycastThis = pygame.transform.scale(RaycastThis,(RaySizeX,RaySizeY))
Frame.blit(RaycastThis, (RayXPos, RayYPos))
Loop = True
Raycast('Textures/Screens/Skybox/Earth.png',0,0,800,600)
while Loop == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
elif event.type == pygame.K_ESCAPE:
Frame.blit('Textures/GUI/loom.png', (0,0))
pygame.display.update()
FPS.tick(60)
I expected to get the loom GUI that I made. Once I tried to press escape, nothing happened.
pygame.K_ESCAPE is not event type (see pygame.event), but it is a pygame.key.
First check if a key was pressed by comparing the event type to pygame.KEYDOWN:
event.type == pygame.KEYDOWN
Then check if the event.key, which cause the event, is the pygame.K_ESCAPE key:
event.key == pygame.K_ESCAPE
Furthermore, the parameter to Surface.blit() has to be a Surface object rather than a filename.
first load the image to a Surface, by pygame.image.load(), then blit the Surface:
sprite = pygame.image.load('Textures/GUI/loom.png')
Frame.blit(sprite, (0,0))
Of course the your Raycast function can be called to do so:
Raycast('Textures/GUI/loom.png',0,0,800,600)
Your code should look somehow like this:
while Loop == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
Raycast('Textures/GUI/loom.png',0,0,800,600)

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)

pygame joystick slows down event handling

I am using a function to wait until a controller is present, but i ran into a problem. I wanted the function to stop when I press a key. Usually these events are handled just fine, but in this part it works terrible. The event seems to be added to the event queue very late or sometimes not at all. My guess is that it is because of the uninitialisation and reinitialisation of pygame.joystick. I just don't know how to solve it. I used this program to create the error:
import pygame, sys
from pygame.locals import *
pygame.init()
SCREEN = pygame.display.set_mode((500,500))
ChangeRun = False
pygame.joystick.init()
if pygame.joystick.get_count() == 0:
while pygame.joystick.get_count() == 0:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type in [KEYUP, KEYDOWN]:
if event.key == K_ESCAPE:
ChangeRun = True
if ChangeRun == True:
break
pygame.joystick.quit()
pygame.joystick.init()
pygame.quit()
sys.exit()
I wanted to use the escape key to end the program, but only after a lot of pressing it works. The same happens with the QUIT event. When printing the events I found that most of the time no event was found.
I use windows 8.1 and python 3.4 and pygame 1.9.2
I have no joystick so I can't test it but normally I would do this similar to mouse and I wouldn't wait for controller:
import pygame
from pygame.locals import *
pygame.init()
pygame.joystick.init()
screen = pygame.display.set_mode((500,500))
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == JOYBUTTONDOWN:
print 'joy:', event.joy, 'button:', event.button
# the end
pygame.joystick.quit()
pygame.quit()

Categories