What you need to know before you start

Building a game in Python means writing code that handles three things: drawing graphics on screen, responding to keyboard and mouse input, and updating what happens each frame. Python itself is just a language — you need a library that does the drawing and input work for you. The most common choice is Pygame, which is free, runs on Windows, Mac, and Linux, and has enough built-in tools to make 2D games without learning graphics programming first.

This guide walks you through installing Pygame, writing your first moving character, handling player input, and building a simple game loop — the repeating cycle that makes a game actually run. You will write real code in real order, not theory. By the end, you will have a working game you can expand.

Key Takeaways

  • Install Python 3.8 or newer, then use pip to install Pygame in one command from your terminal or command prompt.
  • Every game needs a loop that runs 60 times per second, drawing the screen, checking for input, and updating positions.
  • Pygame handles drawing rectangles and images, detecting key presses, and measuring time — the core tasks you need for a playable game.
  • Start with a single moving character and collision detection before adding enemies, scoring, or sound.
  • Test your game constantly as you add each piece, because bugs are easier to find when you know what you just changed.

Install Python and Pygame on your computer

First, check whether Python is already installed. Open your terminal (Mac and Linux) or command prompt (Windows) and type python --version. If you see version 3.8 or higher, you can skip to the Pygame install. If you see an error or a version older than 3.8, download Python from python.org, run the installer, and make sure to check the box that says "Add Python to PATH" on Windows.

Once Python is installed, install Pygame by typing this command into your terminal or command prompt:

pip install pygame

Wait for the installation to finish. You will see a message saying "Successfully installed pygame" when it is done. Test it by opening Python and typing import pygame — if no error appears, Pygame is ready.

Write your first game window and game loop

Create a new file called game.py in a folder on your computer. Open it in a text editor (Notepad, Visual Studio Code, or any editor that saves plain text). Type this code:

import pygame import sys pygame.init() screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("My Game") clock = pygame.time.Clock() running = True while running:     for event in pygame.event.get():         if event.type == pygame.QUIT:             running = False          screen.fill((0, 0, 0))     pygame.display.flip()     clock.tick(60)

Save the file and run it from your terminal by typing python game.py. A black window should appear. Click the X button to close it. This code does the essential work: it creates a window, starts a loop that runs 60 times per second, checks for the quit event, and refreshes the screen. Every game you build will have this same structure.

Add a player character that moves with the keyboard

Now add a rectangle that represents your player and moves when you press arrow keys. Replace the code inside your while loop with this:

player_x = 375 player_y = 275 player_width = 50 player_height = 50 player_speed = 5 while running:     for event in pygame.event.get():         if event.type == pygame.QUIT:             running = False          keys = pygame.key.get_pressed()     if keys[pygame.K_LEFT]:         player_x -= player_speed     if keys[pygame.K_RIGHT]:         player_x += player_speed     if keys[pygame.K_UP]:         player_y -= player_speed     if keys[pygame.K_DOWN]:         player_y += player_speed          screen.fill((0, 0, 0))     pygame.draw.rect(screen, (255, 0, 0), (player_x, player_y, player_width, player_height))     pygame.display.flip()     clock.tick(60)

Run the game again. A red square should appear in the center of the window. Press the arrow keys and the square moves. The code checks which keys are pressed every frame, then moves the player position left, right, up, or down. The pygame.draw.rect() function draws the rectangle at the new position, and pygame.display.flip() shows it on screen.

Detect collisions and add a target to collect

Add a target object that the player collides with. Add this code before the while loop:

target_x = 600 target_y = 300 target_width = 40 target_height = 40 score = 0

Then inside the while loop, after you update the player position but before you draw, add this collision check:

player_rect = pygame.Rect(player_x, player_y, player_width, player_height) target_rect = pygame.Rect(target_x, target_y, target_width, target_height) if player_rect.colliderect(target_rect):     score += 1     target_x = 100     target_y = 100

Then in your drawing section, add a line to draw the target:

pygame.draw.rect(screen, (0, 255, 0), (target_x, target_y, target_width, target_height))

Run the game. A green square appears. Move the red square over it and the green square jumps to a new position. The colliderect() function checks whether two rectangles overlap. When they do, the score increases and the target moves. This is the foundation for any game mechanic where the player interacts with objects.

Display the score on screen

Add text to show the player their score. First, create a font object before the while loop:

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

Then in your drawing section, after you draw the rectangles but before pygame.display.flip(), add:

score_text = font.render("Score: " + str(score), True, (255, 255, 255)) screen.blit(score_text, (10, 10))

Run the game. White text showing your score appears in the top-left corner and updates every time you collect the target. The font.render() function turns text into an image, and screen.blit() draws that image at a specific position.

Expand your game with enemies and boundaries

Keep the player from moving off screen by adding boundary checks. After you update the player position, add:

if player_x < 0:     player_x = 0 if player_x + player_width > 800:     player_x = 800 - player_width if player_y < 0:     player_y = 0 if player_y + player_height > 600:     player_y = 600 - player_height

To add an enemy, create a list before the while loop and add enemies to it:

enemies = [] for i in range(3):     enemies.append({"x": 100 + i * 200, "y": 100, "width": 40, "height": 40})

Then in your loop, move each enemy and check for collision with the player:

for enemy in enemies:     enemy["x"] += 2     if enemy["x"] > 800:         enemy["x"] = -40          enemy_rect = pygame.Rect(enemy["x"], enemy["y"], enemy["width"], enemy["height"])     if player_rect.colliderect(enemy_rect):         running = False

And draw them:

for enemy in enemies:     pygame.draw.rect(screen, (255, 255, 0), (enemy["x"], enemy["y"], enemy["width"], enemy["height"]))

Run the game. Yellow squares move across the screen from left to right. Touch one and the game ends. This pattern — storing objects in a list, updating them each frame, drawing them, and checking collisions — is how you add complexity to a game without rewriting the core loop.

Frequently Asked Questions

Why does my game run slowly or stutter?

The most common cause is drawing too many objects or checking collisions inefficiently. Start by checking that clock.tick(60) is in your loop — it limits the game to 60 frames per second. If the game still stutters, reduce the number of enemies or targets, or move collision checks outside the drawing section so they only run once per frame instead of multiple times.

How do I load an image instead of drawing a rectangle?

Use pygame.image.load("filename.png") to load an image file, then screen.blit(image, (x, y)) to draw it. Store the image in the same folder as your game.py file. Collision detection works the same way — use image.get_rect() to get the rectangle around the image and check collisions as before.

Can I add sound to my game?

Yes. Use pygame.mixer.Sound("filename.wav") to load a sound file, then call sound.play() when something happens — for example, when the player collects a target. Store sound files in the same folder as your game.

What should I build next after this basic game?

Add a timer that counts down, or a lives system where touching an enemy costs a life instead of ending the game immediately. Then try adding levels where the number of enemies increases, or make the target worth different points depending on which one you collect. Each addition teaches you a new pattern you will use in larger games.

Where do I find Pygame documentation when I get stuck?

The official Pygame documentation is at pygame.org. Search for the function name you are using — for example, "pygame.draw.rect" — and the page shows what arguments it takes and what it returns. Reading documentation is a skill that gets faster with practice.