yoav
yoav

Reputation: 322

Python PyGame press two buttons at the same time

import pygame

finish = False
while not finish:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            finish = True
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP:
            print "A"
        if event.key == pygame.K_RIGHT:
            print "B"
        if event.key == pygame.K_LEFT:
            print "C"
    

Why doesn't this let me press 2 buttons at the same time and how do I make a code that does that?

Upvotes: 0

Views: 1632

Answers (2)

alexisdevarennes
alexisdevarennes

Reputation: 5632

Try this:

import pygame

finish = False
while not finish:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            finish = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                print "A"
            if event.key == pygame.K_RIGHT:
                print "B"
            if event.key == pygame.K_LEFT:
                print "C"

In your version you're iterating over pygame.event.get() and you evaluate only the last event in the for loop (apart from the quit logic), meaning you only evaluate the last keypress. Move the code into the loop and you can evaluate all the events.

If you want to detect multiple keypresses then use pygame.key.get_pressed()

finish = False
while not finish:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            finish = True

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        print("C")    
    if keys[pygame.K_RIGHT]:
        print("B")
    if keys[pygame.K_UP]:
        print("A")

Upvotes: 2

Rabbid76
Rabbid76

Reputation: 210889

The keyboard events (e.g. pygame.KEYDOWN) occure only once when a button is pressed.
Use pygame.key.get_pressed() to continuously evaluate the states of the buttons. e.g.:

finish = False
while not finish:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            finish = True

    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        print "A"
    if keys[pygame.K_RIGHT]:
        print "B"
    if keys[pygame.K_LEFT]:
        print "C"

Or if you would rather get a list:

finish = False
while not finish:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            finish = True

    keys = pygame.key.get_pressed()
    if any(keys):
        kmap = {pygame.K_UP : "A", pygame.K_RIGHT : "B", pygame.K_LEFT : "C"}
        sl = [kmap[key] for key in kmap if keys[key]]
        print sl

Upvotes: 2

Related Questions