Pygame Keys Tutorial – Complete Guide

Welcome to this comprehensive tutorial on pygame keys – the fundamental building blocks in the creation of interactive games in Python. If you’ve ever wondered how to control game characters or objects using keys, then this tutorial is for you. With Python’s pygame module, you can effectively determine key presses and transforms them into desired actions for your game.

What are Pygame Keys?

Pygame keys refer to the keyboard input functionality offered by the Pygame library. Pygame is a popular set of Python modules, mainly for developing video games. It provides a host of built-in features, one of which is handling keyboard events.

What is Their Function?

Keys in Pygame are primarily used to track keyboard input. It’s this functionality that gives our game characters the ability to move around, jump, or perform various actions in response to a player’s commands.

Why Should I Learn It?

Being a game developer, you’d probably agree that the most engaging games are interactive and responsive. A big part of being responsive is being able to register and respond to a player’s input. So, understanding how pygame handles keyboard input not only boosts your skill set but also propels you a step closer to creating exciting and interactive games.

Let’s dive into some coding and see these keys in action.

(Note: We are writing the first part of the article, part 2-6 will be written in subsequent tasks.)

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

Getting Started with Pygame Keys

Before working with pygame keys, it’s essential to grasp some basic pygame programming. Let’s begin by starting a simple pygame program:

import pygame
pygame.init()

WIN_WIDTH, WIN_HEIGHT = 800, 600
WIN = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))

while True: # main game loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

In the above code, we’ve created a simple pygame window. The loop continually checks for events, and if the window is closed (event type being pygame.QUIT), the game loop quits.

Now, let’s introduce the use of keys.

Keyboard Input in Pygame

Keyboard inputs are considered events in Pygame. The most common key functions used in Pygame are `pygame.KEYDOWN` and `pygame.KEYUP`. These essentially represent the pressing and releasing of a key.

The following is an example of keydown event handling:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        pygame.quit()
    elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
            print('Spacebar pressed!')

In this example, the user presses the Spacebar, and a message is printed (Spacebar pressed!) to the console.

You can use multiple elif conditions to introduce additional keys as shown below:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        pygame.quit()
    elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
            print('Spacebar pressed!')
        elif event.key == pygame.K_UP:
            print('Up arrow pressed!')

Lastly, here’s a complete code snippet integrating pygame key inputs:

import pygame
pygame.init()

WIN_WIDTH, WIN_HEIGHT = 800, 600
WIN = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))

while True: # main game loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                print('Spacebar pressed!')
            elif event.key == pygame.K_UP:
                print('Up arrow pressed!')

We’ll delve into more action-oriented key usage next. Stay tuned!

Key States in Pygame

In the previous section, we processed keydown events. Another approach to handle keyboard input in Pygame is by keeping track of “key states”. For this purpose, we use `pygame.key.get_pressed()` function which returns a list of boolean values representing the state of each key on the keyboard.

In this next example, we identify if the Spacebar or Up arrow key is being pressed:

keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
    print('Spacebar pressed!')
if keys[pygame.K_UP]:
    print('Up arrow pressed!')

The major advantage of this method. We can process multiple keys being pressed at the same time. Here’s how you can implement it:

while True: # main game loop
    keys = pygame.key.get_pressed()
    if keys[pygame.K_SPACE] and keys[pygame.K_UP]:
        print('Spacebar and Up arrow pressed together!')

Now, let’s type some code into our program to create more interactivity.

Adding Movements Using Pygame Keys

We’ll be creating a simple game scenario where a player can move an object around the window using arrow keys.

First, let’s create a rectangle using pygame’s `Rect` function:

rect = pygame.Rect(WIN_WIDTH // 2, WIN_HEIGHT // 2, 50, 50)

This will create a rectangle in the center of our window with a width and height of 50.

We can get our rectangle to move by simply changing its x and y coordinates. Here’s how we can do it with arrow keys:

keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
    rect.move_ip(0, -2)  # move up
elif keys[pygame.K_DOWN]:
	rect.move_ip(0, 2)  # move down
elif keys[pygame.K_LEFT]:
	rect.move_ip(-2, 0)  # move left
elif keys[pygame.K_RIGHT]:
	rect.move_ip(2, 0)  # move right

The `move_ip` function changes the position of the rectangle in-place.

The complete code including creation of rectangle and controlling its movements using keys is as follows:

import pygame
pygame.init()

WIN_WIDTH, WIN_HEIGHT = 800, 600
WIN = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))

rect = pygame.Rect(WIN_WIDTH // 2, WIN_HEIGHT // 2, 50, 50)
 
while True: # main game loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
 
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        rect.move_ip(0, -2)  
    elif keys[pygame.K_DOWN]:
	    rect.move_ip(0, 2)  
    elif keys[pygame.K_LEFT]:
	    rect.move_ip(-2, 0) 
    elif keys[pygame.K_RIGHT]:
	    rect.move_ip(2, 0) 
		
    WIN.fill((0, 0, 0))  # fill the screen with black
    pygame.draw.rect(WIN, (255, 255, 255), rect)  # draw our rectangle
    pygame.display.update()  # update the display

With these pieces of code, you’re well on your way to adding nuanced, interactive movements to your game. Keep practicing to become more and more proficient. Happy coding!

Adding Velocity and Direction to Movements

Movements become more natural when we start to consider velocity and direction for our game objects. For that purpose, we need to define a velocity for our rectangle and a variable to keep track of its direction. Let’s add that to our program:

VELOCITY = 2
direction = {'UP': False, 'DOWN': False, 'LEFT': False, 'RIGHT': False}

while True: # main game loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                direction['UP'] = True
            elif event.key == pygame.K_DOWN:
                direction['DOWN'] = True
            elif event.key == pygame.K_RIGHT:
            	direction['RIGHT'] = True
            elif event.key == pygame.K_LEFT:
            	direction['LEFT'] = True
        elif event.type == pygame.KEYUP:
        	if event.key == pygame.K_UP:
        	    direction['UP'] = False
        	elif event.key == pygame.K_DOWN:
        	    direction['DOWN'] = False
        	elif event.key == pygame.K_RIGHT:
        	    direction['RIGHT'] = False
        	elif event.key == pygame.K_LEFT:
        	    direction['LEFT'] = False
         
    if direction['UP']:
        rect.move_ip(0, -VELOCITY)
    if direction['DOWN']:
        rect.move_ip(0, VELOCITY)
    if direction['LEFT']:
        rect.move_ip(-VELOCITY, 0)
    if direction['RIGHT']:
        rect.move_ip(VELOCITY, 0)

The above code allows the rectangle to move freely in any direction. Diagonal movements are possible too.

Preventing the Rectangle from Going Off Screen

Playing games where your characters or objects can move out of your screen is quite annoying. To prevent this situation, we can write a simple condition:

if rect.left  WIN_WIDTH: # checks if the rectangle has hit the right border
    rect.right = WIN_WIDTH
if rect.top  WIN_HEIGHT: # checks if the rectangle has hit the bottom border
    rect.bottom = WIN_HEIGHT

Complete code with velocity, direction, and screen constraint is as follows:

import pygame
pygame.init()

WIN_WIDTH, WIN_HEIGHT = 800, 600
WIN = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))

rect = pygame.Rect(WIN_WIDTH // 2, WIN_HEIGHT // 2, 50, 50)
VELOCITY = 2
direction = {'UP': False, 'DOWN': False, 'LEFT': False, 'RIGHT': False}

while True: # main game loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                direction['UP'] = True
            elif event.key == pygame.K_DOWN:
                direction['DOWN'] = True
            elif event.key == pygame.K_RIGHT:
            	direction['RIGHT'] = True
            elif event.key == pygame.K_LEFT:
            	direction['LEFT'] = True
        elif event.type == pygame.KEYUP:
        	if event.key == pygame.K_UP:
        	    direction['UP'] = False
        	elif event.key == pygame.K_DOWN:
        	    direction['DOWN'] = False
        	elif event.key == pygame.K_RIGHT:
        	    direction['RIGHT'] = False
        	elif event.key == pygame.K_LEFT:
        	    direction['LEFT'] = False
                
    if direction['UP']:
        rect.move_ip(0, -VELOCITY)
    if direction['DOWN']:
        rect.move_ip(0, VELOCITY)
    if direction['LEFT']:
        rect.move_ip(-VELOCITY, 0)
    if direction['RIGHT']:
        rect.move_ip(VELOCITY, 0)
    
    if rect.left  WIN_WIDTH:
        rect.right = WIN_WIDTH
    if rect.top  WIN_HEIGHT:
        rect.bottom = WIN_HEIGHT	
        
    WIN.fill((0, 0, 0))  # fill the screen with black
    pygame.draw.rect(WIN, (255, 255, 255), rect)  # draw our rectangle
    pygame.display.update()  # update the display

By completing this, you have now mastered how to take and process inputs using Pygame keys, assign directions and velocities to game objects and prevent it from going off the screen. These skills are fundamental to game development using Pygame. Keep going forward, you’re doing great!

Where to Go From Here?

Continuing your learning journey post-Pygame keys is full of thrilling opportunities. Mastering Python programming and game development involves the consolidation of several concepts and techniques, and with every new technique, a world of ideas opens up. So, where to next?

At Zenva, we believe in helping learners evolve from beginners to professionals. This journey requires a dedicated learning path and a comprehensive set of courses and tutorials. Our Python Mini-Degree is precisely engineered to foster this growth. This inclusive collection of courses cater to a wide range of topics – from coding basics, algorithms and object-oriented programming to immersive game development and app creation. Not only will you learn about other Python libraries and frameworks like Tkinter and Kivy, but also get to work on real-world projects and enhance your portfolio.

For those who wish to dive deeper into Python and explore its different applications, we also recommend our broad collection of Python courses. Expand your skill set with Zenva and never stop learning! Happy coding!

Conclusion

In this tutorial, we’ve delved deep into the concept of Pygame keys, understanding how keyboard inputs can be transformed into actionable movements in your Python games. Not only have you learned how to interpret these key events, but you’ve also engaged with assigning velocity and direction, and limiting movements within the gaming screen. This knowledge holds the potential to usher you into creating more engaging, interactive, and professional-grade games.

At Zenva, we are proud to be part of your learning journey and welcome you to continue building your mastery with our comprehensive Python Mini-Degree. With Python’s power in your hands, we are excited to see what you’ll create next in your trail of coding excellence!

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.