Skip to content
Tutorials Center
My learning

Topics

Lesson 1 of 41 ยท Getting Started

Introduction to Pygame

Meet Pygame, the Python library for 2D games. Learn what it does, how pygame and pygame-ce differ, what a game loop is, and run your first headless pygame code.

Pygame is a free library that lets you build 2D games and interactive graphics in Python. It wraps SDL, a C library that talks to the window system, the keyboard, the mouse, the sound card and the game controller, and gives you a friendly Python interface to all of it. You write short Python code; Pygame draws pixels, plays sounds and delivers input events.

People use Pygame to learn programming, to prototype game ideas, to write small arcade games, to build visualizations (sorting algorithms, simulations, physics toys) and to teach. It is not a 3D engine and it is not meant for huge commercial titles, but for 2D it is fast enough and very easy to start with.

pygame or pygame-ce?

There are two packages that you import the same way (import pygame):

  • pygame is the original project.
  • pygame-ce ("Community Edition") is a fork that is more actively developed. It has newer features, faster releases and many bug fixes, and it supports the newest Python versions first.

Their code is almost identical, and every lesson in this course works in both. If you are starting today, install pygame-ce (see Installing Pygame). Never install both in the same environment, because they share the module name and will conflict.

How a game works

Every game, no matter how large, repeats the same cycle many times per second:

flowchart LR
    A["Handle events<br/>(keys, mouse, quit)"] --> B["Update state<br/>(move, collide, score)"]
    B --> C["Draw everything<br/>(clear, blit, shapes)"]
    C --> D["Wait for next frame<br/>(clock.tick)"]
    D --> A

The game loop: input, update, draw, wait. One pass is one frame.

If the loop runs 60 times per second, the game runs at 60 frames per second (FPS). Each pass you read what the player did, change your game state, redraw the whole screen, and then wait just long enough to keep the speed steady. You will build this loop yourself in The Game Loop.

What Pygame gives you

Window and drawing Surfaces, shapes, images, text
Input Keyboard, mouse, gamepads
Sound Effects and music
Timing Clock and timers

Plain Python on top of SDL.

1 / 2

The main modules

Pygame is a package of small modules. You will meet all of these in this course:

Module What it does
pygame.display Creates the window and shows finished frames
pygame.event The queue of things that happened (key presses, clicks, quit)
pygame.draw Draws lines, rectangles, circles, polygons
pygame.image Loads and saves images
pygame.font Renders text to images
pygame.mixer Plays sound effects and music
pygame.time Clock, timers and tick counters
pygame.key, pygame.mouse Reads the keyboard and mouse directly
pygame.sprite Game objects, groups and collision helpers
pygame.math Vector2 and Vector3
pygame.mask Pixel-perfect collision shapes
pygame.transform Scale, rotate and flip surfaces

The central ideas are the Surface (a rectangle of pixels), the Rect (a rectangle with handy position attributes) and the event queue. Everything else is built on those three.

A complete first game, in miniature

Here is a full Pygame program. It opens a window, moves a ball and closes when you click the close button. Do not worry about every line yet: each one is explained in the next lessons. This code needs a real window, so it is shown read-only. Copy it into a file called ball.py on your own computer and run it after installing Pygame.

Python
import pygame

pygame.init()
screen = pygame.display.set_mode((640, 360))
pygame.display.set_caption("My first game")
clock = pygame.time.Clock()

x, speed = 50, 4
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    x += speed
    if x > 640 or x < 0:
        speed = -speed

    screen.fill((20, 24, 40))
    pygame.draw.circle(screen, (255, 200, 60), (x, 180), 20)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Read it top to bottom: initialize, create a window, then loop. Each frame it handles events, moves x, clears the screen with fill, draws a circle and flips the finished image to the monitor.

Note: Windows, sound and the event queue need a real display and audio device. The browser runner on this site is headless, so the runnable examples in this course use the parts of Pygame that work without a window: Surface, Rect, Vector2, draw, transform, mask, sprite, font and Clock. They are the same classes your real game uses, so what you learn carries over. Examples labelled "stand-in" simulate the window parts in plain Python and print text.

Try it: pixels without a window

A Surface is just a grid of pixels in memory. The screen window is a special surface; you can also make your own. This example paints a small picture and prints it as text so you can see it.

Python Draw on a Surface and print it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You just used the same pygame.draw functions that draw on a real screen. Only the destination differs.

Try it: your game as a state machine

Games are just state that changes each frame. This stand-in runs ten frames of the ball program above without a window and prints where the ball is.

Python Stand-in: ten frames of the ball game

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the ball hits the right edge and bounces back: the update step changed speed, and the next frame used it. That is the whole idea of a game loop.

Some useful facts

  • Pygame can run on Windows, macOS, Linux, Raspberry Pi and, with extra tooling, in the browser (via WebAssembly).
  • Coordinates start at the top-left corner: x grows to the right and y grows downward.
  • Colors are (red, green, blue) tuples with values from 0 to 255.
  • Pygame is single-threaded by design. A slow update makes the frame rate drop; keep each frame's work small.
  • Many indie games and thousands of game-jam entries have been made with it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the three repeating steps of a game loop, before waiting for the next frame?

    Each frame reads input, changes the game state and draws the result. Then the loop waits to keep a steady frame rate.
  2. 2. What is the difference between pygame and pygame-ce?

    Both are imported with import pygame. Install only one of them in an environment.
  3. 3. Where is the origin (0, 0) of the screen, and which way does y grow?

    Pygame uses the usual computer graphics convention of the top-left corner as the origin with y growing downward.
  4. 4. What is a Surface?

    Surfaces hold pixels. The window is a special surface, and images you load are surfaces too.

Summary

  • Pygame is a Python library for 2D games, built on SDL.
  • Install pygame-ce (or pygame), but never both.
  • A game is a loop: events, update, draw, wait.
  • Surfaces hold pixels, Rects describe positions, and the event queue delivers input.
  • The origin is the top-left and y grows downward.
  • Runnable examples here use headless Surfaces and plain-Python stand-ins.

Next: Installing Pygame