↖ Back to index

Keyboard without events

There are actually two different ways of checking if the player is pressing keys. One is with events, as we have seen. We'll see the second one next.

The function pygame.key.get_pressed() will get us a list of all keys that are pressed at the time. We use it like this:

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
  print("The LEFT arrow is pressed")

This is how the above works:

  1. We get the list of the keys that are pressed right now. We put it in the variable keys.
  2. We look into this list using square brakets. With keys[pygame.K_LEFT] we check if the left arrow was pressed.
  3. If this is true (if the left arrow was pressed), we print a message.

This example uses pygame.K_LEFT same as we were using it earlier with events. The same will work for any other key.

Challenges

Should we use keyboard events or not?

As you can see, there are two ways of reading the keyboard. Which one is better? The answer is "it depends". You will use one or the other depending on the situation.