Search code examples
pythoneventspygamekey

How do I check for two keyboard keys being pressed at the same time with pygame?


I'm trying to put some features into my pygame games that get executed when two keys (e.g. a + ESC) get pressed at the same time. I tried using

for event in pygame.event.get():
  if event.type == pygame.KEYDOWN and event.key == pygame.K_a and event.key == pygame.K_ESCAPE:
    # do something

But it doesn't recognize when I hit both keys at the same time


Solution

  • Use pygame.key.get_pressed() to get the state of all keyboard buttons.

    keys = pygame.key.get_pressed()
    if keys[pygame.K_a] and keys[pygame.K_ESCAPE]:
        # [...]
    

    Check the state of the keys when the KEYDOWN event occurs on one of the keys (a or ESC):

    for event in pygame.event.get():
        # [...]
    
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a or event.key == pygame.K_ESCAPE: # <--- or 
    
                keys = pygame.key.get_pressed()
                if keys[pygame.K_a] and keys[pygame.K_ESCAPE]:
                    print("a and ESC")
    

    The same combined in a single condition:

    event_list = pygame.event.get()
    keys = pygame.key.get_pressed()
    for event in event_list:
        # [...]        
    
        if event.type == pygame.KEYDOWN and \
            ((event.key == pygame.K_a and keys[pygame.K_ESCAPE]) or \
            (event.key == pygame.K_ESCAPE and keys[pygame.K_a])):
            
            print("a and ESC")
    

    Note: pygame.event.get() must be called before pygame.key.get_pressed(), since the states of the keys returned by pygame.event.get() are set when the events are evaluated.