pygame Core
Build the foundation of a pygame game in Python: the main loop, delta-time
movement, drawing with Surface/Rect, input, and Sprite/Group management.
Targets pygame-ce 2.5.8 (the actively maintained community fork; same
import pygame), which supports Python 3.10–3.15.
When to use
- Use when starting a pygame game, fixing the loop, frame-rate-dependent speed,
input handling, blitting, or sprite/group collision.
- Use when code does
import pygame and the project depends on pygame-ce
(or pygame).
When not to use: Python language questions unrelated to pygame. 3D rendering
(pygame is 2D). For cross-engine save/load use save-systems; for rebindable input
architecture see input-systems.
Core workflow
- Install pygame-ce, not legacy pygame.
pip install pygame-ce — it's the
maintained fork and imports as pygame. Don't install both in one environment.
- Init and open a window.
pygame.init(), screen = pygame.display.set_mode((w, h)), clock = pygame.time.Clock().
- Run one loop: events → update → draw → flip. Pump the event queue every
frame (
for event in pygame.event.get()), update state, redraw, then
pygame.display.flip().
- Make it frame-rate independent. Get
dt = clock.tick(60) / 1000 (seconds)
and scale all motion by dt. Keep positions as floats; blit at integer rects.
- Handle input two ways: event-based (
KEYDOWN/MOUSEBUTTONDOWN, for discrete
actions) and polled (pygame.key.get_pressed(), for held movement).
- Organise objects with
Sprite + Group. Subclass pygame.sprite.Sprite
with image/rect; group.update(dt) and group.draw(screen) handle the
batch. Run it and watch the window before assuming it works.
Patterns
1. Minimal game loop (the skeleton)
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
running = True
while running:
dt = clock.tick(60) / 1000 # cap at 60 FPS; dt = seconds since last frame
for event in pygame.event.get(): # MUST drain the queue or the OS thinks it hung
if event.type == pygame.QUIT:
running = False
# update game state here, scaled by dt ...
screen.fill((18, 18, 28)) # clear each frame
# draw everything here ...
pygame.display.flip() # present the frame
pygame.quit()
2. Delta-time movement (frame-rate independent)
from pygame.math import Vector2
pos = Vector2(100, 100) # keep position as floats
speed = 220 # PIXELS PER SECOND, not per frame
# inside the loop, after computing dt:
keys = pygame.key.get_pressed()
direction = Vector2(
keys[pygame.K_RIGHT] - keys[pygame.K_LEFT],
keys[pygame.K_DOWN] - keys[pygame.K_UP],
)
if direction.length_squared() > 0:
direction = direction.normalize() # equal speed on diagonals
pos += direction * speed * dt # RIGHT: dt-scaled
screen.blit(player_img, (round(pos.x), round(pos.y))) # blit at integer pixels
3. Input: events vs polling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN: # discrete press: jump, menu, pause
if event.key == pygame.K_SPACE:
jump()
elif event.key == pygame.K_ESCAPE:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
shoot_at(event.pos) # event.pos = (x, y)
# Polled state (read once per frame) for continuous/held input:
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
move_left(dt)
4. A Sprite subclass + a Group
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
# convert() once at load makes blits much faster; _alpha keeps transparency.
self.image = pygame.image.load("player.png").convert_alpha()
self.rect = self.image.get_rect(center=(x, y))
self.pos = pygame.math.Vector2(self.rect.center)
self.speed = 240
def update(self, dt): # Group.update(dt) calls this per sprite
keys = pygame.key.get_pressed()
self.pos.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * self.speed * dt
self.rect.center = (round(self.pos.x), round(self.pos.y))
all_sprites = pygame.sprite.Group()
all_sprites.add(Player(400, 300))
# in the loop:
all_sprites.update(dt) # calls each sprite's update(dt)
all_sprites.draw(screen) # blits each sprite at its rect
5. Collision detection
# Sprite vs group: e.g. player picking up coins (True = remove collided coins).
collected = pygame.sprite.spritecollide(player, coins, dokill=True)
score += len(collected)
# Group vs group: bullets vs enemies (kill both on hit).
hits = pygame.sprite.groupcollide(bullets, enemies, True, True)
# Plain rect overlap (no sprites needed):
if player.rect.colliderect(door_rect):
open_door()
Pitfalls
- Window freezes / "not responding" → you didn't pump the event queue. Call
pygame.event.get() (or pygame.event.pump()) every frame.
- Speed differs on faster machines → you moved by a fixed amount per frame.
Scale by
dt = clock.tick(fps) / 1000 and use pixels-per-second values.
- Sub-pixel movement snaps/jitters →
rect coordinates are integers; store the
true position as a Vector2 of floats and assign rect.center = round(...) each
frame. In pygame-ce you can instead use a float rect: image.get_frect(...) returns
a pygame.FRect, which sprite groups and collision functions accept like a Rect.
- Objects jump or tunnel through walls after the window was dragged or the game
paused in a debugger → the next
clock.tick() returns the whole stall as one huge
dt. Clamp it before use, e.g. dt = min(clock.tick(60) / 1000, 0.05).
ValueError: Can't normalize Vector of length zero → Vector2.normalize() was
called with no keys held. Check length_squared() > 0 first, as in Pattern 2.
- Blits are slow / framerate drops → call
.convert() (opaque) or
.convert_alpha() (transparent) on loaded images once; un-converted surfaces blit
far slower.
- Nothing appears → you forgot
pygame.display.flip() (or update()), or you
drew before screen.fill(...) so it was cleared away.
- Wrong draw order → pygame uses painter's order; later blits cover earlier ones.
Draw background first, sprites last.
pip install pygame got the old one → for the maintained fork use
pip install pygame-ce; having both installed causes import conflicts.
- Diagonal movement is faster → normalise the direction vector before scaling by
speed.
References
- For
Group variants (GroupSingle, LayeredUpdates for z-order), pixel-perfect
collision with mask, slicing a spritesheet, simple animation, sound/music, and
text rendering, read references/sprites-and-collision.md.
Related skills
love2d-core — the same loop concepts in LÖVE/Lua.
bevy-ecs — a heavier ECS engine when a project outgrows pygame.
input-systems / save-systems — engine-agnostic input and persistence.
platformer / roguelike — genre templates that pair with pygame.
1---2name: pygame-core3description: >4 Structure a pygame (pygame-ce) game in Python: the init/event/update/draw loop,5 delta-time movement, Surface/Rect blitting, keyboard/mouse input, and6 Sprite/Group management with collision. Use when building or debugging a pygame7 game — when the user mentions pygame, pygame-ce, the game loop, blit, Surface,8 Rect, sprite groups, or clock.tick. Targets pygame-ce.9metadata:10 source: https://skillmd.com/skills/junmystery/pygame-core11---1213# pygame Core1415Build the foundation of a pygame game in Python: the main loop, delta-time16movement, drawing with `Surface`/`Rect`, input, and `Sprite`/`Group` management.17Targets **pygame-ce 2.5.8** (the actively maintained community fork; same18`import pygame`), which supports Python 3.10–3.15.1920## When to use2122- Use when starting a pygame game, fixing the loop, frame-rate-dependent speed,23 input handling, blitting, or sprite/group collision.24- Use when code does `import pygame` and the project depends on `pygame-ce`25 (or `pygame`).2627**When *not* to use:** Python language questions unrelated to pygame. 3D rendering28(pygame is 2D). For cross-engine save/load use `save-systems`; for rebindable input29architecture see `input-systems`.3031## Core workflow32331. **Install pygame-ce, not legacy pygame.** `pip install pygame-ce` — it's the34 maintained fork and imports as `pygame`. Don't install both in one environment.352. **Init and open a window.** `pygame.init()`, `screen =36 pygame.display.set_mode((w, h))`, `clock = pygame.time.Clock()`.373. **Run one loop: events → update → draw → flip.** Pump the event queue every38 frame (`for event in pygame.event.get()`), update state, redraw, then39 `pygame.display.flip()`.404. **Make it frame-rate independent.** Get `dt = clock.tick(60) / 1000` (seconds)41 and scale all motion by `dt`. Keep positions as floats; blit at integer rects.425. **Handle input two ways:** event-based (`KEYDOWN`/`MOUSEBUTTONDOWN`, for discrete43 actions) and polled (`pygame.key.get_pressed()`, for held movement).446. **Organise objects with `Sprite` + `Group`.** Subclass `pygame.sprite.Sprite`45 with `image`/`rect`; `group.update(dt)` and `group.draw(screen)` handle the46 batch. Run it and watch the window before assuming it works.4748## Patterns4950### 1. Minimal game loop (the skeleton)5152```python53import pygame5455pygame.init()56screen = pygame.display.set_mode((800, 600))57pygame.display.set_caption("My Game")58clock = pygame.time.Clock()5960running = True61while running:62 dt = clock.tick(60) / 1000 # cap at 60 FPS; dt = seconds since last frame63 for event in pygame.event.get(): # MUST drain the queue or the OS thinks it hung64 if event.type == pygame.QUIT:65 running = False6667 # update game state here, scaled by dt ...6869 screen.fill((18, 18, 28)) # clear each frame70 # draw everything here ...71 pygame.display.flip() # present the frame7273pygame.quit()74```7576### 2. Delta-time movement (frame-rate independent)7778```python79from pygame.math import Vector28081pos = Vector2(100, 100) # keep position as floats82speed = 220 # PIXELS PER SECOND, not per frame8384# inside the loop, after computing dt:85keys = pygame.key.get_pressed()86direction = Vector2(87 keys[pygame.K_RIGHT] - keys[pygame.K_LEFT],88 keys[pygame.K_DOWN] - keys[pygame.K_UP],89)90if direction.length_squared() > 0:91 direction = direction.normalize() # equal speed on diagonals92pos += direction * speed * dt # RIGHT: dt-scaled93screen.blit(player_img, (round(pos.x), round(pos.y))) # blit at integer pixels94```9596### 3. Input: events vs polling9798```python99for event in pygame.event.get():100 if event.type == pygame.QUIT:101 running = False102 elif event.type == pygame.KEYDOWN: # discrete press: jump, menu, pause103 if event.key == pygame.K_SPACE:104 jump()105 elif event.key == pygame.K_ESCAPE:106 running = False107 elif event.type == pygame.MOUSEBUTTONDOWN:108 shoot_at(event.pos) # event.pos = (x, y)109110# Polled state (read once per frame) for continuous/held input:111keys = pygame.key.get_pressed()112if keys[pygame.K_a]:113 move_left(dt)114```115116### 4. A Sprite subclass + a Group117118```python119class Player(pygame.sprite.Sprite):120 def __init__(self, x, y):121 super().__init__()122 # convert() once at load makes blits much faster; _alpha keeps transparency.123 self.image = pygame.image.load("player.png").convert_alpha()124 self.rect = self.image.get_rect(center=(x, y))125 self.pos = pygame.math.Vector2(self.rect.center)126 self.speed = 240127128 def update(self, dt): # Group.update(dt) calls this per sprite129 keys = pygame.key.get_pressed()130 self.pos.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * self.speed * dt131 self.rect.center = (round(self.pos.x), round(self.pos.y))132133all_sprites = pygame.sprite.Group()134all_sprites.add(Player(400, 300))135136# in the loop:137all_sprites.update(dt) # calls each sprite's update(dt)138all_sprites.draw(screen) # blits each sprite at its rect139```140141### 5. Collision detection142143```python144# Sprite vs group: e.g. player picking up coins (True = remove collided coins).145collected = pygame.sprite.spritecollide(player, coins, dokill=True)146score += len(collected)147148# Group vs group: bullets vs enemies (kill both on hit).149hits = pygame.sprite.groupcollide(bullets, enemies, True, True)150151# Plain rect overlap (no sprites needed):152if player.rect.colliderect(door_rect):153 open_door()154```155156## Pitfalls157158- **Window freezes / "not responding"** → you didn't pump the event queue. Call159 `pygame.event.get()` (or `pygame.event.pump()`) every frame.160- **Speed differs on faster machines** → you moved by a fixed amount per frame.161 Scale by `dt = clock.tick(fps) / 1000` and use pixels-per-second values.162- **Sub-pixel movement snaps/jitters** → `rect` coordinates are integers; store the163 true position as a `Vector2` of floats and assign `rect.center = round(...)` each164 frame. In pygame-ce you can instead use a float rect: `image.get_frect(...)` returns165 a `pygame.FRect`, which sprite groups and collision functions accept like a `Rect`.166- **Objects jump or tunnel through walls after the window was dragged or the game167 paused in a debugger** → the next `clock.tick()` returns the whole stall as one huge168 `dt`. Clamp it before use, e.g. `dt = min(clock.tick(60) / 1000, 0.05)`.169- **`ValueError: Can't normalize Vector of length zero`** → `Vector2.normalize()` was170 called with no keys held. Check `length_squared() > 0` first, as in Pattern 2.171- **Blits are slow / framerate drops** → call `.convert()` (opaque) or172 `.convert_alpha()` (transparent) on loaded images once; un-converted surfaces blit173 far slower.174- **Nothing appears** → you forgot `pygame.display.flip()` (or `update()`), or you175 drew before `screen.fill(...)` so it was cleared away.176- **Wrong draw order** → pygame uses painter's order; later blits cover earlier ones.177 Draw background first, sprites last.178- **`pip install pygame` got the old one** → for the maintained fork use179 `pip install pygame-ce`; having both installed causes import conflicts.180- **Diagonal movement is faster** → normalise the direction vector before scaling by181 speed.182183## References184185- For `Group` variants (`GroupSingle`, `LayeredUpdates` for z-order), pixel-perfect186 collision with `mask`, slicing a spritesheet, simple animation, sound/music, and187 text rendering, read `references/sprites-and-collision.md`.188189## Related skills190191- `love2d-core` — the same loop concepts in LÖVE/Lua.192- `bevy-ecs` — a heavier ECS engine when a project outgrows pygame.193- `input-systems` / `save-systems` — engine-agnostic input and persistence.194- `platformer` / `roguelike` — genre templates that pair with pygame.