I'm making a game with pygame and I want to add a hotkey to close the game. Right now I am using:
keys_pressed = pygame.key.get_pressed()
# Hotkey for exiting game. CTRL + SHIFT + Q
if keys_pressed[pygame.K_LCTRL] and keys_pressed[pygame.K_LSHIFT] and keys_pressed[pygame.K_q]:
pygame.quit()
sys.exit()
This works in closing the game but if I press other keys with it (Ex/ CTRL + SHIFT + L + Q), it also closes the game. Is there a way I can fix this and have it only work if my desired keys are pressed and nothing else.
If you're handling KEYDOWN or KEYUP events, the event object has a bit field attribute called mod that will tell you which other modifier keys are pressed.
Here's a minimal example:
import pygame
screen = pygame.display.set_mode((480, 320))
pygame.init()
run = True
clock = pygame.time.Clock()
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
print(f"Key {pygame.key.name(event.key)} pressed")
if event.key == pygame.K_q:
if event.mod & pygame.KMOD_CTRL and event.mod & pygame.KMOD_SHIFT:
print("Hotkey Exit!")
run = False
elif event.type == pygame.KEYUP:
print(f"Key {pygame.key.name(event.key)} released")
screen.fill(pygame.Color("grey"))
pygame.display.update()
clock.tick(60) # limit to 60 FPS
pygame.quit()
When running the code and then pressing Ctrl+Shift+Q you'll see the following on the console:
$ python3.9 -i pyg_simple_hotkey.py
pygame 2.1.2 (SDL 2.0.18, Python 3.9.13)
Hello from the pygame community. https://www.pygame.org/contribute.html
Key left ctrl pressed
Key left shift pressed
Key q pressed
Hotkey Exit!
>>>
Just count the total number of keys pressed and include that as a condition in your if statement:
import pygame
import sys
import time
pygame.init()
display = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
while True:
clock.tick(100)
pygame.event.pump()
keys_pressed = pygame.key.get_pressed()
num_keys_pressed = len([x for x in keys_pressed if x])
if (
num_keys_pressed == 3
and keys_pressed[pygame.K_LCTRL]
and keys_pressed[pygame.K_LSHIFT]
and keys_pressed[pygame.K_q]
):
break
pygame.quit()
Related
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.
I want to make a FPS game in Pygame in windowed mode.
I need to be able to move my camera around for 360 degrees and more without limitation and with the hidden cursor.
I used Pygame's set_visible and set_pos but it doesn't prevent my mouse going out of the window and blocking on the screen borders.
import pygame
pygame.init()
game_display = pygame.display.set_mode((800,600))
pygame.mouse.set_visible(False)
exit = False
while (not exit):
pygame.mouse.set_pos = (400, 300)
mouse_move = (0,0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
if event.type == pygame.MOUSEMOTION:
mouse_move = event.rel
if mouse_move != (0,0):
print(mouse_move)
pygame.quit()
You have to call pygame.event.set_grab(True) as well.
Better allow the users to exit with the Esc or another key, because they won't be able to click the x button anymore to close the window.
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
exit = True
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)
I am trying to create a nice and simple game just for practice with pygame, and I was trying to change a value using mouse click and I can't find out what to do
global item
ev = pygame.event.get()
item = 0
while True:
for event in ev:
if event.type == QUIT:
pygame.quit()
sys.exit()
for event in ev:
if event.type == pygame.MOUSEBUTTONDOWN:
item + 1
print (item)
After this is run, and I click the mouse, the game just freezes and nothing appears in the shell.
Please help
Thanks
Welcome to stackoverflow.
A simple script where clicking in the window increments item by 1 and prints it:
import pygame
pygame.init()
screen = pygame.display.set_mode((400,400))
clock = pygame.time.Clock()
item = 0
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
item += 1
print item
clock.tick(30)
pygame.quit()
This example shows the basic layout and flow of a pygame program.
Notice the for event in pygame.event.get() loop contains both of the loops in your example.
Hope this helps
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()