How do I detect multiple keypresses in python all at the same time?

Question:

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

Asked By: Ebenezer Isaac

||

Answers:

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:

e.g. for multiple key press

keys = pygame.key.get_pressed()
if keys[pygame.K_w] and keys[pygame.K_a]:
    #Do something

More details in documentation.

Answered By: amsh

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)
Answered By: ircama
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.