我如何在Pygame中制作热键
我正在使用Pygame进行游戏,我想添加一个热键以关闭游戏。现在我正在使用:
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()
这可以关闭游戏,但是如果我按其他键(ex/ ctrl + shift + l + q),它也会关闭游戏。有什么方法可以解决此问题,并且只有按下所需的键,而仅此而已。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您要处理
keydown
或keyup
事件,事件对象具有一个bit Five属性,称为mod
,它将告诉您哪个其他修饰符键被按下。这是一个最小示例:
运行代码时,然后按 ctrl + shift + q q >在控制台上您会看到以下内容:
If you're handling
KEYDOWN
orKEYUP
events, the event object has a bit field attribute calledmod
that will tell you which other modifier keys are pressed.Here's a minimal example:
When running the code and then pressing Ctrl+Shift+Q you'll see the following on the console:
只需计算按下的键总数,并将其作为条件在您的
中包括在
语句中:Just count the total number of keys pressed and include that as a condition in your
if
statement: