Pygame Keyboard Input (Events)

This tutorial explains how to take keyboard input in Pygame.

Every game in the world must create an interactive experience for the one playing it. The first step in creating such an experience is taking input from the user, and use this input to effect the world in some unique way.

Common examples of this are the arrow keys used to move your character, different keys for various attacks (RPGs) or different dialogue choices which you select with a mouse etc.

In this tutorial we’ll be learning how to detect these “input events” from the keyboard in Python Pygame to enhance our gaming experiences. If you’re learn about mouse input, you can follow our mouse events tutorial.


Introduction

Due to the number of preceding steps required, taking input can seem a little tricky to those who don’t know the basics of game creation. In our many game tutorials, we’ve explained the concept of the infinite game loop. The game loop will run continuously, repeating events until the game is over. It is within this constantly looping game loop that we will check for input from the user.

Pygame keeps track of “events” that occur, which we can see with the events.get() function. There are many thing that classify as events, such as Mouse and Keyboard inputs or the quit button on the window.

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

Above is a standard event check included in every pygame program. This allows for a clean exit from the game by first shutting down the program.


Detecting Keyboard Input Events

That’s enough of an introduction. Using real life examples will help you understand the concept faster. Below is a simplified piece of code from our Pygame RPG Tutorial, where we detect key presses from the user.

There are three layers to this code. First we have the infinite game loop, followed by a loop returning occurring events, following by a condition check to see if any key is currently being pressed. Once we’ve reached this point we may add as many if statements to check for various key presses.

while True:
    # Cycles through all the events currently occuring
    for event in pygame.event.get():
          
          # Condition becomes true when keyboard is pressed   
          if event.type == pygame.KEYDOWN:

              if event.key == pygame.K_m:
                  fireball.fire()
                  music_manager.playsound(fsound, 0.3)

              if event.key == pygame.K_n:
                  handler.next_stage()

              if event.key == pygame.K_q:
                  handler.interact()

              if event.key == pygame.K_SPACE:
                  player.jump()

              if event.key == pygame.K_RETURN:
                  player.attack()

You can see that we use the “m” key to shoot out a fireball, the “space” key to jump and the “enter” (Return) key to attack.

If you want to add Key-presses handling into your code, the above format is a foolproof way of doing it. You can also use the pygame.KEYUP event, which triggers when you release the key.

Here is the full code that you can run on your system, which makes use of both KEYDOWN and KEYUP.

import pygame
from pygame.locals import *
import sys

pygame.init()
display = pygame.display.set_mode((300, 300))

while 1:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                print("Key A has been pressed")
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_a:
                print("Key A has been released")

Detecting Pressed Keys

The above method is only for single button clicks. It doesn’t matter whether you just click it once, or hold it down for several seconds. It will have the same effect. The Method will discuss here, is for “pressed” key input.

We use the get_pressed() function to return a list of the states of all keys. If the key is not pressed, it’s value is 0, otherwise it’s 1. The if statement in the below code activates only if the state of the key is 1 (pressed).

while 1:
    pressed_keys = pygame.key.get_pressed()

    if pressed_keys[K_a]:
        print("Key A has been pressed")

You will find this method more suitable for Player movement in many games. The difference is that as long as you have Key “A” pressed, the above print statement will continue to print as it is detecting continuous input. The previous method would activate it just once.

Detecting Multi Key Input

Another great feature here is that it can detect two key presses at the same time. Something that you can’t do with the first method.

    pressed_keys = pygame.key.get_pressed()

    if pressed_keys[K_a] and pressed_keys[K_b]:
        print("Key A and Key B has been pressed")

More about Pygame Events

Keyboard events play a massive role in enabling other cool features, such as Text Input, Player Movement and other shortcuts (opening inventory).

Another important category of events which also play a major role, are known as “user events”. These are basically custom Pygame events that we can create, which symbolize an important event for our game (such as a Player dying).


List of Commonly used Keys

In total, there are probably well over a 100 different keys that Pygame could detect. For the sake of brevity and conciseness, we’ll stick to about 50 of the commonly used ones.

Pygame Keys

K_BACKSPACE

K_TAB

K_CLEAR

K_RETURN

K_ESCAPE

K_SPACE

K_PLUS

K_MINUS

K_PERIOD

K_SLASH

K_UP

K_DOWN

K_LEFT

K_RIGHT

K_0

K_1

K_2

K_3

K_4

K_5

K_6

K_7

K_8

K_9

K_a

K_b

K_c

K_y

K_z

K_DELETE

K_KP0

K_KP1

K_KP2

K_KP3

K_KP4

K_KP5

K_KP6

K_KP7

K_KP8

K_KP9

K_F1

K_F2

K_F3

K_F14

K_F15

K_RSHIFT

K_LSHIFT

K_RCLTRL

K_LCTRL

K_RALT

K_LALT

Key Description

Backspace

Tab

Clear

Return (Enter)

Escape (Esc)

Space

plus sign ( + )

minus sign ( – )

period ( . )

forward slash

Up Key

Down Key

Left Key

Right Key

0

1

2

3

4

5

6

7

8

9

a

b

c

y

z

Delete (Del)

(Keypad) 0

(Keypad) 1

(Keypad) 2

(Keypad) 3

(Keypad) 4

(Keypad) 5

(Keypad) 6

(Keypad) 7

(Keypad) 8

(Keypad) 9

F1

F2

F3

F14

F15

Right Shift key

Left Shift Key

Right Control key

Left Control ley

Right Alt Key

Left Alt key

There are other several (less common) key inputs as well, like the asterisk which you find in complete pygame “keys” documentation.


This marks the end of the Pygame Keyboard Input Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
8 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments