Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Pygame and holding multiple keys

Tags:

python

pygame

I'm writing a code in pygame where the user is able to hold down multiple keys at once, however I'm experiencing some strange behaviour with the following line of code:

print(pygame.key.get_pressed()[273:277])

The purpose of this line is to detect which arrow keys are currently being held down (it's using that range because the elements of pygame.key.get_pressed() from positions [273:277] correspond to the 4 arrow keys).

When I press any of the 4 arrow keys individually, it prints correctly, but I find that if I hold down more then 2 arrow keys at once, some keys stop appearing. For example, holding Up, Right, then pressing Left doesn't seem to do anything

At first, I thought it was just that maybe my keyboard was unable to detect more then 2 key presses at a time, but I don't think that's what's happening, as I noted that if I was holding down Up and Down, then pressed Left, it wouldn't register that I was holding Left. However, if I was holding down Up and Down, then pressed Right, it would register the third button press.

Any help is appreciated, thanks!

like image 420
Bryan T. Avatar asked Oct 17 '25 07:10

Bryan T.


2 Answers

Actually, it is your keyboard at work.

Well known to game designers, there are combinations of key presses that will work and some will not. According to this link, their game has multiple bugs related to the combination of keys they used to fire the guns and move the tank. It is best to use more recognizable keys if you can or just find the combinations of keys that will work, in this case, it would be 4 times 4 times 4 times 4 at least 256 combinations you can go through... I recommend creating a program for this.

like image 63
Anthony Pham Avatar answered Oct 18 '25 21:10

Anthony Pham


Try using keyup/keydown event and storing the state variables instead.

if event.type == KEYUP:
    if event.key == (insert key id here):
        uparrow_pressed = False
elif event.type == KEYDOWN:
    if event.key == (insert key id here):
        uparrow_pressed = True
like image 33
Oisin Avatar answered Oct 18 '25 20:10

Oisin