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:
keys
.keys[pygame.K_LEFT]
we check if the left arrow was pressed.This example uses pygame.K_LEFT
same as we were using it earlier with events. The same will work for any other key.
pygame.key.get_pressed
to program the movement of a character (an image) on the screen.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.
pygame.key.get_pressed()
. For example, for movement.