Pygame Beginner Tutorial: How to Build Your First Python Game

Pygame Beginner Tutorial: How to Build Your First Python Game
Pygame beginner tutorial hero image

Have you ever wanted to create your own video game but did not know where to begin?

Pygame is one of the most approachable ways to start learning game development with Python. It gives you tools for creating windows, drawing graphics, reading keyboard input, playing audio, tracking time, and detecting collisions.

In this Pygame beginner tutorial, you will build a small but complete game in which the player moves around the screen and collects a target. Each time the target is collected, the player’s score increases and the target moves to a new location.

By the end of this tutorial, you will understand:

  • How to install Pygame
  • How to create a game window
  • How the Pygame game loop works
  • How to draw objects on the screen
  • How to move a player with the keyboard
  • How to detect collisions
  • How to display a score
  • How to control the game’s frame rate

No previous game-development experience is required. Some basic familiarity with Python variables, loops, functions, and conditional statements will be helpful, but every important part of the game will be explained.

What Is Pygame?

Pygame is a free and open-source Python library used to create games and other multimedia applications. It provides Python interfaces for common game-development tasks such as graphics, sound, keyboard input, mouse input, timing, and window management. Pygame is built around the Simple DirectMedia Layer, commonly called SDL.

Pygame is especially useful for:

  • Learning the fundamentals of game programming
  • Building simple 2D games
  • Creating prototypes
  • Developing educational software
  • Experimenting with animation and interactive graphics
  • Practicing Python programming through visual projects

Pygame is not a complete visual game engine like Unity, Godot, or Unreal Engine. You generally create your game through Python code rather than placing objects inside a graphical editor. That makes Pygame an excellent learning tool because it exposes the basic systems that make a game work.

What You Will Build

The game in this tutorial will contain two objects:

  1. A blue player controlled with the arrow keys or WASD
  2. A yellow target that appears at a random position

When the player touches the target:

  • The score increases by one
  • The target moves to another random location
  • The game continues

Although this is a simple project, it introduces many concepts used in larger games:

  • The game loop
  • Input handling
  • Object movement
  • Screen boundaries
  • Collision detection
  • Random object placement
  • Text rendering
  • Frame-rate control

Step 1: Install Python

Before installing Pygame, you need Python on your computer. Download a current version of Python from the official Python website and follow the installer instructions for your operating system.

On Windows, make sure the Python installer is configured so that Python can be launched from the terminal. Depending on the installer version, this may involve enabling an option to add Python to your system path.

After installation, open Command Prompt, PowerShell, Terminal, or another command-line application and enter:

python --version

Some systems use the following command instead:

python3 --version

You should see a Python version number.

Step 2: Create a Project Folder

Create a new folder for the game, such as:

pygame-beginner-game

Open that folder in your preferred code editor. Good beginner-friendly editor options include Visual Studio Code, Thonny, IDLE, and PyCharm Community Edition.

Create a new Python file named:

main.py

This file will contain the game code.

Step 3: Create a Virtual Environment

A virtual environment keeps the packages used by one Python project separate from the packages used by other projects.

Open a terminal inside your project folder and run:

python -m venv .venv

On systems that use python3, enter:

python3 -m venv .venv

Activate the Virtual Environment on Windows

In Command Prompt:

.venv\Scripts\activate

In PowerShell:

.venv\Scripts\Activate.ps1

Activate the Virtual Environment on macOS or Linux

source .venv/bin/activate

After activation, you may see (.venv) at the beginning of your terminal prompt. Using a virtual environment is not absolutely required for a small tutorial, but it is a good habit for Python development.

Step 4: Install Pygame

With the virtual environment active, install Pygame using pip:

python -m pip install pygame

You can verify the installation with:

python -m pygame.examples.aliens

This command should launch one of Pygame’s included example programs. You can also test the installation in main.py:

import pygame
print(pygame.version.ver)

Run the file:

python main.py

If a Pygame version appears without an import error, the installation is working.

Step 5: Import and Initialize Pygame

Replace the contents of main.py with:

import pygame
pygame.init()

The first line imports the Pygame package. The second line initializes the imported Pygame modules. Most beginner projects should call pygame.init() near the beginning of the program.

Step 6: Create the Game Window

Add the following code:

import pygame
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("My First Pygame Game")

pygame.display.set_mode() creates the game window and returns the display surface. A Pygame Surface is an object used to represent an image or drawing area. The display surface is the main area where the game is drawn.

The window is 800 pixels wide and 600 pixels tall. pygame.display.set_caption() changes the title displayed at the top of the window.

Step 7: Create the Game Loop

A game must continually read input, update object positions, check game rules, draw the next frame, and repeat. This repeating structure is called the game loop.

import pygame
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("My First Pygame Game")
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
pygame.quit()

Run the program with python main.py. A blank window should appear, and you should be able to close it normally.

Understanding the Event Loop

Pygame stores events such as keyboard presses, mouse movement, and window-close requests in an event queue. Calling pygame.event.get() retrieves the events waiting in that queue. Without event handling, the operating system may consider the program unresponsive.

Step 8: Fill the Background

Define a background color near the top of the file:

BACKGROUND_COLOR = (30, 30, 40)

Then place the following line inside the game loop, after the event-handling section:

screen.fill(BACKGROUND_COLOR)

Colors in Pygame are commonly represented using RGB values:

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

After drawing the background, update the display:

pygame.display.flip()

Step 9: Create the Player

For this first game, the player will be represented by a rectangle. Add these constants:

PLAYER_COLOR = (70, 150, 255)
PLAYER_SIZE = 50
PLAYER_SPEED = 5

Create the player rectangle before the game loop:

player = pygame.Rect(
    SCREEN_WIDTH // 2 - PLAYER_SIZE // 2,
    SCREEN_HEIGHT // 2 - PLAYER_SIZE // 2,
    PLAYER_SIZE,
    PLAYER_SIZE,
)

Draw the player inside the game loop:

pygame.draw.rect(screen, PLAYER_COLOR, player)

Run the program again. You should see a blue square in the window.

Step 10: Move the Player

Add this code inside the game loop after the event-handling section:

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] or keys[pygame.K_a]:
    player.x -= PLAYER_SPEED
if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
    player.x += PLAYER_SPEED
if keys[pygame.K_UP] or keys[pygame.K_w]:
    player.y -= PLAYER_SPEED
if keys[pygame.K_DOWN] or keys[pygame.K_s]:
    player.y += PLAYER_SPEED

The player can now move with the arrow keys or WASD. Horizontal movement changes player.x, while vertical movement changes player.y.

Step 11: Keep the Player on the Screen

At the moment, the player can move outside the visible window. Add the following code after the movement logic:

player.clamp_ip(screen.get_rect())

The screen.get_rect() method returns a rectangle representing the screen boundaries. clamp_ip() moves the player rectangle back inside those boundaries when necessary.

Step 12: Control the Frame Rate

Create a clock before the game loop:

clock = pygame.time.Clock()

Then add the following line near the end of the game loop:

clock.tick(60)

The game will now target a maximum of approximately 60 frames per second. The clock also prevents the game loop from using more processing time than necessary.

Step 13: Add a Collectible Target

Import Python’s random module at the top of the file:

import random
import pygame

Add the target settings:

TARGET_COLOR = (255, 215, 70)
TARGET_SIZE = 30

Create the target before the game loop:

target = pygame.Rect(
    random.randint(0, SCREEN_WIDTH - TARGET_SIZE),
    random.randint(0, SCREEN_HEIGHT - TARGET_SIZE),
    TARGET_SIZE,
    TARGET_SIZE,
)

Draw the target inside the game loop:

pygame.draw.rect(screen, TARGET_COLOR, target)

You should now see a yellow square somewhere in the window.

Step 14: Detect Collisions

Create a score variable before the game loop:

score = 0

Then add the following collision logic after the player movement code:

if player.colliderect(target):
    score += 1
    target.x = random.randint(0, SCREEN_WIDTH - TARGET_SIZE)
    target.y = random.randint(0, SCREEN_HEIGHT - TARGET_SIZE)

When the player touches the target, the score increases by one and the target moves to a new random location.

Step 15: Display the Score

Create a font object before the game loop:

font = pygame.font.Font(None, 36)

Inside the game loop, create the score image:

score_text = font.render(
    f"Score: {score}",
    True,
    (255, 255, 255),
)

Then draw it on the screen:

screen.blit(score_text, (20, 20))

The blit operation copies the rendered text surface onto the display surface at the coordinates (20, 20).

Complete Pygame Beginner Game Code

Here is the complete program:

import random
import pygame
# Initialize Pygame
pygame.init()
# Window settings
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60
# Colors
BACKGROUND_COLOR = (30, 30, 40)
PLAYER_COLOR = (70, 150, 255)
TARGET_COLOR = (255, 215, 70)
TEXT_COLOR = (255, 255, 255)
# Player settings
PLAYER_SIZE = 50
PLAYER_SPEED = 5
# Target settings
TARGET_SIZE = 30
# Create the game window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Collect the Target")
# Create a clock for frame-rate control
clock = pygame.time.Clock()
# Create the score font
font = pygame.font.Font(None, 36)
# Create the player in the center of the screen
player = pygame.Rect(
    SCREEN_WIDTH // 2 - PLAYER_SIZE // 2,
    SCREEN_HEIGHT // 2 - PLAYER_SIZE // 2,
    PLAYER_SIZE,
    PLAYER_SIZE,
)
# Create the target at a random location
target = pygame.Rect(
    random.randint(0, SCREEN_WIDTH - TARGET_SIZE),
    random.randint(0, SCREEN_HEIGHT - TARGET_SIZE),
    TARGET_SIZE,
    TARGET_SIZE,
)
# Game state
score = 0
running = True
# Main game loop
while running:
    # Process events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # Read the current keyboard state
    keys = pygame.key.get_pressed()
    # Move the player
    if keys[pygame.K_LEFT] or keys[pygame.K_a]:
        player.x -= PLAYER_SPEED
    if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
        player.x += PLAYER_SPEED
    if keys[pygame.K_UP] or keys[pygame.K_w]:
        player.y -= PLAYER_SPEED
    if keys[pygame.K_DOWN] or keys[pygame.K_s]:
        player.y += PLAYER_SPEED
    # Keep the player inside the window
    player.clamp_ip(screen.get_rect())
    # Check whether the player collected the target
    if player.colliderect(target):
        score += 1
        target.x = random.randint(0, SCREEN_WIDTH - TARGET_SIZE)
        target.y = random.randint(0, SCREEN_HEIGHT - TARGET_SIZE)
    # Draw the background and game objects
    screen.fill(BACKGROUND_COLOR)
    pygame.draw.rect(screen, TARGET_COLOR, target)
    pygame.draw.rect(screen, PLAYER_COLOR, player)
    # Create and draw the score text
    score_text = font.render(f"Score: {score}", True, TEXT_COLOR)
    screen.blit(score_text, (20, 20))
    # Show the completed frame and limit the frame rate
    pygame.display.flip()
    clock.tick(FPS)
# Shut down Pygame
pygame.quit()

Save the file and run:

python main.py

Move the blue square into the yellow target. Every collision should increase the score and move the target.

How the Complete Game Works

1. Initialization

pygame.init() prepares the required Pygame modules.

2. Game Setup

The program creates the display window, frame-rate clock, font, player rectangle, target rectangle, and score variable. These objects are created before the main loop because they need to persist throughout the game.

3. Event Processing

The program processes pygame.QUIT events so the window remains responsive and can be closed normally.

4. Game-State Updates

The program reads the keyboard, moves the player, restricts the player to the screen, and checks for collisions.

5. Drawing

The program draws the background, target, player, and score. Drawing order matters because objects drawn later appear over objects drawn earlier.

6. Frame Completion

pygame.display.flip() reveals the completed frame, while clock.tick(FPS) limits how quickly the game loop repeats.

Common Pygame Beginner Errors

Error: No Module Named Pygame

This usually means Pygame is not installed in the Python environment running your program. Try python -m pip install pygame, then run the program with the same Python command.

The Window Opens and Immediately Closes

This usually happens when there is no game loop, the program encounters an error, running becomes false immediately, or pygame.quit() is called too early. Run the program from a terminal so any error message remains visible.

The Window Stops Responding

Make sure the game loop processes events with pygame.event.get(). Failing to handle the event queue can make the window appear frozen.

The Player Moves Too Quickly

Reduce PLAYER_SPEED and confirm that the game has a frame-rate limit such as clock.tick(60).

Objects Leave Trails Behind Them

Clear the screen before drawing each new frame with screen.fill(BACKGROUND_COLOR).

The Player Appears Behind Another Object

Check the drawing order. Objects drawn later appear over objects drawn earlier.

Ways to Improve the Game

Add a Countdown Timer

Give the player 30 seconds to collect as many targets as possible. pygame.time.get_ticks() can be used to measure elapsed time.

Add a High Score

Store the highest score reached during the current session, or save it to a text or JSON file.

Add Sound Effects

Play a sound whenever the target is collected by using Pygame’s mixer module.

Replace Rectangles with Images

Load image files with pygame.image.load("player.png").convert_alpha() and draw them with screen.blit().

Add Enemies

Create red rectangles that move around the screen. Touching an enemy could end the game or reduce the score.

Add Multiple Targets

Store several target rectangles in a list and check each one for collisions.

Increase the Difficulty

Increase player speed, make the target smaller, add enemies, or shorten the time limit as the score rises.

A Better Project Structure for Larger Pygame Games

Keeping everything inside one file is acceptable for a beginner project. Larger games are easier to maintain when the code is divided into separate files:

my_game/
├── assets/
│   ├── images/
│   ├── sounds/
│   └── fonts/
├── main.py
├── player.py
├── target.py
├── settings.py
└── requirements.txt
  • main.py: Game loop and overall control
  • player.py: Player behavior
  • target.py: Target behavior
  • settings.py: Screen dimensions, colors, and speeds
  • assets/: Images, audio, and font files
  • requirements.txt: Python package requirements

Important Pygame Concepts to Learn Next

Delta Time

Multiply movement by the amount of time since the previous frame so movement is less dependent on frame rate.

Sprites and Sprite Groups

Use sprites to organize enemies, bullets, obstacles, collectibles, and animated objects.

Animation

Cycle through multiple images over time to create movement such as walking or jumping.

Game States

Organize menus, gameplay, pause screens, settings, and game-over screens as separate states.

Tile Maps

Build levels from reusable image tiles for platformers, role-playing games, and top-down adventures.

Object-Oriented Programming

Use classes to organize player, enemy, projectile, and other object behavior.

Is Pygame Good for Beginners?

Yes. Pygame is a strong choice for beginners who want to learn programming through game development. It provides immediate visual results while reinforcing variables, loops, conditional statements, functions, lists, classes, file management, mathematics, coordinate systems, and problem solving.

Pygame also makes many underlying game-development concepts visible. You are responsible for the loop, movement, collision rules, drawing order, and state changes. This requires more coding than some visual game engines, but it can provide a better understanding of how games work internally.

Is Pygame Suitable for Professional Games?

Pygame is most commonly associated with education, prototypes, game jams, small independent games, and 2D projects. It can produce polished software, but it does not provide many of the integrated production tools found in larger engines. Its greatest strengths are simplicity, Python integration, rapid experimentation, educational value, and direct control over game logic.

Frequently Asked Questions About Pygame

Is Pygame free?

Yes. Pygame is free and open-source software.

Do I need to know Python before learning Pygame?

You do not need to be an expert, but familiarity with variables, data types, if statements, loops, functions, and imports will make Pygame easier.

Can Pygame create 3D games?

Pygame is primarily designed for 2D graphics and multimedia applications. Beginners mainly interested in 3D development will usually benefit from a dedicated 3D engine.

Can Pygame run on a Raspberry Pi?

Yes. Pygame can run on Raspberry Pi systems with a compatible Python and Pygame installation. It is useful for games, educational projects, dashboards, and interactive hardware projects.

Can I make a platformer with Pygame?

Yes. You will need to implement gravity, jumping, platforms, collision response, level loading, camera movement, and animation.

Can I publish a game made with Pygame?

Yes. You can distribute a Pygame project, although packaging it for other users requires additional steps.

Is Pygame difficult to learn?

The fundamentals are approachable. The larger challenge is learning general game-development concepts such as movement, collision response, animation, state management, and level design.

Final Thoughts

Pygame provides an accessible introduction to Python game development. In this tutorial, you learned how to install Pygame, initialize the library, create a game window, build a game loop, process window events, read keyboard input, move a player, enforce screen boundaries, create a randomly positioned target, detect collisions, display a score, and limit the frame rate.

The completed game is intentionally simple, but its structure is the foundation of many larger 2D games. The best next step is to modify the project by adding a timer, enemies, sounds, images, or a game-over screen. Each new feature will introduce another important programming and game-design concept.

You do not need to begin with a complicated idea. A small playable project that you understand is more valuable than a large unfinished game copied from someone else. Start simple, experiment often, and build one feature at a time.

Reference Sources

  • Pygame documentation: https://www.pygame.org/docs/
  • Pygame source repository: https://github.com/pygame/pygame
  • Python virtual environments documentation: https://docs.python.org/3/tutorial/venv.html
Next
Next

Best Smart Home Protocols for Home Assistant