PyGame Basics: Keyboard Input

PyGame Basics: Keyboard Input

October 4, 2019 10:27 pm Published by Leave your thoughts

In this guide, we will take a look at a couple ways to gather keyboard input with PyGame.

There are a few ways of grabbing keyboard input. The first way to gather keyboard input is via capturing PyGame events. To check if any arrow keys are pressed down on the current update, you can write:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            print("Pressed left")
        if event.key == pygame.K_RIGHT:
            print("Pressed right")
        if event.key == pygame.K_UP:
            print("Pressed up")
        if event.key == pygame.K_DOWN:
            print("Pressed down")

To check if any arrow key is released on the current update, we can type:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT:
            print("The left arrow key was released.")
        if event.key == pygame.K_RIGHT:
            print("The right arrow key was released.")
        if event.key == pygame.K_UP:
            print("The up arrow key was released.")
        if event.key == pygame.K_DOWN:
            print("The down arrow key was released.")

Another way to check pressed keys is to use the pygame.key.get_pressed method. In your game loop, or update function, you could type:

pressed = pygame.key.get_pressed()

if pressed[pygame.K_w]:
    playery -= speed
if pressed[pygame.K_s]:
    playery += speed
if pressed[pygame.K_a]:
    playerx -= speed
if pressed[pygame.K_d]:
    playerx += speed

Unlike the previous method, this method allows you to check whether a key is down every game update. Using the pygame.key.get_pressed method would allow you to easily check inputs and move your player (or any other game object) how you wish.

Concluding Thoughts

Now you know the different ways of collecting input with PyGame. Hopefully you found this guide useful, if you have, you may want to take a look at the rest of this series. To receive news about our latest tutorials and courses we publish, consider subscribing to our newsletter. Of course, if you found this tutorial valuable, sharing it on your favorite social media platform would be much appreciated.

Tags: , , , ,

Categorised in:

This post was written by Jared York

Leave a Reply

Your email address will not be published. Required fields are marked *