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.
CodePudding user response:
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!
>>>
CodePudding user response:
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()