Pygame 标志

Pygame

组织
CodeAtCode
pygame

Use when building 2D games in Python with pygame - game loop and delta time, sprites and groups, collision detection, drawing and surfaces, events and input, sound and fonts, camera, or performance optimization

概览

发布者CodeAtCode
代码仓库oss-ai-skills
技能名称pygame
星标数
30
复刻数
3
附带文件
3
许可协议GPL-3.0
链接
  • Markdown 格式的指令

    模型按需加载的 SKILL.md 文件,因此只有在请求确实匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 3 个随附文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 CodeAtCode 发布于 GitHub。请在安装前查看源内容。

安装

在 TypingMind 中安装 Pygame AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/CodeAtCode/oss-ai-skills/tree/master/frameworks/pygame
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/CodeAtCode/oss-ai-skills.git /tmp/oss-ai-skills
mkdir -p .claude/skills
cp -r /tmp/oss-ai-skills/frameworks/pygame .claude/skills/pygame
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Pygame,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Pygame。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Pygame 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会获取指令,因此未使用的技能不会产生额外费用。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Objective: Use this skill to prevent game loop instability, visual stuttering, and collision bugs in 2D games by enforcing delta-time discipline, fixed timesteps, and performance-conscious rendering.

Pygame

Python game development library.

Quick Start

bash
pip install pygame-ce  # Community Edition - actively maintained
python
import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
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))
    # Draw game objects
    pygame.display.flip()
    
    clock.tick(60)  # Limit to 60 FPS

pygame.quit()

For full API reference, see https://www.pygame.org/docs/ref/

Game Loop Architecture

The Non-Negotiable Discipline

A game loop has three phases: handle events → update simulation → render. Never derive motion from raw frame counts—always use delta time (dt).

Critical pattern: dt = clock.tick(FPS) / 1000 without clamping lets a stalled frame (e.g., system suspend, GC pause) teleport entities through walls. A 5-second stall at 60 FPS yields dt = 5.0, moving a 100 px/s entity 500 pixels in one update.

Do always clamp max_dt because a stalled frame (system suspend, GC pause) can teleport entities through walls if delta time is unbounded.

Fixed Timestep with Render Interpolation

The robust pattern: fixed physics steps, interpolated rendering for smoothness.

python
class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((800, 600))
        self.clock = pygame.time.Clock()
        self.running = True
        
        # Fixed timestep: physics always runs at 60 Hz
        self.fixed_dt = 1/60
        self.accumulator = 0.0
        self.max_dt = 1/10  # Clamp: ignore frames > 100ms (prevents tunneling)
    
    def run(self):
        while self.running:
            # Calculate delta time (seconds)
            dt = self.clock.tick(60) / 1000.0
            
            # Clamp to prevent spiral of death on stalled frames
            if dt > self.max_dt:
                dt = self.max_dt
            
            # Handle events
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
            
            # Fixed timestep update loop
            self.accumulator += dt
            while self.accumulator >= self.fixed_dt:
                self.update(self.fixed_dt)
                self.accumulator -= self.fixed_dt
            
            # Render with interpolation (smooths visual updates)
            interp = self.accumulator / self.fixed_dt
            self.render(interp)
        
        pygame.quit()
    
    def update(self, dt):
        """Physics and game logic at fixed 60 Hz"""
        # Movement: position += velocity * dt
        # Collision detection
        # AI decisions
        pass
    
    def render(self, interp):
        """Render with interpolation factor (0.0 to 1.0)"""
        self.screen.fill((0, 0, 0))
        
        # Interpolate positions for smooth rendering between physics steps
        for sprite in self.all_sprites:
            render_x = sprite.prev_x + (sprite.x - sprite.prev_x) * interp
            render_y = sprite.prev_y + (sprite.y - sprite.prev_y) * interp
            self.screen.blit(sprite.image, (render_x, render_y))
        
        pygame.display.flip()

Why this matters:

  • Consistent physics regardless of framerate drops
  • Deterministic simulation (network games, replays)
  • No "spiral of death" when frame time exceeds update time
  • Interpolation makes rendering smooth even when physics runs slower

Variable delta alternative (simpler, less precise):

python
# Simpler: variable timestep (acceptable for non-critical physics)
dt = self.clock.tick(60) / 1000.0
if dt > 0.1:  # Clamp to 100ms max
    dt = 0.1
self.update(dt)

Update/Draw/Collision Placement

python
def update(self, dt):
    # 1. Handle input (keyboard/mouse state)
    # 2. Update positions: pos += vel * dt
    # 3. Update animations (frame += dt * fps)
    # 4. Collision detection (after positions change)
    # 5. Game logic (score, state transitions)

def render(self, interp):
    # 1. Clear screen (fill or restore background)
    # 2. Draw static background (once, cached)
    # 3. Draw sprites/groups (sorted by z-order if needed)
    # 4. Draw UI overlay (HUD, score, health)
    # 5. Flip display

Sprite and Group Cost

Why Groups Are the Bottleneck

Group.update() calls .update() on every sprite each frame. For 1000 sprites, that's 1000 function calls. The cost is not the group—it's the work each sprite does.

Profile before optimizing:

python
import time

# Measure update cost
start = time.perf_counter()
all_sprites.update()
update_ms = (time.perf_counter() - start) * 1000

# Measure draw cost
start = time.perf_counter()
all_sprites.draw(screen)
draw_ms = (time.perf_counter() - start) * 1000

print(f"Update: {update_ms:.2f}ms, Draw: {draw_ms:.2f}ms")
# Budget: < 8ms update, < 8ms draw for 60 FPS headroom

Group Types and Their Costs

Group TypeCostUse When
GroupO(n) update, O(n) drawMost cases, sprites with .update()
GroupSingleO(1) accessSingle entity (player, boss)
LayeredUpdatesO(n) + layer sortingZ-order rendering, depth sorting
Sprite (manual)O(1)Single sprite, no group overhead
python
# GroupSingle: single entity, faster access
player = pygame.sprite.GroupSingle()
player.add(PlayerSprite())
player.update()  # Updates only the single sprite
player.draw(screen)

# LayeredUpdates: control draw order by layer
layers = pygame.sprite.LayeredUpdates()
layers.add(background, layers=[0])  # Draw first
layers.add(player, layers=[1])
layers.add(enemies, layers=[2])
layers.add(particles, layers=[3])  # Draw last (on top)
layers.change_layer(player, 5)  # Move player to top

When to Draw Manually

Skip groups when:

  • Sprites don't need .update() (static background tiles)
  • You need custom draw order per frame
  • You're using dirty rect optimization
python
# Manual draw: skip group overhead for static tiles
for tile in background_tiles:
    screen.blit(tile.image, tile.rect)  # No update() call

# Custom z-order: sort before draw
sprites_to_draw = sorted(all_sprites, key=lambda s: s.z_index)
for sprite in sprites_to_draw:
    screen.blit(sprite.image, sprite.rect)

GroupCollide vs Manual Collision

GroupCollide returns a dict keyed by sprite—expensive if you only need "did anything hit?"

python
# Expensive: groupcollide builds full dict
hits = pygame.sprite.groupcollide(bullets, enemies, False, False)
# hits = {bullet1: [enemy1, enemy2], bullet2: [enemy3], ...}

# Cheaper: spritecollide, short-circuit on first hit
for bullet in bullets:
    if pygame.sprite.spritecollideany(bullet, enemies):
        bullet.kill()
        break  # Stop checking

Collision Detection Decision Guide

Collision Strategies by Cost

StrategyCostUse When
AABB (rect.colliderect)O(1), fastMost games, initial filter
spritecollide (rect)O(n) per spriteSmall sprite counts (< 100)
groupcollide (dict)O(n×m)Need full collision map
Mask (collide_mask)O(pixels)Pixel-perfect needed
Circle (collide_circle)O(1), approximateRound sprites, medium precision

The Failure Modes

Tunneling at high velocity: A bullet moving 200 px/frame skips a 32-pixel enemy entirely.

Fix: Use continuous collision (swept AABB) or subdivide high-velocity updates.

python
# Subdivide to prevent tunneling
def update_high_velocity(bullet, dt, subdivisions=4):
    sub_dt = dt / subdivisions
    for _ in range(subdivisions):
        bullet.x += bullet.vx * sub_dt
        bullet.y += bullet.vy * sub_dt
        if pygame.sprite.spritecollideany(bullet, enemies):
            return True  # Collision detected
    return False

O(n²) broad-phase: 500 bullets × 500 enemies = 250,000 checks per frame.

Fix: AABB pre-filter with spatial partitioning.

python
# AABB pre-filter: reject distant sprites first
def collide_with_filter(bullet, enemies):
    # Fast bounding box check
    for enemy in enemies:
        if not bullet.rect.colliderect(enemy.rect):
            continue  # Skip expensive mask check
        
        # Only now do the expensive check
        if bullet.mask and enemy.mask:
            offset = (enemy.rect.x - bullet.rect.x, 
                     enemy.rect.y - bullet.rect.y)
            if bullet.mask.overlap(enemy.mask, offset):
                return True
    return False

# For large counts: use a quadtree or grid
# (See references/performance.md for spatial partitioning)

Mask vs Colorkey vs Rect

python
# Rect collision (fastest, least precise)
if player.rect.colliderect(enemy.rect):
    handle_collision()

# Colorkey: simple transparency, no pixel-perfect
image = pygame.image.load("sprite.png").convert()
image.set_colorkey((0, 0, 0))  # Black is transparent

# Mask: pixel-perfect (slow, use as second filter)
mask = pygame.mask.from_surface(image)  # Expensive, do once at load
# Store mask on sprite
sprite.mask = mask

# Collision: rect first (AABB), then mask
if sprite1.rect.colliderect(sprite2.rect):
    offset = (sprite2.rect.x - sprite1.rect.x, 
              sprite2.rect.y - sprite1.rect.y)
    if sprite1.mask.overlap(sprite2.mask, offset):
        handle_pixel_perfect_collision()

Rule: Always use AABB as first filter. Mask collision is 10-100× slower than rect.

Surface and Blit Pitfalls

Per-Frame Allocation

Never allocate Surfaces inside the game loop.

python
# Bad: Allocates new surface every frame (triggers GC, causes stutter)
while running:
    text = font.render(score_text, True, WHITE)
    screen.blit(text, (10, 10))

# Good: Cache the surface, update only when score changes
class HUD:
    def __init__(self):
        self.score_font = pygame.font.Font(None, 36)
        self.score_surface = None
        self.score = 0
    
    def set_score(self, value):
        if value != self.score:
            self.score = value
            self.score_surface = self.score_font.render(
                str(value), True, WHITE
            )
    
    def draw(self, screen):
        if self.score_surface:
            screen.blit(self.score_surface, (10, 10))

convert() and convert_alpha() at Load Time

python
# Bad: Converts on every load (or worse, every frame)
image = pygame.image.load("sprite.png").convert()

# Good: Load once at startup, convert immediately
class AssetManager:
    def __init__(self):
        self.player = pygame.image.load("player.png").convert_alpha()
        self.tile = pygame.image.load("tile.png").convert()
        # Opaque → convert(), transparent → convert_alpha()

Do call convert()/convert_alpha() at load time only because converting surfaces inside the game loop triggers garbage collection and causes stutter.

Rule of thumb:

  • convert(): Opaque images, no transparency (20-30% faster blit)
  • convert_alpha(): Images with alpha channels or colorkeys

set_alpha vs Alpha Channel

python
# Bad: set_alpha on many sprites (slow, recomputes every blit)
for sprite in hundreds_of_sprites:
    sprite.image.set_alpha(128)

# Good: Use alpha channel in the image itself (precomputed)
# Load with transparency already baked in
sprite = pygame.image.load("fading.png").convert_alpha()

Rule: set_alpha() on a Surface is slower than having the alpha channel in the image data. Pre-render semi-transparent surfaces once.

blit vs blits Batching

python
# Bad: Multiple individual blit calls
for sprite in sprites:
    screen.blit(sprite.image, sprite.rect)

# Good: Batched blits (single call, faster)
screen.blits([(s.image, s.rect) for s in sprites])

# Even better: pre-compute the list
blit_list = [(s.image, s.rect) for s in sprites]
screen.blits(blit_list)

Rule: blits() is 10-30% faster than individual blit() calls for large sprite counts.

When Not to Use Pygame

Browser-Targeted Games

Problem: Pygbag (pygame-to-WebAssembly) has limitations:

  • Large binary size (~10MB+ initial load)
  • Input latency in browser
  • No access to native APIs (file system, notifications)
  • Mobile browser performance issues

Alternative: Native JS/TypeScript game engines (Phaser, Babylon.js) or Unity/Godot export to WebGL.

Hardware-Accelerated 3D or Heavy 2D Sprite Counts

Problem: Pygame uses software rendering (SDL2 software renderer by default). Even with HWSURFACE, it's not a full 3D pipeline.

Symptoms:

  • 1000 moving sprites at 60 FPS

  • Need for 3D transformations (rotation in 3D space, perspective)
  • Shader effects (bloom, depth of field)

Alternative:

  • 2D: Godot (GDScript, built-in sprite batching)
  • 3D: Panda3D, Ursina, or OpenGL/DirectX directly
  • High-performance 2D: Pyglet (OpenGL-backed)

Projects Needing a Retained-Mode Scene Graph

Problem: Pygame is immediate-mode. You redraw everything every frame. No scene graph, no object retention.

Symptoms:

  • Complex UI with nested widgets
  • Need for editor-time scene composition
  • Undo/redo history of scene changes

Alternative: Godot (built-in scene system), Unity, or a retained-mode UI library (Dear PyGui for tools).

Games That Must Ship on Mobile

Problem: Pygame has no official mobile support. Pygbag targets web, not native mobile.

Symptoms:

  • Need iOS/Android app store distribution
  • Need native mobile features (push notifications, in-app purchases)
  • Need touch-optimized input handling

Alternative: Godot, Unity, or Flutter with game plugins.

Deep Dives

Load these reference files on demand for detailed implementations:

  • Drawing & Surfaces: references/drawing-surfaces.md — Colors, shapes, surface operations, transforms
  • Performance Optimization: references/performance.md — Image conversion, RLEACCEL, batched blits, dirty rects, pre-rendered surfaces
  • Sprites, Camera & UI: references/sprites-camera-ui.md — Sprite classes, groups, camera implementation, button UI elements

References

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Pygame AI 技能有什么作用?

Use when building 2D games in Python with pygame - game loop and delta time, sprites and groups, collision detection, drawing and surfaces, events and input, sound and fonts, camera, or performance optimization

为什么在 TypingMind 中使用 Pygame?

因为您只需安装一次,就能搭配任何模型使用。Pygame 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型,甚至可以在聊天中途切换模型,而不会影响技能正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Pygame?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/CodeAtCode/oss-ai-skills/tree/master/frameworks/pygame。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Pygame?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Pygame 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以搭配 Pygame 使用,包括 GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等,都可在 TypingMind 中使用您自己的 API 密钥接入。

Pygame AI 技能免费吗?

是的。该技能源自 CodeAtCode 在 GitHub 上以 GPL-3.0 许可证发布的项目。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇