go-game-dev
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGo 游戏开发专家 (Go Game Development Expert)
Go Game Development Expert
本技能为独立游戏开发者提供了一套使用 Go 语言构建专业级游戏的标准化工程流和深度决策模型。
This skill provides indie game developers with a standardized engineering workflow and in-depth decision-making model for building professional-grade games using the Go language.
✅ DOS (必须做的事)
✅ DOS (Things You Must Do)
- 热路径零分配 (Zero Allocation):
- 必须在 和
Update()循环复用切片(Draw())和对象池(slice = slice[:0]或泛型 Pool),确保每帧 GC 压力为零。sync.Pool
- 必须在
- 主线程封印 (Main Thread Binding):
- 所有的绘图逻辑(,
DrawImage)必须严格限制在NewImage主回调中执行,以确保运行在 OS 主线程。Game.Draw()
- 所有的绘图逻辑(
- 并发安全 (Concurrency Safety):
- 在 Goroutine 中处理 AI 或物理运算时,必须通过 回传结果到主循环,或者对共享状态加
Channel锁。sync.RWMutex
- 在 Goroutine 中处理 AI 或物理运算时,必须通过
- 显存手动管理 (Manual VRAM Disposal):
- 任何动态创建的 (非嵌入资源),必须在使用完毕后显式调用
ebiten.Image,不得依赖 GC。.Dispose()
- 任何动态创建的
- Zero Allocation on Hot Paths:
- Must reuse slices () and object pools (
slice = slice[:0]or generic Pool) in thesync.PoolandUpdate()loops to ensure zero GC pressure per frame.Draw()
- Must reuse slices (
- Main Thread Binding:
- All drawing logic (,
DrawImage) must be strictly restricted to theNewImagemain callback to ensure execution on the OS main thread.Game.Draw()
- All drawing logic (
- Concurrency Safety:
- When handling AI or physics calculations in Goroutines, results must be passed back to the main loop via , or shared states must be locked with
Channel.sync.RWMutex
- When handling AI or physics calculations in Goroutines, results must be passed back to the main loop via
- Manual VRAM Disposal:
- Any dynamically created (non-embedded resources) must explicitly call
ebiten.Imageafter use; do not rely on GC..Dispose()
- Any dynamically created
❌ DON'TS (绝对禁止的事)
❌ DON'TS (Things You Must Never Do)
- 🚫 禁止在循环中创建对象:
- 严禁在 中使用
Update(隐式接口转换)、fmt.Sprintf或make([]int)。&Vector{}
- 严禁在
- 🚫 禁止跨线程渲染:
- 绝不要在自己启动的 中调用任何图形 API。这会导致随机崩溃或
go func()。invalid memory address
- 绝不要在自己启动的
- 🚫 禁止并发读写 Map:
- 严禁在未加锁的情况下从多个 Goroutine 访问同一个 。Go 的 Map 竞态检测会直接 Panic 整个进程。
map
- 严禁在未加锁的情况下从多个 Goroutine 访问同一个
- 🚫 禁止 CGO 频繁交互:
- 避免在 循环中高频调用微小的 C 函数(如 Raylib 的单点绘图)。必须在 Go 侧批处理数据,一次性传递给 C 侧。
Update
- 避免在
- 🚫 Forbid Object Creation in Loops:
- Strictly prohibit using (implicit interface conversion),
fmt.Sprintformake([]int)in&Vector{}.Update
- Strictly prohibit using
- 🚫 Forbid Cross-Thread Rendering:
- Never call any graphics API in a self-started . This will cause random crashes or
go func()errors.invalid memory address
- Never call any graphics API in a self-started
- 🚫 Forbid Concurrent Map Reads/Writes:
- Strictly prohibit accessing the same from multiple Goroutines without locking. Go's Map race detector will directly panic the entire process.
map
- Strictly prohibit accessing the same
- 🚫 Forbid Frequent CGO Interactions:
- Avoid high-frequency calls to tiny C functions (such as Raylib's single-point drawing) in the loop. Data must be batched on the Go side and passed to the C side in one go.
Update
- Avoid high-frequency calls to tiny C functions (such as Raylib's single-point drawing) in the
Workflows
Workflows
Phase 1: 标准化工程脚手架 (Project Scaffolding)
Phase 1: Standardized Project Scaffolding
切勿将所有代码塞进。请遵循 Go 标准项目布局。main.go
- 目录结构:
- : 程序入口,仅负责初始化窗口和启动 Game Loop。
cmd/game/main.go - : 核心逻辑,对外部不可见。
internal/game/ - : 嵌入式文件系统 (
internal/assets/) 的对接口。embed.FS - : (可选) 存放 Component 和 System 定义。
internal/ecs/
- 动作:
go mod init <module>- 创建 并定义
internal/game/game.go结构体。Game - 在 中调用
cmd/game/main.go。ebiten.RunGame(&game.Game{})
Never stuff all code into. Follow the Go standard project layout.main.go
- Directory Structure:
- : Program entry point, only responsible for initializing the window and starting the Game Loop.
cmd/game/main.go - : Core logic, invisible to external parties.
internal/game/ - : Interface for embedded file system (
internal/assets/).embed.FS - : (Optional) Stores Component and System definitions.
internal/ecs/
- Actions:
go mod init <module>- Create and define the
internal/game/game.gostruct.Game - Call in
ebiten.RunGame(&game.Game{}).cmd/game/main.go
Phase 2: 场景管理状态机 (Scene Manager FSM)
Phase 2: Scene Manager FSM
游戏不是一个大循环,而是一系列场景的切换(Logo -> Menu -> Play -> Over)。
- 模式:
- 定义 接口:必须包含
Scene和Update() error。Draw(screen *ebiten.Image) - 在 结构体中持有
Game。currentScene Scene
- 定义
- 动作:
- 实现 ,提供
SceneManager方法。SwitchTo(Scene) - 确保 只是一层代理:
Game.Update()。return g.currentScene.Update() - 实现第一个 并挂载。
TitleScene
- 实现
A game is not a single big loop, but a series of scene switches (Logo -> Menu -> Play -> Over).
- Pattern:
- Define the interface: Must include
SceneandUpdate() error.Draw(screen *ebiten.Image) - Hold in the
currentScene Scenestruct.Game
- Define the
- Actions:
- Implement and provide the
SceneManagermethod.SwitchTo(Scene) - Ensure is just a proxy:
Game.Update().return g.currentScene.Update() - Implement the first and mount it.
TitleScene
- Implement
Phase 3: 数据导向实体设计 (Data-Oriented Entity Design)
Phase 3: Data-Oriented Entity Design
随着实体数量增加,OOP 继承树会成为性能瓶颈。
- 策略:
- 少量实体 (<500): 使用 组合模式 (Composition)。定义 结构体,内嵌
GameObject和*Sprite。*Position - 海量实体 (>1000): 必须上 ECS (Entity Component System)。推荐使用 或
donburi库。arche
- 少量实体 (<500): 使用 组合模式 (Composition)。定义
- 动作:
- 定义 接口或结构体数据。
Component - 实现 (如
System),只遍历拥有MovementSystem组件的实体。Velocity
- 定义
As the number of entities increases, OOP inheritance trees become performance bottlenecks.
- Strategies:
- Small number of entities (<500): Use Composition Pattern. Define the struct, embedding
GameObjectand*Sprite.*Position - Large number of entities (>1000): Must use ECS (Entity Component System). Recommended libraries are or
donburi.arche
- Small number of entities (<500): Use Composition Pattern. Define the
- Actions:
- Define interfaces or struct data.
Component - Implement (such as
System), only iterating over entities with theMovementSystemcomponent.Velocity
- Define
Phase 4: 输入与资源抽象 (Input & Asset Abstraction)
Phase 4: Input & Asset Abstraction
不要直接在逻辑代码里写。ebiten.IsKeyPressed(ebiten.KeySpace)
- 输入映射 (Input Mapping):
- 创建 ,将物理按键(Space, A, GamepadA)映射为逻辑意图(
InputSystem,ActionJump)。ActionShoot - 逻辑层只判断 。
input.IsActionJustPressed(ActionJump)
- 创建
- 资源池化:
- 建立全局(或场景级)。
AssetLoader - 使用 或普通
sync.Map缓存加载过的图片,避免重复 I/O。map
- 建立全局(或场景级)
Don't directly writein logic code.ebiten.IsKeyPressed(ebiten.KeySpace)
- Input Mapping:
- Create to map physical keys (Space, A, GamepadA) to logical intents (
InputSystem,ActionJump).ActionShoot - The logic layer only checks .
input.IsActionJustPressed(ActionJump)
- Create
- Resource Pooling:
- Establish a global (or scene-level) .
AssetLoader - Use or ordinary
sync.Mapto cache loaded images to avoid repeated I/O.map
- Establish a global (or scene-level)
Phase 5: 构建自动化 (Build Automation)
Phase 5: Build Automation
本地能跑不代表能发给玩家。
- 动作:
- 配置 实现代码热重载(虽然对图形窗口支持有限,但对逻辑调试有用)。
.air.toml - 编写 或
Makefile,固化构建参数:scripts/build.py- Windows:
GOOS=windows GOARCH=amd64 go build -ldflags="-H windowsgui -s -w" - Web:
GOOS=js GOARCH=wasm go build -o game.wasm
- Windows:
- 配置
Working locally doesn't mean it can be distributed to players.
- Actions:
- Configure to implement code hot reloading (support for graphical windows is limited, but useful for logic debugging).
.air.toml - Write or
Makefileto formalize build parameters:scripts/build.py- Windows:
GOOS=windows GOARCH=amd64 go build -ldflags="-H windowsgui -s -w" - Web:
GOOS=js GOARCH=wasm go build -o game.wasm
- Windows:
- Configure
Bundled Resources
Bundled Resources
- References:
- : Ebitengine 深度设计模式、性能陷阱与优化建议。
references/ebitengine_patterns.md - : 视觉特效指南 (Screen Shake, Shaders, Particles)。
references/vfx_guide.md - : Steam, Itch.io 及移动端商店的官方发布规则、编译参数与审核指南。
references/publishing.md - : 卡牌游戏工程化指南 (手牌算法, 数据结构, 状态机)。
references/genre_cardgame.md - : 模拟经营架构通识 (区块网格, 资源流图, 确定性 Tick)。
references/genre_simulation.md
- Scripts:
- : 一键式多平台交叉编译自动化工具(支持 Wasm, Windows, Linux, macOS)。
scripts/build_all.py
- References:
- : Ebitengine in-depth design patterns, performance pitfalls, and optimization suggestions.
references/ebitengine_patterns.md - : Visual Effects Guide (Screen Shake, Shaders, Particles).
references/vfx_guide.md - : Official release rules, compilation parameters, and review guidelines for Steam, Itch.io, and mobile app stores.
references/publishing.md - : Engineering Guide for Card Games (Hand algorithms, data structures, state machines).
references/genre_cardgame.md - : General Architecture for Simulation Games (Block grids, resource flow diagrams, deterministic ticks).
references/genre_simulation.md
- Scripts:
- : One-click cross-platform cross-compilation automation tool (supports Wasm, Windows, Linux, macOS).
scripts/build_all.py