Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i press two keys simultaneously for a single event using Pygame?

Tags:

python

pygame

I am making a game using Pygame and Python.I wish to move a block by pressing two keys simultaneously.How can i do that? I am able to move the block using a single key.. but it doesn't work for two keys together.

I want the block to move wen i press "right key" and "1" together

The given code works efficiently move using a single key

 if event.type==KEYDOWN:
        if event.key==K_RIGHT:
            move_fullcube=left

I tried using "and" but it still doesn't work

 if event.type==KEYDOWN:
            if event.key==K_RIGHT and event.key==K_1:
                move_fullcube=left
like image 315
shinite Avatar asked May 09 '16 17:05

shinite


People also ask

What pygame key event is use to ask if the keyboard is pressed?

Detecting if a key is pressed: KEYDOWN and pygame. KEYUP events respectively. For example, if we want to detect if a key was pressed, we will track if any event of pygame.

What is pygame key Get_pressed ()?

pygame.key.get_pressed. — get the state of all keyboard buttons.

How do you get pressed keys in pygame?

Use pygame. First, we get an array with all the pressed keys at this frame with the pygame. key. get_pressed method, and then we will see whether the key was pressed. We get this value with one of the key constants in Pygame.


2 Answers

The easiest way is to use pygame.key.get_pressed(). This function returns a list of keys which are currently down. The following example shows how to check if two keys are being pressed at the same time:

keys = pygame.key.get_pressed()

if keys[pygame.K_RIGHT] and keys[pygame.K_LEFT]:
    move_fullcube = left

See the documentation at https://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed.

like image 122
wyattis Avatar answered Oct 19 '22 03:10

wyattis


There are two different ways to do keyboard event handling in pygame. The first way is what you are doing, where you get a list of every event and loop through that list. The problem with your approach is that you can only look at a single event at a time, so event.key will never equal K_RIGHT and K_1 at the same time because it's only a single key. Both events will happen, but you can only look at one of them at a time. If you want to do it this way, you must setup two variables right_pressed and one_pressed. Something like this

right_pressed = False
one_pressed = False
for event in pygame.event.get():
    if event.type==KEYDOWN:
        if event.key==K_RIGHT:
            right_pressed = True
        if event.key==K_1:
            one_pressed = True

Then outside of your loop check if they are both true.

The other, easier way to do it is to use pygame.keys.get_pressed(), which is much more convenient for checking if an individual key is down at the moment.

like image 35
DJMcMayhem Avatar answered Oct 19 '22 01:10

DJMcMayhem