简体   繁体   中英

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'.

If I want to use 'w', 'a', 's', 'd' as my keys.

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.....

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.key.get_pressed() returns the list of all the keys pressed at one time:

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM