๐ŸŽฎ Pygame Zero Cheatsheet

Make games with Pygame Zero. Copy any example into the Editor and press โ–ถ Run.

๐Ÿš€ Getting started

A Pygame Zero game defines a draw() function (and usually update(dt)), then starts the game loop. In this editor you must import pgzrun and call pgzrun.go() at the end โ€” the same two lines you would add in Thonny.

import pgzrun

def draw():
    screen.fill("midnightblue")
    screen.draw.filled_circle((200, 150), 40, "orange")

def update(dt):
    pass            # move things here; dt = seconds since the last frame

pgzrun.go()         # starts the game โ€” keep this as the last line
๐Ÿ’ก In this editor the game fills the game area, so WIDTH and HEIGHT are ignored. Use screen.width and screen.height (or screen.bounds()) when you need the size. You do not import screen, Actor, keyboard, โ€ฆ โ€” they are ready to use, exactly like in real Pygame Zero.

๐Ÿ” The game loop: draw & update

The engine calls draw() to paint each frame and update(dt) to move things. dt is the seconds elapsed since the previous frame โ€” multiply speeds by it for smooth, frame-rate-independent motion.

draw()Paint the frame. Called every frame.
update()Update game state. Called every frame.
update(dt)Same, but given dt = seconds since last frame.
import pgzrun

x = 20

def update(dt):
    global x
    x += 120 * dt           # 120 pixels per second, any frame rate

def draw():
    screen.clear()
    screen.draw.filled_rect(Rect(x, 100, 60, 60), "tomato")

pgzrun.go()

๐Ÿ–Œ๏ธ Drawing on the screen

Draw shapes and fills through screen. Coordinates are in pixels with (0, 0) at the top-left, x to the right and y downward.

screen.clear()Clear the surface to black.
screen.fill(color)Fill the whole surface with a colour.
screen.fill(c, gcolor)Fill with a topโ†’bottom gradient.
screen.bounds()A Rect covering the whole surface.
screen.draw.line(a, b, color)Line between points a and b.
screen.draw.circle(pos, r, color)Circle outline.
screen.draw.filled_circle(pos, r, color)Filled circle.
screen.draw.rect(rect, color)Rectangle outline.
screen.draw.filled_rect(rect, color)Filled rectangle.

Colours can be names ("red"), hex ("#ff8800"), or tuples (r, g, b) / (r, g, b, a).

import pgzrun

def draw():
    screen.fill("navy", "black")           # gradient background
    screen.draw.line((0, 180), (400, 180), "white")
    screen.draw.circle((120, 90), 30, "cyan")
    screen.draw.filled_rect(Rect(200, 60, 80, 60), "gold")

pgzrun.go()

โœ๏ธ Text

Draw styled text with screen.draw.text. Position it with any one anchor (topleft, center, midbottom, โ€ฆ) or a plain (x, y).

screen.draw.text(s, (x, y), ...)Draw text s at a position.
fontsize=40Text size in pixels.
color="white"Text colour.
owidth, ocolorOutline width and colour.
shadow=(1,1), scolorDrop shadow offset and colour.
gcolor="blue"Vertical gradient from color to gcolor.
angle=15Rotate the text (degrees, anticlockwise).
import pgzrun

def draw():
    screen.fill("black")
    screen.draw.text("Score: 10", topleft=(10, 10), fontsize=30, color="white")
    screen.draw.text("WIN!", center=(200, 120), fontsize=70,
                     color="yellow", owidth=1, ocolor="red")

pgzrun.go()
๐Ÿ’ก Text uses the system font. A fontname option is accepted but ignored here, so your code still runs unchanged in Thonny.

๐Ÿงฑ Rect & ZRect

Rectangles store position and size and have handy anchor points you can read and write (writing one moves the rectangle). ZRect is the same but keeps decimals.

Rect(x, y, w, h)A rectangle at (x, y) of size w ร— h.
r.x, r.y, r.width, r.heightPosition and size.
r.left, r.right, r.top, r.bottomEdges.
r.center, r.centerx, r.centeryCentre point.
r.topleft, r.midbottom, โ€ฆCorner / mid-edge anchor points.
r.colliderect(other)True if two rects overlap.
r.collidepoint(x, y)True if a point is inside.
box = Rect(0, 0, 50, 50)
box.center = (200, 150)          # move so its centre is here
print(box.topleft)               # (175, 125)
print(box.colliderect(Rect(180, 130, 10, 10)))   # True

๐Ÿง Actors (sprites)

An Actor is an image you can move, rotate and fade. Upload an image in the File Manager (or use a bundled one like alien), then build an actor from its name.

Actor("alien")Make an actor from images/alien.png.
a.pos = (x, y)Move the actor (its anchor goes to pos).
a.x, a.y, a.left, a.center, โ€ฆPosition like a Rect.
a.angle = 45Rotation in degrees (anticlockwise).
a.opacity = 0.5Transparency, 0โ€“1.
a.image = "alien_hurt"Swap the picture.
a.draw()Draw the actor this frame.
a.distance_to(target)Distance to a point or actor.
a.angle_to(target)Angle to a point or actor.
a.colliderect(other) ยท a.collidepoint(p)Collision checks.
import pgzrun

alien = Actor("alien")
alien.pos = (100, 100)

def update(dt):
    alien.x += 100 * dt
    if alien.left > screen.width:
        alien.right = 0

def draw():
    screen.clear()
    alien.draw()

pgzrun.go()

โŒจ๏ธ Keyboard

Check which keys are held with keyboard, or react to presses with the on_key_down / on_key_up hooks.

keyboard.left / .right / .up / .downArrow keys (True while held).
keyboard.space ยท keyboard.aAny key by name.
keyboard[keys.A]Same, using the keys enum.
on_key_down(key)Called when a key goes down.
on_key_up(key)Called when a key is released.
import pgzrun

player = Rect(180, 130, 40, 40)

def update(dt):
    if keyboard.left:  player.x -= 200 * dt
    if keyboard.right: player.x += 200 * dt

def draw():
    screen.fill("black")
    screen.draw.filled_rect(player, "lime")

pgzrun.go()
๐Ÿ’ก Click the game once so it can hear the keyboard.

๐Ÿ–ฑ๏ธ Mouse

React to clicks and movement. pos is (x, y) in the game's coordinates; button is one of the mouse values.

on_mouse_down(pos)A mouse button was pressed at pos.
on_mouse_down(pos, button)Also tells you which button.
on_mouse_up(pos, button)A button was released.
on_mouse_move(pos, rel, buttons)The mouse moved.
mouse.LEFT / MIDDLE / RIGHTButton values.
import pgzrun

spots = []

def draw():
    screen.fill("black")
    for p in spots:
        screen.draw.filled_circle(p, 15, "gold")

def on_mouse_down(pos):
    spots.append(pos)

pgzrun.go()

โฐ Clock (timing)

Schedule functions to run later or repeatedly โ€” great for spawning enemies, countdowns and animations.

clock.schedule(fn, delay)Call fn once after delay seconds.
clock.schedule_unique(fn, delay)Same, replacing any pending call to fn.
clock.schedule_interval(fn, secs)Call fn every secs seconds.
clock.unschedule(fn)Cancel a scheduled call.
import pgzrun

count = 0

def tick():
    global count
    count += 1

def draw():
    screen.fill("black")
    screen.draw.text(str(count), center=(200, 120), fontsize=80, color="white")

clock.schedule_interval(tick, 1.0)   # once a second
pgzrun.go()

๐Ÿ”Š Sounds

Play short sound effects from the sounds/ area. The editor ships with eep and ding; upload your own .wav files in the File Manager.

sounds.ding.play()Play a sound once.
sounds.ding.play(3)Play and repeat it 3 more times.
sounds.ding.stop()Stop that sound.
sounds.ding.get_length()Length in seconds.
import pgzrun

def draw():
    screen.fill("teal")
    screen.draw.text("Click for a ding", center=(200, 120),
                     fontsize=34, color="white")

def on_mouse_down(pos):
    sounds.ding.play()

pgzrun.go()

๐ŸŽต Music

Background music plays one track at a time from the music/ area. The editor ships with spook4; upload your own .mp3 files too.

music.play(name)Play a track on a loop.
music.play_once(name)Play a track once.
music.queue(name)Play this track after the current one.
music.stop()Stop the music.
music.pause() ยท music.unpause()Pause / resume.
music.fadeout(secs)Fade to silence over secs seconds.
music.set_volume(v) ยท music.get_volume()Volume, 0โ€“1.
on_music_end()Called when a one-shot track finishes.
import pgzrun

def draw():
    screen.fill("indigo")
    screen.draw.text("Press P for music", center=(200, 120),
                     fontsize=34, color="white")

def on_key_down(key):
    if key == keys.P:
        music.play("spook4")

pgzrun.go()
๐Ÿ’ก Browsers only start audio after you interact with the page, so click the game (or press a key) before expecting sound.

๐Ÿ–ผ๏ธ Asset names

Images, sounds and music are looked up by name (no file extension, no folder). Names must be lowercase letters, numbers and underscores, starting with a letter โ€” e.g. alien, alien_hurt, level_1.

images.alienLoads images/alien.png (also .jpg, .gif).
sounds.dingLoads sounds/ding.wav (also .ogg).
music.play("spook4")Plays music/spook4.mp3 (also .ogg).
๐Ÿ’ก Same code, two homes: a game written here runs unchanged in Thonny after pip install pgzero and pgzrun game.py. For more, see the official Pygame Zero docs โ†—.