Pygame is a free, open-source Python library for building 2D games and multimedia applications. It wraps the SDL (Simple DirectMedia Layer) C library, so Python code can create a window, draw images and shapes, play sounds, and handle keyboard, mouse and gamepad input on Windows, macOS and Linux. You install it with pip install pygame, call pygame.init(), and run a game loop.
If you are searching for what is Pygame, the practical answer is this: it is a free, open-source Python library that lets you draw graphics, play sound, read keyboard and mouse input, and run a game loop with very little code.
Pygame started as a tool for 2D games, but engineers use it for much more. Quick simulators, live sensor dashboards and touchscreen interfaces on boards like the Raspberry Pi are all common uses.
In this guide you will learn what the Pygame library is, how it works, its features and key functions, how to install it, and how to write a working program. You will also see where it fits in embedded and IoT work, and where it does not.
Python has no built-in way to open a window, animate an object or play a sound. Pygame fills that gap with a small, readable API, which is why it has stayed popular for more than two decades.
Quick history (facts):
Why it matters for engineers:
pip install and you are drawing.Five ideas explain almost everything you will do in Pygame:
blit().pygame.event.get() hands them to your code.Engineer’s note: Rect stores integers. If you add speed * dt straight onto a Rect position, the fractional part is thrown away and slow objects can freeze or drift. Keep a float position and copy it into the Rect each frame.
A Pygame program is one loop that repeats many times per second. Each pass is one frame:
pygame.display.flip() to show the finished frame.clock.tick(60) so the loop does not run faster than needed.If you have written a super-loop on a microcontroller, this pattern is familiar. The event queue plays the role of flags your main loop polls, and clock.tick() is the software cousin of waiting for a timer tick. Keep in mind that Pygame runs on a general-purpose operating system, so timing is soft, not hard real-time.
Your Python game code
|
Pygame modules (display, event, draw, image, font, mixer, sprite)
|
SDL2: video, audio, input and timers (written in C)
|
OS and drivers: Windows, macOS, Linux (X11, Wayland, KMSDRM)
|
Hardware: display, speakers, keyboard, mouse, gamepad, touchscreen
The same layering appears in embedded Linux graphics: application, library, driver, hardware. Once you see this stack, an error such as No available video device makes sense immediately, because SDL could not find a display to attach to.
pygame.mixer module.Rect collisions for speed, and pygame.mask for pixel-perfect checks.pygame.time.Clock for frame-rate control and delta time.pygame.math.Vector2 and Vector3 for positions, velocities and directions.pygame.surfarray exposes pixels as NumPy arrays for bulk image processing.python3 -m pygame.examples.aliens to see a complete sample game.| Function or class | What it does |
|---|---|
| pygame.init() | Initializes all Pygame modules |
| pygame.display.set_mode((w, h)) | Creates the window and returns the screen Surface |
| pygame.display.set_caption(text) | Sets the window title |
| pygame.event.get() | Returns all pending events from the queue |
| pygame.key.get_pressed() | Returns the current state of every key |
| pygame.time.Clock().tick(fps) | Caps the frame rate and returns elapsed milliseconds |
| Surface.fill(color) | Clears or colors a Surface |
| Surface.blit(source, pos) | Copies one Surface onto another |
| pygame.draw.rect / circle / line | Draws basic shapes |
| pygame.image.load(path) | Loads an image file into a Surface |
| pygame.font.SysFont(name, size) | Creates a font; render() turns text into a Surface |
| pygame.mixer.Sound(path).play() | Plays a sound effect |
pygame.display.flip() / update() | Shows the frame you just drew |
| pygame.quit() | Shuts down all modules |
Engineer’s note: flip() redraws the whole screen, while update(rect_list) refreshes only the regions you pass. On a slow board with a mostly static interface, partial updates can help on some setups, so measure before you commit to them.
Both packages are imported with import pygame, which surprises many beginners.
pip install pygame-ce. Version 2.5.8 (August 2026) requires Python 3.10 or newer.Check PyPI for newer releases before you pin a version.
Facts first, then recommendations. Pygame is strongest for prototypes, tools and 2D products.
Step 1: Check Python and pip
python --version
pip --version
Step 2: Install Pygame
# Windows
py -m pip install pygame
# macOS and Linux
python3 -m pip install pygame
Step 3: Verify the installation
python3 -m pygame.examples.aliens
This opens a bundled demo game, which confirms that graphics, sound and input work. Importing Pygame also prints a banner with the Pygame, SDL and Python versions, which is handy when you are asking for help.
Raspberry Pi OS and other Debian-based systems
Recent Raspberry Pi OS releases block system-wide pip install with an externally-managed-environment error. Use a virtual environment, or the system package:
python3 -m venv ~/pygame-env
source ~/pygame-env/bin/activate
pip install pygame
# Alternative: system package
sudo apt install python3-pygame
Install troubleshooting
pip not found: use python -m pip instead.pygame and pygame-ce. Run pip uninstall pygame pygame-ce, then install only one.ModuleNotFoundError: pip installed into a different Python than the one running your script. Activate the right virtual environment.Every Pygame program follows the same five steps:
import pygame, then pygame.init().screen = pygame.display.set_mode((640, 360)).pygame.time.Clock(), Rects, images, fonts.pygame.display.flip().pygame.quit() when the loop ends.This small game moves a paddle with the left and right arrow keys and bounces a ball. Save it as catch_ball.py and run python3 catch_ball.py.
import sys
import pygame
pygame.init()
WIDTH, HEIGHT, FPS = 640, 360, 60
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('IIES Pygame Demo: Catch the Ball')
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 28)
# Game objects
player = pygame.Rect(WIDTH // 2 - 40, HEIGHT - 30, 80, 12)
player_x = float(player.x) # float copy avoids Rect truncation
PLAYER_SPEED = 360 # pixels per second
ball_pos = pygame.Vector2(WIDTH // 2, HEIGHT // 3)
ball_vel = pygame.Vector2(220, 180) # pixels per second
BALL_RADIUS = 10
score = 0
running = True
while running:
dt = min(clock.tick(FPS) / 1000, 0.05) # seconds per frame, capped
# 1. Input
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 * dt
if keys[pygame.K_RIGHT]:
player_x += PLAYER_SPEED * dt
player_x = max(0, min(WIDTH - player.width, player_x))
player.x = round(player_x)
# 2. Update
ball_pos += ball_vel * dt
if ball_pos.x < BALL_RADIUS: ball_vel.x = abs(ball_vel.x) elif ball_pos.x > WIDTH - BALL_RADIUS:
ball_vel.x = -abs(ball_vel.x)
if ball_pos.y < BALL_RADIUS: ball_vel.y = abs(ball_vel.y) ball_rect = pygame.Rect(0, 0, BALL_RADIUS * 2, BALL_RADIUS * 2) ball_rect.center = (round(ball_pos.x), round(ball_pos.y)) if ball_rect.colliderect(player) and ball_vel.y > 0:
ball_vel.y = -abs(ball_vel.y)
score += 1
if ball_pos.y > HEIGHT + BALL_RADIUS: # missed the ball
ball_pos.update(WIDTH // 2, HEIGHT // 3)
score = 0
# 3. Draw
screen.fill((18, 24, 38))
pygame.draw.rect(screen, (0, 200, 150), player)
pygame.draw.circle(screen, (255, 180, 0), ball_rect.center, BALL_RADIUS)
screen.blit(font.render(f'Score: {score}', True, (230, 230, 230)), (10, 10))
# 4. Present
pygame.display.flip()
pygame.quit()
sys.exit()
pygame.init() starts the modules, set_mode() creates the window, and Clock and Font are created once, before the loop.dt): clock.tick(FPS) returns milliseconds since the last frame. Multiplying speed by dt keeps motion the same on a fast PC and a slower Raspberry Pi. The 0.05 cap stops the ball from teleporting after a stall.player_x holds the exact position and player.x receives the rounded value, which avoids the integer truncation problem in Rect.event.get() is called every frame so the window stays responsive. get_pressed() reads held keys, which suits continuous movement.abs() to set the direction is safer than flipping the sign, because the ball can never get stuck outside a wall.colliderect() checks overlap. The ball_vel.y > 0 test makes sure the paddle scores once per bounce, not on every frame of contact.Common errors in this program:
pygame.event.get() was removed or is not called every frame.pygame.error: video system not initialized: a display call ran before pygame.init().dt was not used for movement.This is where Pygame becomes useful for embedded work. A Raspberry Pi or other Linux board reads a sensor, and Pygame draws the result.
readline() call that waits for serial data will freeze the window.import threading
import pygame
import serial # pip install pyserial
pygame.init()
SENSOR_EVENT = pygame.event.custom_type()
def read_serial(port='/dev/ttyUSB0', baud=115200): # COM3 on Windows
with serial.Serial(port, baud, timeout=1) as ser:
while True:
line = ser.readline().decode(errors='ignore').strip()
if line:
pygame.event.post(pygame.event.Event(SENSOR_EVENT, value=line))
threading.Thread(target=read_serial, daemon=True).start()
# Inside your main loop:
# for event in pygame.event.get():
# if event.type == SENSOR_EVENT:
# latest_reading = event.value
Engineer’s note: if your sensor streams at 1 kHz and your screen runs at 60 FPS, draw only the latest value or a decimated buffer. Keep the full-rate data in a ring buffer or a log file.
| Option | Language | Best for | Trade-off |
|---|---|---|---|
| Pygame | Python | Learning, prototypes, 2D games, dashboards | You build most systems yourself |
| Pygame-CE | Python | Same as Pygame, with faster fixes and extra features | Needs a newer Python; never mix with pygame |
| Arcade | Python | Modern 2D games with built-in physics and tilemap support | Needs OpenGL-capable graphics; smaller community |
| Godot | GDScript, C# | Full 2D and 3D games with a visual editor | Heavier tool; less natural for Python or embedded Linux dashboards |
Recommendation: pick Pygame when you want to understand how things work or need a quick visual tool. Pick an engine when you need an editor, 3D or large-team workflows.
dt.convert() or convert_alpha() once after loading.pygame==2.6.1 (or your chosen pygame-ce version) in requirements.txt and use a virtual environment.pygame.SCALED flag when you open the window.pygame.quit() and release serial ports and files.| Mistake | Why it happens | Impact | How professionals avoid it |
|---|---|---|---|
Not calling event.get() every frame | Beginners place it inside a condition or forget it | Window freezes and the OS reports Not Responding | Pump events once per frame at the top of the loop |
| Moving objects by pixels per frame | It works on the developer’s PC | Different speeds on different hardware | Use pixels per second times dt, with dt capped |
| Loading images or fonts inside the loop | Snippets are copied without restructuring | Disk reads every frame, stutter, high CPU | Load once before the loop and store in variables or a dict |
Skipping convert() and convert_alpha() | Images still display, so the cost is invisible | Slow blits from per-frame format conversion | Convert every image right after loading |
| Installing pygame and pygame-ce together | Following two different tutorials | Import errors or strange behavior | One package per virtual environment, pinned in requirements.txt |
| Blocking calls in the main loop | Using time.sleep(), input() or a blocking serial read | Frozen window and missed input | Use Clock.tick(), worker threads and custom events |
pygame.get_sdl_version() tell you which Pygame, SDL and Python you are really running.pygame.display.set_caption(f'{clock.get_fps():.0f} FPS') is the cheapest profiler you have.pygame.draw.rect(screen, (255, 0, 0), rect, 1) while debugging collisions.print(event) shows exactly what the queue delivers, including unexpected types.SDL_VIDEODRIVER=dummy and SDL_AUDIODRIVER=dummy to run logic tests on a server, over SSH or in CI.No available video device usually means no display is attached to the session. mixer not initialized usually means no audio device.pygame.mixer.init() in a try/except pygame.error block so a missing sound card does not crash the app.convert() or convert_alpha() so blits skip format conversion.font.render() is costly, so re-render only when the text changes.set_at() and get_at() in Python are slow. Use surfarray with NumPy for bulk pixel work.group.draw(screen) and group.update() reduce Python overhead for many objects.pygame.SCALED.clock.tick(30) for a status panel uses far less CPU and power than an uncapped loop.So, what is Pygame? It is a lightweight, open-source Python library that gives you windows, graphics, sound, input and timing on top of SDL, and it is one of the fastest ways to turn Python code into something you can see and play with.
For embedded engineers, it is a practical tool for dashboards, simulators and prototypes on Linux-class boards, while the real-time work stays in firmware. Start with the example in this guide, change the speed and colors, add a second ball, and then connect a real sensor. That sequence builds the same skills you use in firmware: loops, timing, events and state.
Pygame is a free, open-source Python library for building 2D games and multimedia applications. It is built on top of SDL, so your Python code can create windows, draw graphics, play sounds and read keyboard, mouse and gamepad input on Windows, macOS and Linux. Beginners like it because a working game needs only a few dozen lines of code.
Pygame is a library, not a full game engine. It gives you the building blocks: windows, drawing, sound, input, timing and collision helpers. You write the game loop, physics, menus and level logic yourself. This makes Pygame excellent for understanding how games work, while engines such as Godot suit larger projects that need editors and 3D.
Open a terminal and run python3 -m pip install pygame (use py -m pip install pygame on Windows). Verify it with python3 -m pygame.examples.aliens, which opens a demo game. On Raspberry Pi OS, create a virtual environment first, or use sudo apt install python3-pygame, because system-wide pip installs are blocked on recent releases.
Pygame is good for 2D games, game jam entries, rapid prototypes, visual simulations and live dashboards. In embedded and IoT work, engineers use it on Raspberry Pi boards to display sensor data, build touchscreen panels and visualize robot behavior. It is less suited to 3D games or hard real-time control.
Yes. Pygame runs on Raspberry Pi OS and other Linux distributions. It works well for 2D interfaces, dashboards and simple games. Keep the resolution modest, convert images with convert() or convert_alpha(), and avoid per-pixel Python loops. Pygame is not suitable for microcontrollers such as STM32 or Arduino, which do not run a Linux-class operating system.
Pygame-CE (Community Edition) is a community-maintained fork of Pygame. Both use import pygame, so they cannot be installed together. Pygame-CE has faster release cycles and extra features, while the original pygame package remains widely used. Pick one per project, and pin its version in requirements.txt for repeatable builds.
Indian Institute of Embedded Systems – IIES