Pygame Keyboard Input Tutorial – Complete Guide

Are you ready to take your game development skills to the next level by mastering keyboard input in Pygame? Making use of keyboard inputs is a critical skill for anyone wanting to construct exciting, immersive games where the player can control characters and navigate on-screen gameplay.

What is Pygame Keyboard Input?

Pygame Keyboard Input refers to the method by which we, as developers, can capture and make use of the keys pressed on the keyboard by the user within our Pygame application. It’s the connection between the player’s commands and your game’s response to those commands.

Why Do Game Developers Need this Skill?

Learning how to handle pygame inputs is an indispensable tool in your game developer toolbox. Here’s why:

  • Player Control: With inputs, you can let the player maneuver characters and make gameplay decisions, leading to a more interactive gaming experience.
  • Game Mechanics: A lot of gaming mechanics are heavily dependent on keyboard inputs—think of movements, selections, or triggers. An understanding of Pygame keyboard inputs allows you to design these mechanics with creativity and precision.
  • Versatility: Keyboard inputs in Pygame are not just limited to games. This knowledge can also come in handy for creating interactive demonstrations or simulations.

With an understanding of Pygame keyboard inputs, we are basically giving a voice to the player within our games. Let’s dive further into the coding aspects of this tutorial.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Basic Keyboard Input Detection

To start with, let’s understand how to simply detect if a key is pressed on the keyboard in Pygame.

import pygame
pygame.init()

win_height = 480
win_width = 640
win = pygame.display.set_mode((win_width, win_height))

run = True
while run:
    pygame.time.delay(100)

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

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                print('Left key pressed')
            elif event.key == pygame.K_d:
                print('Right key pressed')

pygame.quit()

In the above example, we’re checking for a KEYDOWN event (a key press) in our games event loop. If detected, we further check if the keys being pressed are “a” for left or “d” for right.

Moving A Game Character with Keyboard Inputs

Let’s build on the previous example and actually move a game character based on the player’s keyboard inputs. We’ll create a small player controlled square object which can move around the window.

import pygame
pygame.init()

win_height = 480
win_width = 640
win = pygame.display.set_mode((win_width, win_height))

x = 50  # initial position of the square
y = 50
width = 64
height = 64
vel = 5  # velocity

run = True
while run:
    pygame.time.delay(100)

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

    keys = pygame.key.get_pressed()

    if keys[pygame.K_a]:
        x -= vel
    if keys[pygame.K_d]:
        x += vel
    if keys[pygame.K_w]:
        y -= vel
    if keys[pygame.K_s]:
        y += vel

    win.fill((0,0,0))
    pygame.draw.rect(win, (255,0,0), (x, y, width, height))
    pygame.display.update() 

pygame.quit()

In this example, we’re making use of pygame’s ‘get_pressed()’ function to keep track of the state of all keys. We can then check if our movement keys (a, w, s, and d) are being pressed and move our rectangle accordingly.

Handling Multiple Simultaneous Key Presses

Now, what if the player wants to move diagonally? They would need to press two movement keys simultaneously. Let’s enhance our code to cater to this possibility.

import pygame
pygame.init()

win_height = 480
win_width = 640
win = pygame.display.set_mode((win_width, win_height))

x = 50  
y = 50
width = 64
height = 64
vel = 5  

run = True
while run:
    pygame.time.delay(100)

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

    keys = pygame.key.get_pressed()

    if keys[pygame.K_a] and x > vel:
        x -= vel
    if keys[pygame.K_d] and x  vel:
        y -= vel
    if keys[pygame.K_s] and y < win_height - height - vel:
        y += vel

    win.fill((0,0,0))
    pygame.draw.rect(win, (255,0,0), (x, y, width, height))
    pygame.display.update() 

pygame.quit()

We merely added additional checks to our movement keys. Meaning, even if two directional buttons are pressed, our character will be able to move seamlessly. We also added boundaries to ensure that our character doesn’t move outside the window.

Creating a Player Class

Let’s now enhance our code cleanliness by creating a player class that will encapsulate all player related attributes and actions.

class Player(object):
    def __init__(self, x, y, width, height, vel):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = vel

    def draw(self, win):
        pygame.draw.rect(win, (255,0,0), (self.x, self.y, self.width, self.height))

player = Player(50, 50, 64, 64, 5)

We’ve now separated our player logic into a dedicated class, helping us to write more organized and maintainable code. From here on, we can easily add more properties, behaviors, and even additional character types!

Adding Player Actions

Let’s continue to enhance our player, adding ‘jump’ action. We will allow our player to jump using the ‘SPACE’ key.

class Player(object):
    def __init__(self, x, y, width, height, vel):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = vel
        self.isJump = False
        self.jumpCount = 10
    
    def jump(self):
        if self.isJump: 
            if self.jumpCount >= -10:  
                neg = 1  
                if self.jumpCount < 0:
                    neg = -1
                self.y -= (self.jumpCount ** 2) * 0.5 * neg
                self.jumpCount -= 1
            else:
                self.isJump = False
                self.jumpCount = 10

player = Player(50, 50, 64, 64, 5)

The jump function uses a parabolic equation to simulate a natural ‘arc’ like jump and fall. Now, we should add this logic to our game loop.

    keys = pygame.key.get_pressed()

    if keys[pygame.K_SPACE]:
        player.jump()

Adding Player States

In real-life scenario, our player can perform different actions resulting in different states. Let’s incorporate this into the player class.

class Player(object):
    def __init__(self, x, y, width, height, vel):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = vel
        self.isJump = False
        self.jumpCount = 10
        self.left = False
        self.right = False
        self.standing = False

# Don't forget to modify the state in your game loop

    keys = pygame.key.get_pressed()

    if keys[pygame.K_a]:  
        player.x -= player.vel  
        player.left = True
        player.right = False
        ... # rest of the code

Now our code has got richer, we can act upon the player’s state to display different sprite animations, sounds, or any other feature in your game.

Practicing these concepts will give you an excellent sense of how you can create interactive games with Pygame. All of these concepts are just scratching the surface, and there’s so much potential to create an immersive gaming experience. So, what are you waiting for? Start creating!

Beyond Basic Movements

Leveraging keyboard input in Pygame allows us to create far more interactive and exciting game mechanics. Let’s explore some advanced uses.

New states like crouching or sprinting can significantly improve the gaming experience. For example, we can have the player character crouch when the “SHIFT” key is pressed.

class Player(object):
    def __init__(self, x, y, width, height, vel):
        # previous code...
        self.isCrouch = False

    def crouch(self):
        if self.isCrouch:
            self.height = self.height // 2

player = Player(50, 50, 64, 64, 5)

# In game loop
if keys[pygame.K_LSHIFT]:
    player.isCrouch = True
else:
    player.isCrouch = False

player.crouch()

Here, the player’s height is reduced by half when the “SHIFT” key is pressed, simulating a crouch action.

We could also increase the player movement speed when the “SHIFT” key is pressed, giving the player a sprint ability.

# In game loop
if keys[pygame.K_LSHIFT]:
    player.vel = 10
else:
    player.vel = 5

These techniques are merely the beginning. As a developer, you have unlimited creativity to bring your games to life with Pygame!

Adding Game Actions

Aside from player movement, we can use Pygame keyboard inputs for other game actions such as firing a weapon or using an ability.

class Player(object):
    def __init__(self, x, y, width, height, vel):
        # previous code...
        self.shootDelay = 0

    def shoot(self):
        if self.shootDelay == 0:
            # add code here to spawn a bullet object
            self.shootDelay = 50

# In game loop
if keys[pygame.K_SPACE] and player.shootDelay == 0:
    player.shoot()

# reduce shootDelay every frame
if player.shootDelay > 0:
    player.shootDelay -= 1

In the above example, when the player hits the “SPACE” key, they fire a bullet (if they haven’t shot recently). This adds a delay between each shot, effectively creating a firing rate.

Adding Game Interactions

Sometimes we want our player to interact with the game world. We can add interactions like picking up items or opening doors with the “E” key:

# In game loop
if keys[pygame.K_e]:
    # Check for and handle interactions in the game world
    handleInteractions(player)

The ‘handleInteractions(player)’ function could check if the player is near an interactive object and perform the appropriate action.

Remember, the Pygame library gives you the tools to create incredible games, but you provide the creativity. Take these concepts and run with them, push the boundaries and see what you can create!

The Road Ahead

If you’ve found our dive into the world of Pygame and Keyboard Input engaging, we have great news! Your journey has just started, and there is so much more to learn and apply in your game development pursuits. Mastery of Python programming and game development waits just around the corner.

Why not further your Python programming skills with a comprehensive learning path? Check out our Python Mini-Degree for an elaborate guide into the world of Python. It covers everything from the basics to building your games, apps, and even AI chatbots! It’s tailored to both beginners and experienced programmers, letting you proceed at your own pace.

In case you are interested in a particular area or topic, we also have a broad collection of Python courses available here. With over 250 supported courses, be ready to skyrocket your skills in programming, game development, and AI.

At Zenva, we believe in equipping you with the necessary skills to bring your game ideas to life. Remember, your journey with Python and game development is yours to shape; let’s navigate this exciting path together!

Conclusion

We hope this walkthrough on handling keyboard inputs in Pygame has added another dimension to your game development skills. Making a game is not just about implementing logic and creating beautiful animations; it is about creating an immersive world where the player’s decisions matter. By learning to handle Pygame keyboard input, you have taken a significant step forward in the world of game creation.

The best way to solidify these skills is through continuous practice and real-world application. Why not kickstart or continue that journey with our Python Mini-Degree? At Zenva, we look forward to being an active contributor to your learning journey in the captivating world of Python and game development. Let’s develop the future together!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.