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
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.
pygame.key.get_pressed. — get the state of all keyboard buttons.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With