[英]How do I detect multiple keypresses in python all at the same time?
I want to move my robot car diagonally and so to achieve that I want to detect if 'w' is pressed along with 'd' or 'a'.我想沿对角线移动我的机器人汽车,因此我想检测“w”是否与“d”或“a”一起按下。
If I want to use 'w', 'a', 's', 'd' as my keys.如果我想使用 'w', 'a', 's', 'd' 作为我的键。
what I have now is like this我现在拥有的是这样的
from curtsies import Input
with Input(keynames='curses') as input_generator:
for key in input_generator:
print(key)
if key == 'w':
#move forward
if key == 's':
#move backward
if key == 'a':
#move left
if key == 'd':
#move right
if key == ' ':
#stop
But I want my program to be something like this :但我希望我的程序是这样的:
while True:
while keypressed('w'):
#move forward
while keypressed('s'):
#move backward
while keypressed('a'):
#move left
while keypressed('d'):
#move right
while keypressed('w')&&keypressed('a'):
#move forward left diagonally
while keypressed('w')&&keypressed('d'):
#move forward right diagonally
Also i want to know when the keys are released so i can make the car stop.我也想知道钥匙什么时候松开,这样我就可以让车停下来。 In essence I want the car to work exactly how a car would function in a game like GTA or NFS.....
从本质上讲,我希望汽车能够在 GTA 或 NFS 等游戏中完全按照汽车的运行方式工作.....
What would be the easiest way to achieve this?实现这一目标的最简单方法是什么? The lighter the code, the better......
代码越轻越好......
The best approach to do it is to use pygame module.最好的方法是使用 pygame 模块。
pygame.key.get_pressed()
returns the list of all the keys pressed at one time: pygame.key.get_pressed()
返回一次按下的所有键的列表:
eg for multiple key press例如对于多个按键
if keys[pygame.K_w] and keys[pygame.K_a]:
#Do something
More details in documentation . 文档中的更多详细信息。
If a small timeout is acceptable, a possible approach is using the send method , like in the following example:如果可以接受较小的超时,则可能的方法是使用send 方法,如下例所示:
from curtsies import Input, events
with Input(keynames="curtsies", sigint_event=True) as input_generator:
while True:
key = input_generator.send(0.1)
if key:
print(key)
if key and (
key in ("q", "Q", "<ESC>", "<Ctrl-d>", "<SigInt Event>")
or isinstance(key, events.SigIntEvent)
):
print("Terminated")
break
if key and key == "<UP>":
print('move up')
print('.', end='', flush=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.