Search code examples
pythonkeypress

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


Solution

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