0

I'm making a game with pygame and I encountered a problem with the following code :

while not self.end: # main game loop
        keys = pygame.key.get_pressed()
        if keys[K_LEFT]:
            adddirection(LEFT)
        elif keys[K_RIGHT]:
            adddirection(RIGHT)
        elif keys[K_UP]:
            adddirection(UP)
        elif keys[K_DOWN]:
            adddirection(DOWN)

When I hold TOP arrow or DOWN arrow, if I press any right or left key, nothing will happen, the elif does not resolves. Why ? Should I do this another way ?

If I replace all the 'elif' by 'if' the opposite happens. If I hold left or right, top and down will never resolves.

I would like to understand that weird mechanic.

Waroulolz
  • 297
  • 9
  • 23

3 Answers3

0

The code would be like

for event in pygame.event.get():
    if event.type==QUIT:
        pygame.quit()
        sys.exit()

    if event.type == KEYDOWN:
        if (event.key == K_LEFT):
            //
        elif (event.key == K_RIGHT):
            //
        elif (event.key == K_UP):
            //
        elif (event.key == K_DOWN):
            //

keys_pressed = key.get_pressed()

if keys_pressed[K_LEFT]:
 //

if keys_pressed[K_RIGHT]:


if keys_pressed[K_UP]:
//

if keys_pressed[K_DOWN]:


//

Replace // with your condtions

Avinash Babu
  • 6,171
  • 3
  • 21
  • 26
  • This is using both methods of detecting keyboard keys and as such is somewhat useless. One can either choose to rely on keydown events or poll the keyboard for better control (imo atleast), using both is pretty much useless and quite confusing – Tehsmeely Aug 02 '14 at 18:11
0

So, as per the nature of elif stacks, if one resolves as true, it wont test the others and simply skip, loop up how if elif else works online somewhere.

so you need to either use "if" for each, or split it in to a for loop.

However since you say when you use if for all of them, you still don't get your expected behaviour. I suspect this could be caused by "adddirection()", could you post that too if you cannot solve this issue?

As is mentioned in another answer, you can also use pygame events to deal with keypresses

Tehsmeely
  • 188
  • 6
0

The problem may be unsolvable. The way keyboards work is every key sends a signal on a copper wire through the USB cable. Mechanical (gaming) keyboards have a copper wire for each key, however to reduce the cost of cheap keyboards, many keys share a wire, and as a result only one of the keys which share a wire can be pressed at once. The arrow keys are on the same wire which may be contributing to your issue. The reason WASD is generally used for movement in games is because the 4 keys run along different wires.

TLDR: You may have better luck using WASD instead of your arrow keys

CPSuperstore
  • 633
  • 10
  • 18