{"guides":[],"hints":[{"hint":"Which side decides where a modified client ends up?","lessonID":"gamedev.authoritative-server","nuance":"With directions the server applies its own speed cap, collision and bounds, so a hacked client can at most choose where to walk; a reported position would let the client decide the outcome."},{"hint":"The server has not applied some of the inputs yet; which ones still matter?","lessonID":"gamedev.client-prediction","nuance":"Inputs 4 to 8 are still in flight and the server will apply them; replaying them on top of the authoritative state predicts where the server will be and corrects only real disagreements, such as the closed door."},{"hint":"Compare the distance moved in one tick with how thick the wall and the bullet are together.","lessonID":"gamedev.collisions","nuance":"Discrete tests only check the positions at the end of each tick; if one tick of motion is longer than the overlap window, no checked position overlaps, so sub-steps or a sweep are required."},{"hint":"Compare how often each method runs on a 60 Hz and on a 120 Hz monitor.","lessonID":"gamedev.ebitengine-structure","nuance":"Update is called TPS times per second whatever the display, while Draw follows the refresh rate, so state changed in Draw advances faster on faster monitors."},{"hint":"Look at which element Remove moves into the freed slot.","lessonID":"gamedev.entity-components","nuance":"Remove copies the last element into the hole at an index the iterator has already passed, so the moved entity would not be visited on this tick."},{"hint":"Alpha is computed after the step loop finishes, from time that was too short for a whole step.","lessonID":"gamedev.fixed-timestep","nuance":"Leftover accumulator time is less than one step, so alpha only blends prev and curr for drawing; the physics always sees the fixed step and game rules keep reading curr."},{"hint":"Think about which number a test can assert reliably across Go releases.","lessonID":"gamedev.frame-budget","nuance":"Allocation rate drives how often GC cycles start and how much assist work the loop pays; an update that allocates nothing in steady state removes that pressure, and asserting exactly zero stays valid when releases change non-zero counts."},{"hint":"The press arrives after the floor is gone, not before the floor arrives.","lessonID":"gamedev.input-actions","nuance":"Buffering forgives a press that comes too early by remembering it until landing; coyote time forgives a press that comes too late by allowing a jump for a few ticks after leaving the floor."},{"hint":"Consider what a binary heap promises about entries that compare equal.","lessonID":"gamedev.pathfinding","nuance":"Admissibility guarantees an optimal cost, not a unique route, and a binary heap is not stable; only a total order such as f, then h, then push sequence fixes which equal-cost path wins."},{"hint":"Ask which code shares the sequence of values the cave consumes.","lessonID":"gamedev.procedural-generation","nuance":"The cave reads the next values of whatever stream it uses; if loot draws from the same stream, every later value moves. A stream derived per system keeps each sequence private, and math/rand/v2 has no global Seed anyway."},{"hint":"Picture the file if power fails halfway through the write.","lessonID":"gamedev.save-games","nuance":"On POSIX file systems rename swaps the directory entry in one step, so readers see the complete old save or the complete synced new one; writing in place truncates first and can leave a torn file."},{"hint":"The pair (3, 8) is found when object 3 queries and again when object 8 queries.","lessonID":"gamedev.spatial-hash","nuance":"Neighborhood queries are symmetric, so each pair appears from both objects; keeping only j > i checks it once and also drops the object itself, which every query returns."},{"hint":"Think about what resuming must restore, and which scene the stack updates.","lessonID":"gamedev.state-machines","nuance":"Only the top scene updates, so the world underneath is frozen while paused, and Pop returns to that same value with its state intact; Replace would discard it."},{"hint":"Compare how int() and math.Floor round -0.56.","lessonID":"gamedev.tilemaps-camera","nuance":"Go's float-to-int conversion discards the fraction, rounding toward zero, so negative positions land one tile too far right or down; math.Floor returns -1 and the bounds check rejects it."},{"hint":"Look at the value shown on the tick right after the cancel.","lessonID":"gamedev.tweening-animation","nuance":"Starting from the current value means the first eased step moves only a fraction away from where the panel already is; both alternatives teleport it to an end point first, which is the 37.5 to 75.0 jump in the program."},{"hint":"Compute the length of the vector (1, 1).","lessonID":"gamedev.vectors-movement","nuance":"The length of (1, 1) is the square root of 2, about 1.41, so an unnormalized diagonal gets 41% more acceleration and top speed than a single direction."}],"id":"gamedev","labs":[],"practice":{"bugs":[],"drills":[],"interviews":[],"quizzes":[],"reviewPairs":[],"reviewRounds":[]},"readings":[{"conceptTag":"gamedev.fixed-timestep","designGuide":{"cautions":["Interpolation adds one step of visual latency.","Teleports and angle wrap-around need special cases when blending."],"cost":"Two copies of the drawn state, an integer accumulator and a clock interface; the real cost is the discipline of never reading the blended state in game logic.","family":"gamedev","flow":["Read frame time","Clamp and accumulate","Step while acc >= step","Draw with alpha"],"ratings":[],"strengths":["Identical inputs produce identical simulations on any display.","Stalls degrade into bounded slow motion instead of a freeze."]},"hint":"Alpha is computed after the step loop finishes, from time that was too short for a whole step.","id":"gamedev.fixed-timestep","introduction":"A game loop runs on two clocks. The display hands you frames of uneven length; the simulation should advance in identical steps. Decoupling the two with an accumulator makes physics independent of the frame rate, makes every run reproducible, and turns a long stall into bounded slow motion instead of a frozen game.","nuance":"Leftover accumulator time is less than one step, so alpha only blends prev and curr for drawing; the physics always sees the fixed step and game rules keep reading curr.","objective":"Advance a simulation in fixed steps from variable frame times, draw it with an interpolation factor and cap catch-up work after a stall.","question":"In a fixed-timestep loop, what is the interpolation factor alpha used for?","references":["https://gafferongames.com/post/fix_your_timestep/","https://gameprogrammingpatterns.com/game-loop.html","https://pkg.go.dev/time#Since"],"reviewAnswer":"How far the frame lies between the last two steps","reviewPrompt":"What does alpha = acc / step mean?","sections":[{"body":"The obvious loop measures the time since the last frame and integrates with it: position += velocity * dt. That ties the physics to whatever the machine delivers. Integration error depends on step size, so the same jump reaches a different apex at 30, 60 and 144 frames per second. A 250 ms stall (a window drag, a long garbage-collection pause on a weak device, a breakpoint) becomes one giant step in which a fast object passes straight through a wall. And because no two runs see the same frame times, a timing bug cannot be replayed, a recorded input file cannot reproduce a match, and two machines running in lockstep drift apart. A fixed step gives every run the same sequence of identical updates; only how often you draw is left to the hardware.","code":"last := time.Now()\nfor running {\n\tnow := time.Now()\n\tdt := now.Sub(last).Seconds() // whatever the last frame happened to cost\n\tlast = now\n\tworld.Update(dt) // physics now depends on the frame rate\n\tworld.Draw()\n}","language":"go","title":"Why frame-sized steps break physics","walkthrough":"This fragment is the pattern to replace, not code to run. Every Update receives a different dt, so the same inputs produce different trajectories on different machines, and a single slow frame turns into a single large, unstable integration step."},{"body":"The worked program replays seven recorded frame durations through a scripted clock. Each frame adds its duration to an accumulator. While the accumulator holds at least one step, the loop saves the current state as the previous one, integrates one 10 ms step and subtracts the step. Whatever remains is shorter than a step and carries over to the next frame. Time stays in time.Duration, an integer count of nanoseconds, so the accumulator cannot drift the way repeated float additions of 0.016 do; floats appear only inside the physics and in the interpolation factor.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nconst (\n\tstep     = 10 * time.Millisecond  // fixed simulation step: 100 updates per second\n\tmaxFrame = 100 * time.Millisecond // never simulate more than this per frame\n\tspeed    = 50.0                   // units per second\n)\n\n// Clock is the only source of time the loop sees.\ntype Clock interface {\n\tNow() time.Duration\n}\n\n// scriptedClock replays recorded frame durations instead of reading the OS clock.\ntype scriptedClock struct {\n\tnow    time.Duration\n\tframes []time.Duration\n}\n\nfunc (c *scriptedClock) Now() time.Duration { return c.now }\n\nfunc (c *scriptedClock) Advance() bool {\n\tif len(c.frames) == 0 {\n\t\treturn false\n\t}\n\tc.now += c.frames[0]\n\tc.frames = c.frames[1:]\n\treturn true\n}\n\ntype State struct{ X float64 }\n\nfunc integrate(s State, dt time.Duration) State {\n\ts.X += speed * dt.Seconds()\n\treturn s\n}\n\ntype Loop struct {\n\tclock      Clock\n\tlast       time.Duration\n\tacc        time.Duration\n\tprev, curr State\n\tsteps      int\n\tdropped    time.Duration\n}\n\ntype Report struct {\n\tRaw, Used time.Duration\n\tSteps     int\n\tAlpha     float64\n\tDrawn     State\n}\n\nfunc (l *Loop) Frame() Report {\n\tnow := l.clock.Now()\n\tr := Report{Raw: now - l.last}\n\tl.last = now\n\tr.Used = min(r.Raw, maxFrame)\n\tl.dropped += r.Raw - r.Used\n\tl.acc += r.Used\n\tfor l.acc >= step {\n\t\tl.prev = l.curr\n\t\tl.curr = integrate(l.curr, step)\n\t\tl.acc -= step\n\t\tr.Steps++\n\t}\n\tl.steps += r.Steps\n\tr.Alpha = float64(l.acc) / float64(step)\n\tr.Drawn = State{X: l.prev.X + (l.curr.X-l.prev.X)*r.Alpha}\n\treturn r\n}\n\nfunc main() {\n\tms := func(v ...int) []time.Duration {\n\t\tout := make([]time.Duration, len(v))\n\t\tfor i, n := range v {\n\t\t\tout[i] = time.Duration(n) * time.Millisecond\n\t\t}\n\t\treturn out\n\t}\n\tclock := &scriptedClock{frames: ms(16, 16, 16, 33, 4, 250, 16)}\n\tloop := &Loop{clock: clock}\n\tfor n := 1; clock.Advance(); n++ {\n\t\tr := loop.Frame()\n\t\tdt := r.Raw.String()\n\t\tif r.Used != r.Raw {\n\t\t\tdt += \" clamped to \" + r.Used.String()\n\t\t}\n\t\tfmt.Printf(\"frame %d: %s, steps=%d alpha=%.2f draw x=%.2f\\n\", n, dt, r.Steps, r.Alpha, r.Drawn.X)\n\t}\n\tfmt.Printf(\"%d steps simulated %v; %v dropped of %v\\n\",\n\t\tloop.steps, time.Duration(loop.steps)*step, loop.dropped, clock.Now())\n}","language":"go","title":"Consume frame time in fixed steps","walkthrough":"Frame 1 brings 16 ms: one step runs and 6 ms stays in the accumulator, so alpha is 0.60. Frame 2 adds 16 ms to those 6 and runs two steps. Frame 5 lasts only 4 ms, so no step runs at all, yet the drawn position still moves from 3.55 to 3.75 because alpha grew. Frame 6 stalls for 250 ms; the loop clamps it to 100 ms, runs ten steps instead of twenty-five and records 150 ms as dropped. The last line reports 20 steps, 200 ms of simulated time, against 351 ms on the clock."},{"body":"After the step loop, the leftover time is a fraction of a step: alpha = accumulator / step, always at least 0 and below 1. Drawing prev + (curr - prev) * alpha shows where the object is at the moment of the frame, so motion looks smooth even when the frame rate and the step rate do not divide evenly. The price is one step of latency: every drawn x in the output equals 50 units per second times the time fed into the loop, minus one 10 ms step. At a 60 Hz step that is about 17 ms, which most games accept; some competitive games extrapolate forward instead and live with occasional overshoot. Interpolate only what is continuous. Positions and scales are safe; angles need shortest-arc blending so 350 to 10 degrees does not spin the long way round; a teleport, respawn or screen wrap must set prev equal to curr, or the sprite visibly slides across the map for one frame. Interpolation is purely visual: game rules, collisions and input handling always read curr, never the blend.","title":"Draw between the last two states"},{"body":"If one step costs more real time than it simulates, each frame owes more steps than the one before, each frame takes longer still, and the game locks up trying to catch up: the spiral of death. A milder version follows every stall, when hundreds of owed steps arrive at once. Clamping the frame time bounds the work: with maxFrame at 100 ms and a 10 ms step, no frame ever runs more than ten steps. The game slows down during an overload instead of freezing, and the Report value makes the dropped time visible so you can log it. Capping steps per frame works the same way. Pick the bound from measurements: if the slowest device you support spends a large share of the step length inside one Update, the fix is a cheaper step or a longer one, not a larger clamp. Lockstep multiplayer cannot drop time, because every peer must simulate every tick; there you slow the whole session down or resynchronize.","title":"Clamp catch-up work to avoid the spiral of death"},{"body":"The loop never calls time.Now; it asks a Clock. Production passes an adapter over the monotonic clock, tests pass a script of frame durations, and every timing edge case becomes a deterministic table row: a zero-length frame, a frame of exactly one step, a stall just above the clamp, a long run whose step count must equal the time fed in divided by the step. Assert on step counts and on curr, not only on the drawn value, because alpha can hide a missing or extra step. If you use Ebitengine, the outer loop already exists: the engine calls your Update at a fixed tick rate, sometimes zero and sometimes several times per frame, and Draw once per frame, as the next lesson shows. The accumulator here is the model of that behavior and the tool for headless servers, replays and simulations that run outside an engine.","code":"// monotonic adapts the OS clock to the Clock interface.\ntype monotonic struct{ start time.Time }\n\nfunc (m monotonic) Now() time.Duration { return time.Since(m.start) }\n\nfunc main() {\n\tloop := &Loop{clock: monotonic{start: time.Now()}}\n\tfor !quit() {\n\t\tr := loop.Frame()\n\t\trender(r.Drawn)\n\t}\n}","language":"go","title":"Inject the clock and test the loop","walkthrough":"Run this fragment in your own program; quit and render are placeholders for your window and drawing code. time.Now carries a monotonic clock reading and time.Since subtracts monotonic readings, so a wall-clock adjustment such as an NTP correction or a user changing the system time never yields a negative or enormous frame."}],"takeaway":"Advance the simulation only in fixed steps taken from an accumulator, draw prev blended toward curr by alpha, clamp the time fed into the loop, and inject the clock so every timing edge case becomes a reproducible test.","title":"Fix the timestep: an accumulator turns uneven frames into identical simulation steps","unitID":"gamedev-loop","wrongAnswers":["A variable dt to pass into the physics update","The number of steps to run in the next frame"]},{"conceptTag":"gamedev.ebitengine-structure","designGuide":{"cautions":["Any state change in Draw becomes a frame-rate bug.","Draw gets no interpolation factor; smooth high-refresh motion needs extra work."],"cost":"A strict split between Update and Draw plus a thin input adapter; little code, but the rule has to be enforced in review.","family":"gamedev","flow":["Layout sets logical size","Update advances one tick","Draw renders current state","Return Termination to quit"],"ratings":[],"strengths":["Game speed is identical on every display refresh rate.","Rules behind a plain Step function run headless in tests."]},"hint":"Compare how often each method runs on a 60 Hz and on a 120 Hz monitor.","id":"gamedev.ebitengine-structure","introduction":"Ebitengine runs the loop from the previous lesson for you. You implement three methods, Update, Draw and Layout, and the engine decides when to call each one. Getting that split right is the most important structural decision in an Ebitengine project: a single state change inside Draw makes the game run at a different speed on every monitor.","nuance":"Update is called TPS times per second whatever the display, while Draw follows the refresh rate, so state changed in Draw advances faster on faster monitors.","objective":"Structure an Ebitengine game so every state change happens in Update, Draw is a read-only view, and the rules run headless in tests.","question":"In an Ebitengine game, why must movement code live in Update rather than Draw?","references":["https://pkg.go.dev/github.com/hajimehoshi/ebiten/v2#Game","https://pkg.go.dev/github.com/hajimehoshi/ebiten/v2#RunGame","https://pkg.go.dev/github.com/hajimehoshi/ebiten/v2#SetTPS","https://ebitengine.org/en/tour/hello_world.html"],"reviewAnswer":"Only in Update, at a fixed number of ticks per second","reviewPrompt":"Where does game state change?","sections":[{"body":"ebiten.Game is an interface with three methods: Update() error, Draw(screen *ebiten.Image) and Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int). Update runs at a fixed tick rate, 60 ticks per second by default and adjustable with ebiten.SetTPS, and the documentation lets you treat the time between two Updates as exactly 1/TPS seconds, so you never measure time inside it. Draw runs once per rendered frame, and how often that happens depends on the display: on a 120 Hz monitor there are about two Draw calls per Update, and when frames are slow the engine may run several Updates before the next Draw. Layout receives the outside size of the window or screen and returns the logical screen size; Ebitengine scales the logical screen to fit, so returning a fixed 320 by 180 gives a pixel-art canvas at any window size. In the first frame Update is guaranteed to run at least once before Draw, so Update is also the natural place for lazy initialization.","title":"Three methods on two different clocks"},{"body":"The Ebitengine module is not available in this sandbox, so the program declares a Game interface with the same three methods and a Screen type that stands in for *ebiten.Image. The run function plays the engine: each frame it calls Layout, then Update as many times as the schedule says, then Draw once. Three schedules model the same 100 ms on a 60 Hz, a 120 Hz and a 30 Hz display. Drone moves in Update; DrawDrone moves in Draw. The last two runs exercise the three possible results of Update: nil continues, the Termination sentinel stops cleanly, and any other error stops the game and is returned to the caller.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n// Screen stands in for *ebiten.Image: Draw writes to it and nothing else.\ntype Screen struct {\n\tW, H int\n\tText string\n}\n\n// Game has the same three methods as ebiten.Game, with the headless Screen.\ntype Game interface {\n\tUpdate() error\n\tDraw(screen *Screen)\n\tLayout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int)\n}\n\n// Termination plays the role of ebiten.Termination: stop without an error.\nvar Termination = errors.New(\"regular termination\")\n\n// Drone changes state only in Update, one tick at a time.\ntype Drone struct {\n\tTick, X, Goal int\n}\n\nfunc (d *Drone) Update() error {\n\td.Tick++\n\td.X += 2\n\tif d.Goal > 0 && d.X >= d.Goal {\n\t\treturn Termination\n\t}\n\treturn nil\n}\n\nfunc (d *Drone) Draw(s *Screen) { s.Text = fmt.Sprintf(\"tick=%d x=%d\", d.Tick, d.X) }\n\nfunc (d *Drone) Layout(outsideWidth, outsideHeight int) (int, int) { return 320, 180 }\n\n// DrawDrone moves inside Draw, so its speed follows the display.\ntype DrawDrone struct{ Drone }\n\nfunc (d *DrawDrone) Update() error { d.Tick++; return nil }\n\nfunc (d *DrawDrone) Draw(s *Screen) {\n\td.X += 2\n\td.Drone.Draw(s)\n}\n\nvar errDiskFull = errors.New(\"disk full\")\n\n// Saver fails on its third tick, the way a real I/O error would surface.\ntype Saver struct{ Drone }\n\nfunc (s *Saver) Update() error {\n\ts.Tick++\n\tif s.Tick == 3 {\n\t\treturn fmt.Errorf(\"autosave: %w\", errDiskFull)\n\t}\n\treturn nil\n}\n\n// run is a headless stand-in for ebiten.RunGame. Each schedule entry is one\n// frame: Layout, then that many Update calls, then one Draw.\nfunc run(g Game, schedule []int) (frames, ticks int, screen Screen, err error) {\n\tfor _, updates := range schedule {\n\t\tscreen.W, screen.H = g.Layout(1920, 1080)\n\t\tfor range updates {\n\t\t\tticks++\n\t\t\tif err := g.Update(); err != nil {\n\t\t\t\tif errors.Is(err, Termination) {\n\t\t\t\t\treturn frames, ticks, screen, nil\n\t\t\t\t}\n\t\t\t\treturn frames, ticks, screen, err\n\t\t\t}\n\t\t}\n\t\tg.Draw(&screen)\n\t\tframes++\n\t}\n\treturn frames, ticks, screen, nil\n}\n\nfunc repeat(pattern []int, times int) []int {\n\tvar out []int\n\tfor range times {\n\t\tout = append(out, pattern...)\n\t}\n\treturn out\n}\n\nfunc main() {\n\tdisplays := []struct {\n\t\tname     string\n\t\tschedule []int\n\t}{\n\t\t{\"60 Hz\", repeat([]int{1}, 6)},\n\t\t{\"120 Hz\", repeat([]int{1, 0}, 6)},\n\t\t{\"30 Hz\", repeat([]int{2}, 3)},\n\t}\n\tfor _, d := range displays {\n\t\tframes, ticks, screen, _ := run(&Drone{}, d.schedule)\n\t\t_, _, drawn, _ := run(&DrawDrone{}, d.schedule)\n\t\tfmt.Printf(\"%-6s %2d frames, %d ticks: Update-driven %q, Draw-driven %q\\n\",\n\t\t\td.name, frames, ticks, screen.Text, drawn.Text)\n\t}\n\t_, ticks, screen, err := run(&Drone{Goal: 20}, repeat([]int{1}, 60))\n\tfmt.Printf(\"goal: Termination on tick %d, last frame %q at %dx%d, err=%v\\n\",\n\t\tticks, screen.Text, screen.W, screen.H, err)\n\t_, ticks, _, err = run(&Saver{}, repeat([]int{1}, 60))\n\tfmt.Printf(\"saver: stopped on tick %d, err=%v, disk full=%t\\n\", ticks, err, errors.Is(err, errDiskFull))\n}","language":"go","title":"A headless driver shows why logic belongs in Update","walkthrough":"Every display delivers six ticks, so Drone ends at x=12 each time although Draw ran 6, 12 or 3 times. DrawDrone moves 2 units per Draw and ends at 12, 24 and 6: on the 120 Hz display it literally runs twice as fast. The goal run returns Termination from its tenth Update; run maps it to a nil error the way ebiten.RunGame does, and the last drawn frame shows tick 9 because in this model the terminating tick is never drawn. Saver wraps a sentinel with %w, so the caller can still match it with errors.Is after the game stops."},{"body":"In your own module the same structure hosts on Ebitengine with a handful of calls. ebiten.RunGame blocks until the game ends and returns the error Update returned, or nil after ebiten.Termination. Window size and title are set before RunGame. Images are allocated once, outside Draw: creating an *ebiten.Image every frame puts texture allocation on the hottest path in the program. Draw positions the sprite through DrawImageOptions.GeoM, the transform applied while the source image is drawn onto the screen, and ebitenutil.DebugPrint writes a line of debug text in the corner.","code":"import (\n\t\"fmt\"\n\t\"image/color\"\n\t\"log\"\n\n\t\"github.com/hajimehoshi/ebiten/v2\"\n\t\"github.com/hajimehoshi/ebiten/v2/ebitenutil\"\n)\n\ntype Game struct {\n\ttick   int\n\tx      float64\n\tsprite *ebiten.Image // created once in main, never inside Draw\n}\n\nvar _ ebiten.Game = (*Game)(nil)\n\nfunc (g *Game) Update() error {\n\tif ebiten.IsKeyPressed(ebiten.KeyEscape) {\n\t\treturn ebiten.Termination // RunGame returns nil\n\t}\n\tg.tick++\n\tg.x += 2\n\tif g.x > 320 {\n\t\tg.x = -16\n\t}\n\treturn nil\n}\n\nfunc (g *Game) Draw(screen *ebiten.Image) {\n\tscreen.Fill(color.RGBA{0x10, 0x18, 0x20, 0xff})\n\top := &ebiten.DrawImageOptions{}\n\top.GeoM.Translate(g.x, 82)\n\tscreen.DrawImage(g.sprite, op)\n\tebitenutil.DebugPrint(screen, fmt.Sprintf(\"tick %d\", g.tick))\n}\n\nfunc (g *Game) Layout(outsideWidth, outsideHeight int) (int, int) {\n\treturn 320, 180 // logical pixels; Ebitengine scales them to the window\n}\n\nfunc main() {\n\tsprite := ebiten.NewImage(16, 16)\n\tsprite.Fill(color.RGBA{0x00, 0xad, 0xd8, 0xff})\n\tebiten.SetWindowSize(960, 540)\n\tebiten.SetWindowTitle(\"Drone\")\n\tif err := ebiten.RunGame(&Game{sprite: sprite}); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}","language":"go","title":"The real main, as a fragment","walkthrough":"Run this fragment in your own environment after adding github.com/hajimehoshi/ebiten/v2 to a module; it is not compiled here and its package clause is omitted. The var _ line proves at compile time that *Game satisfies ebiten.Game. Update returns ebiten.Termination when Escape is held, so RunGame returns nil, while a genuine failure would come back as an error and reach log.Fatal. Draw only reads g.x and g.tick, so it is correct no matter how many times per tick the engine calls it."},{"body":"Update is the only method that changes state, but the rules do not have to live in it. A thin Update that copies Ebitengine input into a plain struct and calls world.Step(input) keeps the rules in code that never imports the engine: tests call Step with scripted input thousands of times per second, a replay system feeds recorded input, and a server can run the same Step without a window. Draw follows the mirror rule: it reads the world and issues draw calls, but never advances timers, consumes input or spawns particles, because the number of Draw calls per tick varies. Animation is the usual slip: derive the frame from the tick counter instead of incrementing a counter in Draw.","code":"func (g *Game) Update() error {\n\tin := Input{\n\t\tLeft:  ebiten.IsKeyPressed(ebiten.KeyArrowLeft),\n\t\tRight: ebiten.IsKeyPressed(ebiten.KeyArrowRight),\n\t}\n\treturn g.world.Step(in) // plain Go below this line: no ebiten imports\n}\n\nfunc (g *Game) Draw(screen *ebiten.Image) {\n\tframe := g.world.Tick / 8 % 4 // animation derived from ticks, not counted here\n\tg.drawPlayer(screen, frame)\n}","language":"go","title":"Keep engine calls at the edge of Update","walkthrough":"This fragment belongs to the same program as the RunGame fragment and runs in your own environment. Input is a plain struct and world.Step is ordinary Go, so a test can build Input values directly. The animation frame is a pure function of world.Tick, so two Draw calls for the same tick show the same frame. The input lesson in this unit replaces the booleans with action bits and edge detection."},{"body":"Express every speed, cooldown and animation length in ticks and treat TPS as a design constant chosen once. ebiten.ActualTPS and ebiten.ActualFPS report measured rates for a debug overlay; game logic must not depend on them, because they fluctuate while the tick contract does not. Ebitengine does not hand Draw an interpolation factor, so at the default 60 TPS a 144 Hz display shows some ticks for two frames and others for three. Most 2D games accept that; a game that needs smoother motion can raise TPS or compute its own alpha from a monotonic clock as in the previous lesson. Passing ebiten.SyncWithFPS to SetTPS makes Update run once per frame, which brings back variable step lengths and every problem of the frame-sized loop. When you review an Ebitengine game, search Draw for assignments to game state: each one is a speed bug waiting for a faster monitor.","title":"Ticks, frames and what to measure"}],"takeaway":"Change state only in Update and measure it in ticks; make Draw a read-only view that is safe to call any number of times; return ebiten.Termination to quit cleanly; keep the rules behind a plain Step function so they run headless.","title":"Ebitengine's Game interface: Update advances ticks, Draw only reads, Layout fixes the screen","unitID":"gamedev-loop","wrongAnswers":["Draw runs on a background goroutine and would race","Update receives a delta time and Draw does not"]},{"conceptTag":"gamedev.vectors-movement","designGuide":{"cautions":["Changing TPS means converting every tuning constant.","Float results can differ across architectures through FMA fusion."],"cost":"A thirty-line type and the habit of thinking in ticks; lockstep multiplayer may additionally need fixed-point math.","family":"gamedev","flow":["Read raw direction","Normalize to unit length","Accelerate, then drag","Add velocity to position"],"ratings":[],"strengths":["Value methods chain cleanly and cannot alias shared state.","Per-tick constants give identical movement on every display."]},"hint":"Compute the length of the vector (1, 1).","id":"gamedev.vectors-movement","introduction":"Almost every line of 2D movement code adds, scales or measures a pair of numbers. A tiny vector type with value methods makes that code read like the math, rules out aliasing bugs and costs nothing measurable. Combined with fixed ticks, it lets you tune movement in units a designer can reason about: pixels per tick, and a drag factor applied once per tick.","nuance":"The length of (1, 1) is the square root of 2, about 1.41, so an unnormalized diagonal gets 41% more acceleration and top speed than a single direction.","objective":"Write a small value-semantics vector type and move a body with normalized input, per-tick acceleration and drag that behave the same on every display.","question":"Holding right and down adds (1, 1) times the acceleration to velocity. What goes wrong without normalizing?","references":["https://gafferongames.com/post/integration_basics/","https://pkg.go.dev/math#Hypot","https://go.dev/ref/spec#Floating_point_operators"],"reviewAnswer":"So diagonal movement is not about 41% faster","reviewPrompt":"Why normalize diagonal input?","sections":[{"body":"Vec2 is two float64 fields, small enough that copying it is cheap and usually stays in registers, and a copy can never be changed behind your back. Every method takes a Vec2 and returns a new one: a.Add(b) leaves a untouched, so b.Vel.Add(...).Scale(drag) reads as one expression without temporaries. Value semantics also make the zero value meaningful: Vec2{} is the origin and a valid 'no direction'. Length uses math.Hypot, which avoids needless overflow and underflow in the intermediate squares; when you only need to compare distances, compare squared lengths instead, as the collision lesson does. Do not use float vectors as map keys: two positions that print identically can differ in the last bit.","title":"Value methods for a two-float type"},{"body":"Holding right and down produces the raw direction (1, 1), whose length is about 1.41. Scaling that by an acceleration makes diagonal movement 41% faster than straight movement, a bug players notice within seconds. Normalize rescales the direction to length 1 and returns the zero vector when nothing is held, instead of dividing by zero and producing NaN. Each tick the body then adds normalized input times accel to its velocity, multiplies velocity by drag, snaps tiny speeds to zero and adds velocity to position. Updating velocity before position is semi-implicit Euler integration: as cheap as the naive order and much more stable for game physics.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\n// Vec2 is small and immutable in use: every method takes and returns values.\ntype Vec2 struct{ X, Y float64 }\n\nfunc (a Vec2) Add(b Vec2) Vec2      { return Vec2{a.X + b.X, a.Y + b.Y} }\nfunc (a Vec2) Scale(k float64) Vec2 { return Vec2{a.X * k, a.Y * k} }\nfunc (a Vec2) Len() float64         { return math.Hypot(a.X, a.Y) }\n\n// Normalize returns a unit vector, or the zero vector when there is no direction.\nfunc (a Vec2) Normalize() Vec2 {\n\tl := a.Len()\n\tif l == 0 {\n\t\treturn Vec2{}\n\t}\n\treturn a.Scale(1 / l)\n}\n\nfunc (a Vec2) String() string { return fmt.Sprintf(\"(%.2f, %.2f)\", a.X, a.Y) }\n\n// Tuning values are per tick at a fixed 60 ticks per second.\nconst (\n\ttps       = 60\n\taccel     = 0.6  // px/tick gained per tick while input is held\n\tdrag      = 0.8  // velocity multiplier applied every tick\n\tstopBelow = 0.05 // px per tick; snap tiny speeds to zero\n)\n\ntype Body struct{ Pos, Vel Vec2 }\n\nfunc (b *Body) Step(input Vec2) {\n\tb.Vel = b.Vel.Add(input.Normalize().Scale(accel)).Scale(drag)\n\tif b.Vel.Len() < stopBelow {\n\t\tb.Vel = Vec2{}\n\t}\n\tb.Pos = b.Pos.Add(b.Vel) // semi-implicit Euler: new velocity, then position\n}\n\nfunc main() {\n\traw := Vec2{1, 1} // right + down held together\n\tfmt.Printf(\"raw input %v length %.2f\\n\", raw, raw.Len())\n\tfmt.Printf(\"unit dir  %v length %.2f\\n\", raw.Normalize(), raw.Normalize().Len())\n\n\tvar b Body\n\tfor tick := 1; tick <= 60; tick++ {\n\t\tinput := Vec2{}\n\t\tif tick <= 12 {\n\t\t\tinput = raw\n\t\t}\n\t\tb.Step(input)\n\t\tstopped := tick > 12 && b.Vel == (Vec2{})\n\t\tif tick <= 3 || tick == 12 || tick == 13 || tick == 20 || stopped {\n\t\t\tfmt.Printf(\"tick %2d pos=%v speed=%.3f px/tick\\n\", tick, b.Pos, b.Vel.Len())\n\t\t}\n\t\tif stopped {\n\t\t\tbreak\n\t\t}\n\t}\n\tterminal := accel * drag / (1 - drag)\n\tfmt.Printf(\"terminal speed %.2f px/tick = %.0f px/s at %d TPS\\n\", terminal, terminal*tps, tps)\n\tfmt.Printf(\"without Normalize the diagonal tops out at %.2f px/tick\\n\", terminal*raw.Len())\n}","language":"go","title":"Normalize diagonal input, then integrate per tick","walkthrough":"The first two lines show the raw diagonal and its unit direction. While input is held (ticks 1 to 12), speed climbs 0.480, 0.864, 1.171 and approaches the terminal speed where the gain of 0.6 per tick balances the 20% drag: v = (v + 0.6) * 0.8 solves to 2.40 px/tick. After release, speed shrinks by a factor of 0.8 per tick until it drops below 0.05 and snaps to zero on tick 30, so the body stops for good instead of creeping by ever smaller amounts. The last line shows what skipping Normalize costs: a diagonal top speed of 3.39 instead of 2.40."},{"body":"With a fixed tick rate, a speed of 2.4 px/tick is exact and the same on every machine, because the fixed-timestep lesson guarantees how many ticks run per second. Per-frame units are wrong on every display except the one you tuned on. Per-second units multiplied by dt are correct in principle but bury the step size in every formula, and drag does not scale linearly: a factor of 0.8 per tick is 0.8 to the power 60 per second, not 0.8 times 60. Keep tuning constants per tick, convert only for people (2.40 px/tick is 144 px/s at 60 TPS), and if you ever change TPS, convert every constant deliberately.","code":"// Convert per-tick tuning from 60 to 120 ticks per second.\nratio := 60.0 / 120.0\nspeed120 := speed60 * ratio         // px/tick halves\naccel120 := accel60 * ratio * ratio // px/tick gained per tick quarters\ndrag120 := math.Pow(drag60, ratio)  // 0.8 becomes about 0.894","language":"go","title":"Why per-tick units beat per-frame units","walkthrough":"This fragment shows the arithmetic and is not a runnable program. Doubling TPS halves the distance per tick, quarters the velocity gained per tick, and turns the drag factor into its square root, so two new ticks remove as much speed as one old tick did. Missing any of these changes how the game feels, which is why the tick rate should be chosen once and early."},{"body":"The output above is exact for this toolchain and machine, but floating-point results are not guaranteed to be bit-identical across architectures. The Go specification allows an implementation to fuse x*y + z into a single fused multiply-add, which skips one rounding, and whether that happens depends on the target architecture and its settings, so the same source can differ in the last bit and drift apart after thousands of ticks. That never matters for a single-player game printed at two decimals. It matters for lockstep multiplayer and for replays shared between platforms. An explicit conversion forces the intermediate rounding and forbids fusion; teams that need strict cross-platform determinism often go further and keep positions in fixed-point integers, as the integer jump physics in the input lesson does.","code":"// The compiler may fuse this into one multiply-add on some targets:\nnext := pos + vel*dt\n// The explicit conversion forces vel*dt to be rounded first, forbidding fusion:\nnext = pos + float64(vel*dt)","language":"go","title":"Floating point is reproducible only within one build","walkthrough":"This fragment follows the floating-point operator rules in the Go specification. In the first line the product vel*dt is not explicitly rounded, so the compiler may compute pos + vel*dt as one fused operation. Wrapping the product in float64(...) requires it to be rounded to float64 first, which makes the result the same with or without FMA hardware."},{"body":"Movement is a pure function of state and input, so table tests pin it down cheaply. Assert that a held diagonal reaches the same top speed as a held cardinal direction, that releasing input reaches exactly zero within a known number of ticks, and that normalizing the zero vector returns the zero vector rather than NaN. NaN is contagious: one bad division turns a position into NaN, every comparison against it is false, and collision code silently stops working, so a debug assertion with math.IsNaN in the step function pays for itself. Keep a body's state in one struct and step it from one place; a second code path that nudges position directly, such as knockback applied from an animation callback, is how determinism quietly breaks.","title":"Test movement as a pure function"}],"takeaway":"Use a small value-type vector, normalize the input direction before scaling it, update velocity and then position once per tick, and keep every tuning constant per tick so movement is identical wherever the same build runs.","title":"A 2D vector value type: normalized input, acceleration and drag in per-tick units","unitID":"gamedev-loop","wrongAnswers":["Diagonal movement becomes about 29% slower","Velocity becomes NaN when both keys are held"]},{"conceptTag":"gamedev.input-actions","designGuide":{"cautions":["Per-key edges double-fire when two keys share an action.","A tap shorter than one tick is invisible to polling."],"cost":"A binding table, two bytes of action state and two counters per player; the real cost is play-testing the window sizes.","family":"gamedev","flow":["Poll keys once per tick","Map keys to action bits","Edge = down &^ prev","Apply grace windows"],"ratings":[],"strengths":["Rebinding and multiple devices become a data change.","Forgiving controls are exact, replayable tick rules."]},"hint":"The press arrives after the floor is gone, not before the floor arrives.","id":"gamedev.input-actions","introduction":"Players do not press buttons on the exact tick the game expects. They press jump a few ticks before landing or a few ticks after running off a ledge, and a strict implementation swallows those presses and feels broken. Responsive platformer controls are built from three small pieces: an action layer over physical keys, edge detection on actions, and short grace windows measured in ticks.","nuance":"Buffering forgives a press that comes too early by remembering it until landing; coyote time forgives a press that comes too late by allowing a jump for a few ticks after leaving the floor.","objective":"Map physical keys to actions, detect presses on the action level, and implement jump buffering and coyote time as tick counters that can be tested deterministically.","question":"A player runs off a ledge and presses jump two ticks later. Which mechanism lets that jump happen?","references":["https://pkg.go.dev/github.com/hajimehoshi/ebiten/v2#IsKeyPressed","https://pkg.go.dev/github.com/hajimehoshi/ebiten/v2/inpututil#IsKeyJustPressed","https://gameprogrammingpatterns.com/command.html"],"reviewAnswer":"A few ticks after leaving a ledge when jump still works","reviewPrompt":"What is coyote time?","sections":[{"body":"Game logic should ask whether Jump is pressed, never whether Space is. A binding table maps each physical key or button to an action, several keys may share one action (Space, W and a gamepad face button all mean Jump), and rebinding becomes a data change. Storing a tick's actions as bits in a uint8 makes the whole input state one comparable value: pressed is down&a != 0, and just pressed is down &^ prev, the bits set now that were clear on the previous tick. Detecting edges on actions rather than keys matters as soon as two keys share an action. A per-key helper such as Ebitengine's inpututil.IsKeyJustPressed correctly reports a fresh press when the player adds W while already holding Space; OR the per-key edges together and you get a second jump the player never asked for.","title":"Bind keys to actions, then detect edges on actions"},{"body":"The program drives a player through 75 scripted ticks: a long hold of Space, a second jump key pressed during that hold, a tap on the floor, a press shortly before landing, and a run to the right over two ledges with one press after each. The physics is integer arithmetic on purpose: gravity is 1 per tick and a jump sets the vertical speed to 5, so every tick is exact and the output reads as a precise specification of the controls. Only ticks with an event are printed.","code":"package main\n\nimport \"fmt\"\n\n// Key names a physical control; Ebitengine would use ebiten.Key values.\ntype Key string\n\n// Action is a bit set, so one tick's input is a single comparable value.\ntype Action uint8\n\nconst (\n\tLeft Action = 1 << iota\n\tRight\n\tJump\n)\n\n// bindings maps physical keys to actions; several keys may share an action.\nvar bindings = map[Key]Action{\n\t\"ArrowLeft\": Left, \"KeyA\": Left,\n\t\"ArrowRight\": Right, \"KeyD\": Right,\n\t\"Space\": Jump, \"KeyW\": Jump, \"PadSouth\": Jump,\n}\n\n// Input holds this tick's actions and the previous tick's.\ntype Input struct{ down, prev Action }\n\nfunc (in *Input) Poll(keys []Key) {\n\tin.prev, in.down = in.down, 0\n\tfor _, k := range keys {\n\t\tin.down |= bindings[k]\n\t}\n}\n\nfunc (in Input) Pressed(a Action) bool     { return in.down&a != 0 }\nfunc (in Input) JustPressed(a Action) bool { return in.down&^in.prev&a != 0 }\n\nconst (\n\tgravity     = 1\n\tjumpSpeed   = 5\n\tcoyoteTicks = 4 // a jump is still allowed this many ticks after leaving the floor\n\tbufferTicks = 5 // a jump press is remembered this many ticks\n)\n\nfunc floorAt(x int) int {\n\tswitch {\n\tcase x < 12:\n\t\treturn 0\n\tcase x < 30:\n\t\treturn -10\n\tdefault:\n\t\treturn -100\n\t}\n}\n\ntype Player struct {\n\tX, Y, VY int\n\tair      int  // ticks since the feet last touched the floor\n\tjumped   bool // this airtime began with a jump, so coyote time is spent\n\tpress    int  // ticks since an unused jump press; -1 when none is pending\n}\n\nfunc (p *Player) Tick(in Input) (event string) {\n\tif in.JustPressed(Jump) {\n\t\tp.press = 0\n\t\tif p.air > 0 {\n\t\t\tevent = fmt.Sprintf(\"jump pressed %d ticks off the floor\", p.air)\n\t\t}\n\t}\n\tif p.press >= 0 {\n\t\tswitch {\n\t\tcase !p.jumped && p.air <= coyoteTicks:\n\t\t\tevent = fmt.Sprintf(\"jump: pressed %d ticks ago, %d ticks off the floor\", p.press, p.air)\n\t\t\tp.VY, p.jumped, p.press = jumpSpeed, true, -1\n\t\tcase p.press >= bufferTicks:\n\t\t\tevent, p.press = \"buffered press expired\", -1\n\t\tdefault:\n\t\t\tp.press++\n\t\t}\n\t}\n\tif in.Pressed(Right) {\n\t\tp.X++\n\t}\n\tif in.Pressed(Left) {\n\t\tp.X--\n\t}\n\tp.VY -= gravity\n\tp.Y += p.VY\n\tif f := floorAt(p.X); p.Y <= f {\n\t\tif p.air > 0 && event == \"\" {\n\t\t\tevent = fmt.Sprintf(\"landed at x=%d y=%d\", p.X, f)\n\t\t}\n\t\tp.Y, p.VY, p.air, p.jumped = f, 0, 0, false\n\t} else {\n\t\tp.air++\n\t}\n\treturn event\n}\n\ntype hold struct {\n\tkey      Key\n\tfrom, to int // inclusive ticks\n}\n\nfunc keysAt(script []hold, tick int) []Key {\n\tvar keys []Key\n\tfor _, h := range script {\n\t\tif tick >= h.from && tick <= h.to {\n\t\t\tkeys = append(keys, h.key)\n\t\t}\n\t}\n\treturn keys\n}\n\nfunc main() {\n\tscript := []hold{\n\t\t{\"Space\", 2, 14},     // hold through landing: one jump, not a bounce\n\t\t{\"KeyW\", 6, 7},       // second jump key while Space is held: no new edge\n\t\t{\"Space\", 17, 17},    // tap on the floor\n\t\t{\"PadSouth\", 24, 24}, // pressed just before landing: buffered\n\t\t{\"KeyD\", 30, 75},     // run right toward two ledges\n\t\t{\"Space\", 43, 43},    // two ticks after walking off: coyote jump\n\t\t{\"Space\", 65, 65},    // six ticks after the next ledge: too late\n\t}\n\tp := &Player{press: -1}\n\tvar in Input\n\tkeyEdges, actionEdges := 0, 0\n\theld := map[Key]bool{}\n\tfor tick := 1; tick <= 75; tick++ {\n\t\tkeys := keysAt(script, tick)\n\t\tnow := map[Key]bool{}\n\t\tfor _, k := range keys {\n\t\t\tif !held[k] && bindings[k] == Jump {\n\t\t\t\tkeyEdges++\n\t\t\t}\n\t\t\tnow[k] = true\n\t\t}\n\t\theld = now\n\t\tin.Poll(keys)\n\t\tif in.JustPressed(Jump) {\n\t\t\tactionEdges++\n\t\t}\n\t\tif ev := p.Tick(in); ev != \"\" {\n\t\t\tfmt.Printf(\"tick %2d: %s\\n\", tick, ev)\n\t\t}\n\t}\n\tfmt.Printf(\"jump keys went down %d times; the Jump action had %d edges\\n\", keyEdges, actionEdges)\n}","language":"go","title":"Simulate the controls tick by tick","walkthrough":"Tick 2 jumps from the floor. Space stays down until tick 14 and W joins it on tick 6, but the Jump action has no new edge, so the landing on tick 10 does not bounce. On tick 24 PadSouth is pressed seven ticks into the air; the press is buffered, the player lands on tick 25, and tick 26 jumps with a two-tick-old press. On tick 41 the player runs off the first ledge; the press on tick 43 comes two ticks after leaving the floor, inside the four-tick coyote window, so it jumps. After the second ledge the press comes six ticks late: no coyote time is left, the buffered press expires on tick 70, and the player lands on tick 71 without jumping. The summary counts six key presses but five action edges, because W never created one."},{"body":"Both features are windows measured in ticks, and both live in Player, where tests can see them. Jump buffering forgives a press that is too early: press is set to 0 on the action edge, grows by one each tick it stays unused, and is cleared when it reaches bufferTicks while a jump is still impossible, so a press made up to five ticks before the first grounded tick still fires. Coyote time forgives a press that is too late: air counts ticks since the feet last touched the floor, and a jump is allowed while air is at most coyoteTicks. The jumped flag is the detail that is easy to miss. A jump also leaves the floor, and without the flag the coyote rule would allow a second jump during the first four ticks of the first one. Start with a handful of ticks for each window and tune them by playing; keep them in ticks for the reasons the movement lesson gives.","title":"Buffering and coyote time are two counters"},{"body":"In a real game, polling is the only code that touches the engine. It runs once per tick at the start of Update and turns key states into the Action bits the simulation already understands. Polling at the tick rate has one consequence worth knowing: a press and release that both happen between two polls are invisible, so an extremely short tap can be lost. At 60 TPS that window is about 17 ms and rarely matters. Ebitengine documents its Key constants as physical key positions on a US keyboard, so a WASD layout stays in the same place for players with other keyboard layouts; when a rebinding screen shows key names, remember that the label printed on the player's key may differ from the constant's name.","code":"var jumpKeys = []ebiten.Key{ebiten.KeySpace, ebiten.KeyW, ebiten.KeyArrowUp}\n\nfunc pollActions() Action {\n\tvar a Action\n\tfor _, k := range jumpKeys {\n\t\tif ebiten.IsKeyPressed(k) {\n\t\t\ta |= Jump\n\t\t}\n\t}\n\tif ebiten.IsKeyPressed(ebiten.KeyArrowLeft) || ebiten.IsKeyPressed(ebiten.KeyA) {\n\t\ta |= Left\n\t}\n\tif ebiten.IsKeyPressed(ebiten.KeyArrowRight) || ebiten.IsKeyPressed(ebiten.KeyD) {\n\t\ta |= Right\n\t}\n\treturn a\n}\n\nfunc (g *Game) Update() error {\n\tg.in.prev, g.in.down = g.in.down, pollActions()\n\tg.player.Tick(g.in)\n\treturn nil\n}","language":"go","title":"Wire the same logic to Ebitengine","walkthrough":"Run this fragment in your own Ebitengine module; it reuses Action, Input and Player from the program above. IsKeyPressed reports each key's level once per tick, and the edge is computed from the previous tick's Action bits, so W pressed while Space is held never produces a second Jump edge. Because Update runs at a fixed tick rate, bufferTicks and coyoteTicks mean the same amount of time on every display."},{"body":"Input is a list of held keys per tick and the output is a list of events, so every control rule becomes a regression test: press three ticks before landing and expect a jump on the first grounded tick; press coyoteTicks + 1 ticks after a ledge and expect none; hold jump across a landing and expect exactly one jump. These tests catch the classic regressions, such as incrementing the buffer before the jump check, which silently shortens the window by a tick, or dropping the jumped flag, which turns coyote time into a double jump. Record real play sessions in the same format and a bug report becomes an exact replay. Combos and charge attacks extend the same idea: small counters over action edges, never timers that read the wall clock.","title":"Test controls as tables of ticks"}],"takeaway":"Read physical keys into action bits once per tick, detect edges on actions rather than keys, and express buffering and coyote time as tick counters in game state so every forgiving rule is deterministic and testable.","title":"Input as actions: edge detection, jump buffering and coyote time in a tick-exact simulation","unitID":"gamedev-loop","wrongAnswers":["Jump buffering, which remembers presses made in the air","Edge detection, which turns a held key into repeated jumps"]},{"conceptTag":"gamedev.state-machines","designGuide":{"cautions":["Without hysteresis, threshold transitions flicker every tick.","Large machines outgrow one switch; split states into types."],"cost":"One interface, a small stack and a Mode enum per actor; a little more structure than a few booleans, repaid at the first state bug.","family":"gamedev","flow":["Scene returns Transition","Stack applies the change","Top scene updates","All scenes draw bottom-up"],"ratings":[],"strengths":["Impossible state combinations cannot be represented.","Pause and overlays need no checks inside gameplay code."]},"hint":"Think about what resuming must restore, and which scene the stack updates.","id":"gamedev.state-machines","introduction":"Games are full of modes: menus, gameplay, pause overlays, and enemies that patrol, chase and attack. Encoding them as booleans such as paused, gameOver, chasing and attacking creates combinations that should be impossible and guards that must be repeated everywhere. Two explicit state machines replace them: a stack of scenes for the flow of the game, and one mode value with one transition function for each enemy.","nuance":"Only the top scene updates, so the world underneath is frozen while paused, and Pop returns to that same value with its state intact; Replace would discard it.","objective":"Run title, playing, paused and game-over scenes through a scene interface and a transition stack, and drive an enemy with a single-mode behavior machine.","question":"In a scene stack, why is the pause menu pushed on top of the playing scene instead of replacing it?","references":["https://gameprogrammingpatterns.com/state.html","https://go.dev/doc/effective_go#interfaces","https://pkg.go.dev/github.com/hajimehoshi/ebiten/v2#Game"],"reviewAnswer":"Pop must resume the same, untouched world beneath it","reviewPrompt":"Why does pause push, not replace?","sections":[{"body":"Four booleans describe sixteen combinations; an enemy that can only be patrolling, chasing, attacking or recovering has four legal ones. Every update then needs guards like !paused && chasing && !attacking, and every new flag doubles the number of states nobody has tested. The bugs are characteristic: the enemy keeps chasing behind the pause menu because one guard was missing, or attacks forever because the code that cleared attacking returned early. A state machine makes the current state a single value, makes transitions the only way to change it, and gives each state one place where its behavior is written. The State pattern lesson shows the idea for a review workflow; games add a stack for overlays and timers that belong to a state.","code":"type Enemy struct {\n\tpatrolling, chasing, attacking, recovering bool // 16 combinations, 4 legal\n\trecoverTicks                               int\n\tpaused                                     bool // and now 32\n}\n\nfunc (e *Enemy) Update() {\n\tif !e.paused && e.chasing && !e.attacking { // every caller repeats a guard like this\n\t\t// ...\n\t}\n}","language":"go","title":"What boolean-flag soup costs","walkthrough":"This fragment is the shape to avoid, not code to run. Nothing stops chasing and attacking from both being true, every caller must remember which flags to clear on each change, and the pause flag leaks into enemy code. Compare it with the single Mode field and the scene stack in the program below."},{"body":"Each scene implements Update, which returns a Transition, and Draw. The Stack applies the transition: Replace swaps the top scene (title to playing, playing to game over), Push puts a scene on top (pause), and Pop returns to the scene underneath with its state untouched. Only the top scene updates, so the world freezes while paused without a single paused check, and every scene draws bottom-up, so the pause overlay appears over the frozen world. Inside Playing, the enemy's Mode is one enum value, and the next method encodes every legal transition in one switch.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n// Input is one tick's snapshot: actions plus the tick number for logging.\ntype Input struct {\n\tTick           int\n\tConfirm, Pause bool\n\tMove           int\n}\n\n// Op says what the scene stack should do after a scene's Update.\ntype Op int\n\nconst (\n\tStay Op = iota\n\tPush\n\tPop\n\tReplace\n)\n\ntype Transition struct {\n\tOp   Op\n\tNext Scene\n}\n\ntype Scene interface {\n\tName() string\n\tUpdate(in Input) Transition\n\tDraw(b *strings.Builder)\n}\n\n// Stack updates only the top scene and draws every scene bottom-up.\ntype Stack struct{ scenes []Scene }\n\nfunc (s *Stack) Update(in Input) {\n\ttop := len(s.scenes) - 1\n\tt := s.scenes[top].Update(in)\n\tswitch t.Op {\n\tcase Stay:\n\t\treturn\n\tcase Push:\n\t\ts.scenes = append(s.scenes, t.Next)\n\tcase Pop:\n\t\ts.scenes = s.scenes[:top]\n\tcase Replace:\n\t\ts.scenes[top] = t.Next\n\t}\n\tnames := make([]string, len(s.scenes))\n\tfor i, sc := range s.scenes {\n\t\tnames[i] = sc.Name()\n\t}\n\tfmt.Printf(\"tick %2d: scenes [%s]\\n\", in.Tick, strings.Join(names, \" \"))\n}\n\nfunc (s *Stack) Draw() string {\n\tvar b strings.Builder\n\tfor _, sc := range s.scenes {\n\t\tsc.Draw(&b)\n\t}\n\treturn b.String()\n}\n\ntype Title struct{}\n\nfunc (Title) Name() string { return \"title\" }\nfunc (Title) Update(in Input) Transition {\n\tif in.Confirm {\n\t\treturn Transition{Replace, NewPlaying()}\n\t}\n\treturn Transition{}\n}\nfunc (Title) Draw(b *strings.Builder) { b.WriteString(\"[press confirm]\") }\n\ntype Playing struct {\n\tPlayerX, HP int\n\tEnemy       Enemy\n}\n\nfunc NewPlaying() *Playing {\n\treturn &Playing{PlayerX: 10, HP: 2, Enemy: Enemy{X: 22, Dir: 1}}\n}\n\nfunc (*Playing) Name() string { return \"playing\" }\nfunc (p *Playing) Update(in Input) Transition {\n\tif in.Pause {\n\t\treturn Transition{Push, Paused{}}\n\t}\n\tp.PlayerX += in.Move\n\tif p.Enemy.Update(in.Tick, p.PlayerX) {\n\t\tp.HP--\n\t}\n\tif p.HP == 0 {\n\t\treturn Transition{Replace, GameOver{}}\n\t}\n\treturn Transition{}\n}\nfunc (p *Playing) Draw(b *strings.Builder) {\n\tfmt.Fprintf(b, \"[player x=%d hp=%d, enemy x=%d %v]\", p.PlayerX, p.HP, p.Enemy.X, p.Enemy.Mode)\n}\n\ntype Paused struct{}\n\nfunc (Paused) Name() string { return \"paused\" }\nfunc (Paused) Update(in Input) Transition {\n\tif in.Pause {\n\t\treturn Transition{Op: Pop}\n\t}\n\treturn Transition{}\n}\nfunc (Paused) Draw(b *strings.Builder) { b.WriteString(\"[PAUSED overlay]\") }\n\ntype GameOver struct{}\n\nfunc (GameOver) Name() string { return \"gameover\" }\nfunc (GameOver) Update(in Input) Transition {\n\tif in.Confirm {\n\t\treturn Transition{Replace, Title{}}\n\t}\n\treturn Transition{}\n}\nfunc (GameOver) Draw(b *strings.Builder) { b.WriteString(\"[game over]\") }\n\n// Mode is the enemy's behavior state: exactly one value at a time.\ntype Mode int\n\nconst (\n\tPatrol Mode = iota\n\tChase\n\tAttack\n\tRecover\n)\n\nfunc (m Mode) String() string { return [...]string{\"patrol\", \"chase\", \"attack\", \"recover\"}[m] }\n\ntype Enemy struct {\n\tX, Dir int\n\tMode   Mode\n\tinMode int // ticks spent in the current mode\n}\n\nfunc (e *Enemy) next(dist int) Mode {\n\tswitch e.Mode {\n\tcase Patrol:\n\t\tif dist <= 5 {\n\t\t\treturn Chase\n\t\t}\n\tcase Chase:\n\t\tif dist <= 1 {\n\t\t\treturn Attack\n\t\t}\n\t\tif dist > 9 { // leave at 9, enter at 5: hysteresis stops flicker\n\t\t\treturn Patrol\n\t\t}\n\tcase Attack:\n\t\treturn Recover\n\tcase Recover:\n\t\tif e.inMode < 3 {\n\t\t\tbreak\n\t\t}\n\t\tif dist > 9 {\n\t\t\treturn Patrol\n\t\t}\n\t\treturn Chase\n\t}\n\treturn e.Mode\n}\n\n// Update runs one tick and reports whether the enemy landed a hit.\nfunc (e *Enemy) Update(tick, playerX int) (hit bool) {\n\tdist := max(playerX-e.X, e.X-playerX) // absolute distance\n\tif m := e.next(dist); m != e.Mode {\n\t\tfmt.Printf(\"tick %2d: enemy %v -> %v at distance %d\\n\", tick, e.Mode, m, dist)\n\t\te.Mode, e.inMode = m, 0\n\t\thit = m == Attack\n\t} else {\n\t\te.inMode++\n\t}\n\tswitch e.Mode {\n\tcase Patrol:\n\t\te.X += e.Dir\n\t\tif e.X <= 20 || e.X >= 26 {\n\t\t\te.Dir = -e.Dir\n\t\t}\n\tcase Chase:\n\t\tif playerX > e.X {\n\t\t\te.X++\n\t\t} else if playerX < e.X {\n\t\t\te.X--\n\t\t}\n\t}\n\treturn hit\n}\n\nfunc inputAt(tick int) Input {\n\tin := Input{Tick: tick}\n\tswitch {\n\tcase tick == 2 || tick == 40 || tick == 42:\n\t\tin.Confirm = true\n\tcase tick == 24 || tick == 27:\n\t\tin.Pause = true\n\tcase tick >= 3 && tick <= 12:\n\t\tin.Move = 1\n\tcase tick >= 13 && tick <= 18:\n\t\tin.Move = -2\n\tcase tick >= 28 && tick <= 36:\n\t\tin.Move = 1\n\t}\n\treturn in\n}\n\nfunc main() {\n\ts := &Stack{scenes: []Scene{Title{}}}\n\tfor tick := 1; tick <= 42; tick++ {\n\t\ts.Update(inputAt(tick))\n\t\tif tick == 25 || tick == 42 {\n\t\t\tfmt.Println(\"draw:\", s.Draw())\n\t\t}\n\t}\n}","language":"go","title":"A scene stack and an enemy mode machine","walkthrough":"Tick 2 replaces the title with a fresh Playing scene. The enemy notices the player at distance 5 on tick 10, attacks at distance 1 on tick 12, recovers, and goes back to patrol on tick 17 because the player has run eleven units away. Tick 24 pushes Paused; the draw on tick 25 shows the frozen world under the overlay, and nothing moves until tick 27 pops back to the same Playing value. The second hit on tick 36 drops HP to zero, Playing replaces itself with GameOver, and after two confirms the new Playing scene starts again at x=10 with hp=2: Replace threw the old world away together with its scene."},{"body":"Returning a Transition instead of assigning a global current-scene variable keeps scenes ignorant of the stack and puts the whole lifecycle in one place. That is where real games add the hooks they need: an Enter method to start music or reset a timer, an Exit method to release resources, and a log line for every transition, which makes bug reports far easier to read. Ownership follows the structure. Playing owns the world; Paused owns nothing and refers to nothing; Replace discards the old world, so a finished run cannot leak enemy state into the next one. The same pushdown structure builds nested menus (options over pause over gameplay) and modal dialogs, and it is why Pop needs no knowledge of what lies underneath. In Ebitengine, Game.Update calls the stack's Update once per tick and Game.Draw calls the stack's Draw.","title":"Transitions are values, so ownership is clear"},{"body":"The next method reads like a transition table: from Patrol only Chase is reachable, Chase leads to Attack or back to Patrol, Attack always leads to Recover, and Recover waits three ticks before deciding. Two details make machines like this robust. First, inMode resets on every transition, so recovering for three ticks is a property of the state rather than a separate cooldown variable someone forgets to reset. Second, the thresholds differ: chase starts at distance 5 but stops only beyond 9. With a single threshold, a player standing exactly on the boundary makes the enemy flip modes every tick, which shows up as jittering animation and repeated alert sounds. Put one-off effects on transitions (the hit happens when entering Attack) and continuous behavior in the per-mode movement switch.","title":"Enemy modes: one value, timers per mode, hysteresis"},{"body":"A Mode enum with a switch scales to roughly a dozen states. Beyond that, separate state types with Enter, Update and Exit methods, the object form of the pattern, keep each state's code in its own file. Hierarchical machines help when several states share a parent behavior, such as every grounded state allowing a jump, and behavior trees or utility scoring suit enemies whose decisions weigh many factors at once. Whatever the form, test it the same way: feed scripted inputs, print transitions with tick numbers as this program does, and compare the result against a golden list. A transition log is also the single most useful attachment to an AI bug report.","title":"When to grow beyond a switch"}],"takeaway":"Give every mode exactly one representation: a scene stack driven by returned transitions, and an enemy Mode with one transition function, per-mode timers and hysteresis, so impossible combinations cannot be expressed at all.","title":"Scenes and enemy behavior as explicit state machines instead of boolean flags","unitID":"gamedev-loop","wrongAnswers":["Pushing makes the pause menu update faster","Replace would keep updating the world in the background"]},{"conceptTag":"gamedev.entity-components","designGuide":{"cautions":["Component pointers are invalid after the next Add or Remove.","Recycled IDs need generation counters to reject stale handles."],"cost":"A store type and explicit world fields; more indirection than plain structs, worth it only when composition or measured iteration cost demands it.","family":"gamedev","flow":["Spawn an entity ID","Add components to stores","Systems loop over dense data","Flush queued removals"],"ratings":[],"strengths":["Behavior composes from components without type hierarchies.","Systems iterate contiguous slices with no gaps."]},"hint":"Look at which element Remove moves into the freed slot.","id":"gamedev.entity-components","introduction":"The first instinct for game objects is a hierarchy: a base object, a character built on it, an enemy built on that. In Go such hierarchies fight the language, which has no inheritance, and the hardware, which prefers contiguous data. An entity-component design keeps an entity as a bare ID, stores each component type in its own dense slice, and writes behavior as systems that loop over those slices.","nuance":"Remove copies the last element into the hole at an index the iterator has already passed, so the moved entity would not be visited on this tick.","objective":"Build a minimal entity-component store with generics, run systems over dense slices, remove with swap-delete, and judge when plain structs are the better design.","question":"Why does the Aging system queue dead entities instead of removing them while it ranges over the store?","references":["https://gameprogrammingpatterns.com/component.html","https://gameprogrammingpatterns.com/data-locality.html","https://go.dev/doc/tutorial/generics","https://pkg.go.dev/iter"],"reviewAnswer":"Swap-delete during iteration skips the moved element","reviewPrompt":"Why queue deaths until Flush?","sections":[{"body":"Picture GameObject, Character embedding GameObject, Enemy embedding Character and FlyingEnemy embedding Enemy. Embedding promotes methods but is not inheritance: there is no virtual dispatch from the embedded type back to the outer one, so when a Character method calls Update it calls Character's Update, never FlyingEnemy's. Teams compensate with interfaces at every level and type switches, while the base type collects fields that only some objects use. Behavior that cuts across branches, such as a turret that has health but is not a character, has no natural home. Iteration suffers as well: a slice of interface values points at objects scattered across the heap, so updating ten thousand of them chases ten thousand pointers. Composition fixes both problems: an entity has whichever components it has, and each system names the ones it needs.","title":"Why deep object hierarchies hurt"},{"body":"Store[T] keeps the components of one type in a dense slice, the owning entity of each element in a parallel owners slice, and a sparse slice from entity ID to dense index plus one, so that zero means absent. Add and Get take constant time, iteration visits only entities that have the component with no gaps, and Remove swap-deletes: the last element moves into the hole, so removal is constant time and the data stays dense. World has one typed store field per component, which keeps every access checked by the compiler without reflection or maps keyed by type. Systems are ordinary functions over the world.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"iter\"\n\t\"slices\"\n)\n\n// Entity is only an ID. It owns no data and has no methods of its own.\ntype Entity uint32\n\n// Store packs one component type densely. sparse[e] holds the dense index\n// plus one (zero means absent); owners[i] says which entity owns data[i].\ntype Store[T any] struct {\n\tsparse []int\n\towners []Entity\n\tdata   []T\n}\n\nfunc (s *Store[T]) Has(e Entity) bool { return int(e) < len(s.sparse) && s.sparse[e] != 0 }\n\nfunc (s *Store[T]) Add(e Entity, v T) {\n\tif s.Has(e) {\n\t\ts.data[s.sparse[e]-1] = v\n\t\treturn\n\t}\n\tif need := int(e) + 1; need > len(s.sparse) {\n\t\ts.sparse = append(s.sparse, make([]int, need-len(s.sparse))...)\n\t}\n\ts.data = append(s.data, v)\n\ts.owners = append(s.owners, e)\n\ts.sparse[e] = len(s.data)\n}\n\n// Get returns a pointer into the dense slice, valid until the next Add or Remove.\nfunc (s *Store[T]) Get(e Entity) (*T, bool) {\n\tif !s.Has(e) {\n\t\treturn nil, false\n\t}\n\treturn &s.data[s.sparse[e]-1], true\n}\n\n// Remove swap-deletes: the last element moves into the hole, so order changes.\nfunc (s *Store[T]) Remove(e Entity) {\n\tif !s.Has(e) {\n\t\treturn\n\t}\n\ti, last := s.sparse[e]-1, len(s.data)-1\n\ts.data[i], s.owners[i] = s.data[last], s.owners[last]\n\ts.sparse[s.owners[i]] = i + 1\n\tvar zero T\n\ts.data[last] = zero // do not keep references alive in the unused tail\n\ts.data, s.owners = s.data[:last], s.owners[:last]\n\ts.sparse[e] = 0\n}\n\n// All yields entities and component pointers in dense order. Do not Add or\n// Remove while iterating; queue structural changes instead.\nfunc (s *Store[T]) All() iter.Seq2[Entity, *T] {\n\treturn func(yield func(Entity, *T) bool) {\n\t\tfor i := range s.data {\n\t\t\tif !yield(s.owners[i], &s.data[i]) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype Position struct{ X, Y int }\ntype Velocity struct{ X, Y int }\ntype Lifetime struct{ Ticks int }\n\ntype World struct {\n\tlast Entity\n\tPos  Store[Position]\n\tVel  Store[Velocity]\n\tLife Store[Lifetime]\n\tdead []Entity\n}\n\nfunc (w *World) Spawn() Entity { w.last++; return w.last }\n\nfunc (w *World) Destroy(e Entity) {\n\tw.Pos.Remove(e)\n\tw.Vel.Remove(e)\n\tw.Life.Remove(e)\n}\n\n// Movement touches every entity that has both Position and Velocity.\nfunc Movement(w *World) {\n\tfor e, v := range w.Vel.All() {\n\t\tif p, ok := w.Pos.Get(e); ok {\n\t\t\tp.X += v.X\n\t\t\tp.Y += v.Y\n\t\t}\n\t}\n}\n\n// Aging only queues deaths; Flush applies them after all systems ran.\nfunc Aging(w *World) {\n\tfor e, l := range w.Life.All() {\n\t\tl.Ticks--\n\t\tif l.Ticks == 0 {\n\t\t\tw.dead = append(w.dead, e)\n\t\t}\n\t}\n}\n\nfunc Flush(w *World) []Entity {\n\tgone := slices.Clone(w.dead)\n\tfor _, e := range w.dead {\n\t\tw.Destroy(e)\n\t}\n\tw.dead = w.dead[:0]\n\treturn gone\n}\n\nfunc main() {\n\tw := &World{}\n\tplayer := w.Spawn()\n\tw.Pos.Add(player, Position{0, 0})\n\tw.Vel.Add(player, Velocity{1, 0})\n\ttree := w.Spawn() // Position only: systems that need Velocity skip it\n\tw.Pos.Add(tree, Position{5, 5})\n\tfor i, ticks := range []int{2, 1, 3, 5} {\n\t\tb := w.Spawn()\n\t\tw.Pos.Add(b, Position{0, i})\n\t\tw.Vel.Add(b, Velocity{3, 0})\n\t\tw.Life.Add(b, Lifetime{ticks})\n\t}\n\tfmt.Println(\"tick 0: velocity dense order\", w.Vel.owners)\n\tfor tick := 1; tick <= 3; tick++ {\n\t\tMovement(w)\n\t\tAging(w)\n\t\tgone := Flush(w)\n\t\tfmt.Printf(\"tick %d: destroyed %v, velocity dense order %v\\n\", tick, gone, w.Vel.owners)\n\t}\n\tids := slices.Clone(w.Pos.owners)\n\tslices.Sort(ids) // dense order is an implementation detail; report by ID\n\tfor _, e := range ids {\n\t\tp, _ := w.Pos.Get(e)\n\t\t_, moving := w.Vel.Get(e)\n\t\tfmt.Printf(\"entity %d at (%d, %d) moving=%t\\n\", e, p.X, p.Y, moving)\n\t}\n}","language":"go","title":"A sparse set per component type","walkthrough":"Entity 1 is a player with Position and Velocity, entity 2 a tree with Position only, and entities 3 to 6 are bullets that live 2, 1, 3 and 5 ticks. Movement ranges over the velocity store, so the tree is never visited. On tick 1 bullet 4 dies and bullet 6, the last element, moves into its slot, giving the dense order [1 3 6 5]; every later death swaps again. Aging only queues deaths in w.dead and Flush destroys them after the systems finish, because removing from a store while ranging over it would skip the element swapped into the current slot. The final report sorts by ID because dense order is an implementation detail."},{"body":"Get returns a pointer into the dense slice, which is fast but short-lived: the next Add may reallocate the slice and the next Remove may move another entity's data to that address. Use such a pointer within one system and never keep it. All is a range-over-func iterator of type iter.Seq2, and the same rule applies to it: no structural changes while iterating, which is why destruction is queued. Remove zeroes the vacated tail element, so a component holding a pointer, such as a sprite, does not keep it alive. This model never reuses IDs; a real engine recycles them and pairs each index with a generation counter, so a stale handle to a destroyed entity fails the lookup instead of silently addressing whichever entity inherited its slot. Rendering usually needs its own sort by layer or depth, because swap-delete makes storage order unstable.","title":"Rules that keep a store correct"},{"body":"Most small Go games need none of this. With a player, a few enemy kinds and bullets, one slice of plain structs per kind and an update loop is already contiguous, fully typed and easy to debug. Reach for components when the same behavior must apply to many otherwise unrelated kinds, when designers compose entities from data files, or when a profile shows iteration dominating the tick; decide with a benchmark, not on principle. Full ECS libraries add archetype storage, queries over several components and parallel scheduling, and each of those is real complexity to own.","code":"type Bullet struct {\n\tPos, Vel Vec2\n\tTicks    int\n}\n\nfunc updateBullets(bs []Bullet) []Bullet {\n\tfor i := range bs {\n\t\tbs[i].Pos = bs[i].Pos.Add(bs[i].Vel)\n\t\tbs[i].Ticks--\n\t}\n\treturn slices.DeleteFunc(bs, func(b Bullet) bool { return b.Ticks <= 0 })\n}","language":"go","title":"When plain structs are enough","walkthrough":"This fragment reuses Vec2 from the movement lesson and is not compiled here. One contiguous slice and one loop, with no IDs at all: for a few hundred bullets it is the simplest option and likely the fastest. slices.DeleteFunc keeps the survivors in order and, since Go 1.22, zeroes the elements past the new length, so removed bullets release anything they referenced."},{"body":"A sparse set has invariants a short test can check after every operation: for each dense index i, sparse[owners[i]] equals i + 1; the number of non-zero sparse entries equals len(data); and owners and data have the same length. Drive random sequences of Add and Remove from a seeded generator and check the invariants after each step, and you will catch the classic swap-delete bug of clearing the removed entity's sparse entry but forgetting to update the moved one. For systems, assert on results keyed by entity ID, never on dense order, so legitimate storage changes do not break the tests.","title":"Test the invariants, not just the output"}],"takeaway":"Keep entities as IDs and components in dense per-type stores, queue structural changes until the systems finish, never hold component pointers across ticks, and stay with plain struct slices until composition or a profile justifies components.","title":"Entities as IDs, components in dense generic stores, systems as plain loops","unitID":"gamedev-loop","wrongAnswers":["Removing entities is too slow to do every tick","Go forbids deleting from a slice inside a range loop"]},{"conceptTag":"gamedev.collisions","designGuide":{"cautions":["Minimum-axis pushes snag on tile seams; resolve tiles per axis.","Fast movers tunnel unless they are sub-stepped or swept."],"cost":"A few dozen lines of geometry; sub-stepping multiplies collision work by the step count for every fast object.","family":"gamedev","flow":["Test overlap cheaply","Measure penetration","Push along shallow axis","Sweep or sub-step fast"],"ratings":[],"strengths":["Box and circle tests are exact and cost a few comparisons.","A swept test finds the time of impact in constant time."]},"hint":"Compare the distance moved in one tick with how thick the wall and the bullet are together.","id":"gamedev.collisions","introduction":"Collision handling has two jobs: detect that two shapes overlap, and decide how to move them apart. Axis-aligned boxes and circles cover most 2D games, and both have exact tests that cost a few comparisons. The failure that bites later is speed: an object that moves farther in one tick than an obstacle is thick can pass through it without ever overlapping it.","nuance":"Discrete tests only check the positions at the end of each tick; if one tick of motion is longer than the overlap window, no checked position overlaps, so sub-steps or a sweep are required.","objective":"Test boxes and circles for overlap, compute the minimum push that separates them, and stop fast objects from tunneling with sub-steps or a swept test.","question":"A bullet passes through a thin wall and no overlap is ever detected. What is the root cause?","references":["https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection","https://pkg.go.dev/math#Copysign"],"reviewAnswer":"Moving farther per tick than the combined thickness","reviewPrompt":"What causes tunneling?","sections":[{"body":"Store a box as a center and half extents. Two boxes overlap when, on both axes, the distance between centers is less than the sum of the half extents; how much less is the penetration depth on that axis. Two circles overlap when the squared distance between centers is less than the squared sum of the radii, so the common miss path never takes a square root. A circle against a box uses the point of the box closest to the circle's center, found by clamping the center into the box; the shapes overlap when that point is closer than the radius. Decide once whether touching counts. These tests use strict comparisons, so shapes that share an edge do not collide, which is exactly the state a resolved collision leaves behind.","title":"Overlap tests that cost a few comparisons"},{"body":"For boxes, the minimum push is along the axis with the smaller penetration, signed away from the other box. It moves the object the shortest distance and usually matches intuition: a box that sinks slightly into a floor is pushed up, not sideways. For circles the push follows the line between the centers. The program resolves one pair of each kind, then fires a bullet that moves 12 units per tick at a wall 2 units thick and compares three ways of checking it: the end position only, sub-steps, and a swept test.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Vec struct{ X, Y float64 }\n\nfunc (a Vec) Add(b Vec) Vec       { return Vec{a.X + b.X, a.Y + b.Y} }\nfunc (a Vec) Sub(b Vec) Vec       { return Vec{a.X - b.X, a.Y - b.Y} }\nfunc (a Vec) Scale(k float64) Vec { return Vec{a.X * k, a.Y * k} }\nfunc (a Vec) Dot(b Vec) float64   { return a.X*b.X + a.Y*b.Y }\nfunc (a Vec) String() string      { return fmt.Sprintf(\"(%.2f, %.2f)\", a.X, a.Y) }\n\n// AABB is an axis-aligned box stored as center and half extents.\ntype AABB struct{ C, Half Vec }\n\n// Push returns the smallest move that separates a from b, along one axis.\n// Touching edges (zero depth) do not count as overlap.\nfunc (a AABB) Push(b AABB) (Vec, bool) {\n\td := b.C.Sub(a.C)\n\tpx := a.Half.X + b.Half.X - math.Abs(d.X)\n\tpy := a.Half.Y + b.Half.Y - math.Abs(d.Y)\n\tif px <= 0 || py <= 0 {\n\t\treturn Vec{}, false\n\t}\n\tif px < py {\n\t\treturn Vec{-math.Copysign(px, d.X), 0}, true\n\t}\n\treturn Vec{0, -math.Copysign(py, d.Y)}, true\n}\n\ntype Circle struct {\n\tC Vec\n\tR float64\n}\n\n// Push separates circle a from circle b along the line between centers.\nfunc (a Circle) Push(b Circle) (Vec, bool) {\n\td := b.C.Sub(a.C)\n\trr := a.R + b.R\n\td2 := d.Dot(d)\n\tif d2 >= rr*rr { // compare squared lengths: no square root on the miss path\n\t\treturn Vec{}, false\n\t}\n\tdist := math.Sqrt(d2)\n\tif dist == 0 {\n\t\treturn Vec{-rr, 0}, true // same center: pick a fixed direction\n\t}\n\treturn d.Scale(-(rr - dist) / dist), true\n}\n\n// PushFromBox separates a circle from a box via the box's closest point.\nfunc (c Circle) PushFromBox(b AABB) (Vec, bool) {\n\tlo, hi := b.C.Sub(b.Half), b.C.Add(b.Half)\n\tq := Vec{max(lo.X, min(c.C.X, hi.X)), max(lo.Y, min(c.C.Y, hi.Y))}\n\td := c.C.Sub(q)\n\td2 := d.Dot(d)\n\tif d2 >= c.R*c.R {\n\t\treturn Vec{}, false\n\t}\n\tif d2 == 0 { // center inside the box: fall back to the box rule\n\t\treturn AABB{c.C, Vec{c.R, c.R}}.Push(b)\n\t}\n\tdist := math.Sqrt(d2)\n\treturn d.Scale((c.R - dist) / dist), true\n}\n\n// Sweep returns the fraction t in [0, 1] of move at which box a first\n// touches b. Growing b by a's half extents turns a into a moving point.\nfunc Sweep(a AABB, move Vec, b AABB) (float64, bool) {\n\tlo := b.C.Sub(b.Half).Sub(a.Half)\n\thi := b.C.Add(b.Half).Add(a.Half)\n\ttmin, tmax := 0.0, 1.0\n\taxes := [2][4]float64{\n\t\t{a.C.X, move.X, lo.X, hi.X},\n\t\t{a.C.Y, move.Y, lo.Y, hi.Y},\n\t}\n\tfor _, ax := range axes {\n\t\tp, d, l, h := ax[0], ax[1], ax[2], ax[3]\n\t\tif d == 0 {\n\t\t\tif p <= l || p >= h {\n\t\t\t\treturn 0, false // parallel to this slab and outside it\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tt1, t2 := (l-p)/d, (h-p)/d\n\t\tif t1 > t2 {\n\t\t\tt1, t2 = t2, t1\n\t\t}\n\t\ttmin, tmax = max(tmin, t1), min(tmax, t2)\n\t\tif tmin >= tmax {\n\t\t\treturn 0, false\n\t\t}\n\t}\n\treturn tmin, true\n}\n\nfunc main() {\n\ta := AABB{Vec{0, 0}, Vec{2, 2}}\n\tb := AABB{Vec{3, 1}, Vec{2, 2}}\n\tpush, hit := a.Push(b)\n\ta.C = a.C.Add(push)\n\t_, again := a.Push(b)\n\tfmt.Printf(\"box vs box: hit=%t push=%v, after push hit=%t\\n\", hit, push, again)\n\n\tc1 := Circle{Vec{0, 0}, 2}\n\tc2 := Circle{Vec{1.8, 2.4}, 2}\n\tpush, hit = c1.Push(c2)\n\tfmt.Printf(\"circle vs circle: hit=%t push=%v\\n\", hit, push)\n\n\tball := Circle{Vec{5, 1}, 1.5}\n\tcrate := AABB{Vec{2, 0}, Vec{2, 2}}\n\tpush, hit = ball.PushFromBox(crate)\n\tfmt.Printf(\"circle vs box: hit=%t push=%v\\n\", hit, push)\n\n\twall := AABB{Vec{10, 0}, Vec{1, 3}}\n\tbullet := AABB{Vec{0, 0}, Vec{0.5, 0.5}}\n\tmove := Vec{12, 0} // one tick of travel: wider than the wall\n\tend := AABB{bullet.C.Add(move), bullet.Half}\n\t_, hit = end.Push(wall)\n\tfmt.Printf(\"bullet discrete: hit=%t, ends at x=%.2f\\n\", hit, end.C.X)\n\n\t// Keep each sub-step at most half the combined thickness along the motion,\n\t// so an overlap is always seen and the shallow axis points back the way it came.\n\tmaxStep := (2*wall.Half.X + 2*bullet.Half.X) / 2\n\tn := int(math.Ceil(math.Abs(move.X) / maxStep))\n\tsub := bullet\n\tfor i := 1; i <= n; i++ {\n\t\tsub.C = sub.C.Add(move.Scale(1 / float64(n)))\n\t\tif push, hit := sub.Push(wall); hit {\n\t\t\tsub.C = sub.C.Add(push)\n\t\t\tfmt.Printf(\"bullet %d substeps of %.2f: hit on substep %d, resolved to x=%.2f\\n\", n, maxStep, i, sub.C.X)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif t, ok := Sweep(bullet, move, wall); ok {\n\t\tfmt.Printf(\"bullet swept: hit at t=%.3f, contact x=%.2f\\n\", t, bullet.C.X+move.X*t)\n\t}\n}","language":"go","title":"Resolve along the axis of least penetration","walkthrough":"Box A overlaps B by 1 on x and 3 on y, so it is pushed 1 unit left; afterwards the boxes touch and no longer count as overlapping. The circles are 3 apart with radii summing to 4, so A moves back by 1 along the unit direction (0.6, 0.8). The ball's closest point on the crate is (4, 1), one unit from its center, so it moves 0.5 to the right. The bullet ends at x=12, beyond the wall spanning 9 to 11, and the end-position test misses it. Eight sub-steps of 1.5 units find the overlap at x=9 and push the bullet back to 8.50. Sweep treats the bullet as a point against the wall grown by the bullet's half size and returns the entry fraction t=0.708: the same contact at 8.50 from one test instead of eight."},{"body":"Tunneling happens when one tick's motion exceeds the overlap window, the combined thickness of the mover and the obstacle along the direction of motion. Sub-stepping splits the move into pieces no longer than half that combined thickness, so every overlap is seen and the shallow axis still points back toward where the mover came from; its cost grows with speed. A swept test computes the time of impact directly with the slab method: on each axis, find when the moving point enters and leaves the grown box, and a hit is the latest entry before the earliest exit. It is exact and constant-time per obstacle, but with several obstacles you must take the earliest hit and decide what happens to the rest of the motion: stop, slide along the surface or bounce. The cheapest fix is often design: cap speeds, or model bullets as rays.","title":"Tunneling and the two standard fixes"},{"body":"Minimum-axis resolution has a known failure on tile maps. A player sliding along a floor made of separate tiles can reach a seam where the horizontal penetration into the next tile is momentarily smaller than the vertical one, and gets pushed sideways: the character snags on a flat floor. The standard fix for grid worlds is to move along x and resolve x against solid tiles using the sign of the motion, then move along y and resolve y. Each axis is pushed back the way it came, so seams never matter, and landing, ceiling bumps and wall stops fall out of which axis collided. Keep minimum-axis and circle resolution for free-moving objects such as pickups, debris and enemies bumping into each other.","code":"// moveX moves b horizontally and stops it at the near face of any solid it enters.\nfunc moveX(b *AABB, dx float64, solids []AABB) (blocked bool) {\n\tb.C.X += dx\n\tfor _, s := range solids {\n\t\tif _, hit := b.Push(s); !hit {\n\t\t\tcontinue\n\t\t}\n\t\tblocked = true\n\t\tif dx > 0 {\n\t\t\tb.C.X = s.C.X - s.Half.X - b.Half.X\n\t\t} else if dx < 0 {\n\t\t\tb.C.X = s.C.X + s.Half.X + b.Half.X\n\t\t}\n\t}\n\treturn blocked\n}","language":"go","title":"Platformers: move and resolve one axis at a time","walkthrough":"This fragment reuses AABB and Push from the program above and runs in your own project. The overlap test is the same, but the resolution ignores the shallow axis and snaps the box to the near face of the solid, chosen by the sign of dx. A matching moveY does the same vertically and reports a landing when dy is positive in screen coordinates, where y grows downward. Moves longer than a tile still need sub-steps."},{"body":"Collision bugs live at exact boundaries, so test them on purpose: shapes exactly touching (no hit), overlapping by a tiny amount, identical centers (the code must pick a fixed direction rather than divide by zero), a circle whose center is inside the box (the closest point equals the center, so the code falls back to the box rule), zero-length motion in Sweep, and motion parallel to a slab. Every case must give the same answer on every run, which is why these examples print fixed precision; compare floats in tests with a tolerance. Once many bodies interact, resolution order matters too: resolving pairs in a fixed order, such as the sorted pair list of the spatial hash lesson, keeps the outcome deterministic.","title":"Test collisions at the boundaries"}],"takeaway":"Use strict overlap tests for boxes and circles, push along the shallow axis or the line between centers, resolve tile movement one axis at a time, and stop tunneling with sub-steps no longer than half the combined thickness or a swept time-of-impact test.","title":"AABB and circle collisions: detect overlap, push out along the shallow axis, sweep fast movers","unitID":"gamedev-loop","wrongAnswers":["Floating-point rounding in the overlap comparison","Resolving along the minimum axis instead of the center line"]},{"conceptTag":"gamedev.spatial-hash","designGuide":{"cautions":["Map iteration order is random; never derive pair order from it.","Clustered scenes and poor cell sizes degrade toward naive cost."],"cost":"A map or dense array rebuilt every tick plus a mark slice; memory grows with objects times cells touched.","family":"gamedev","flow":["Choose a cell size","Insert by bounding box","Query cells, dedupe","Check pairs with j > i"],"ratings":[],"strengths":["Cuts pair checks from quadratic to near linear in spread-out scenes.","Simple to rebuild every tick and to verify against the naive loop."]},"hint":"The pair (3, 8) is found when object 3 queries and again when object 8 queries.","id":"gamedev.spatial-hash","introduction":"Checking every object against every other costs n(n-1)/2 tests: 124,750 for 500 objects, every tick, and almost all of those pairs are far apart. A broad phase discards distant pairs cheaply so the exact tests from the collision lesson run only on near candidates. A uniform grid stored in a hash map is the simplest broad phase that works well for most 2D games.","nuance":"Neighborhood queries are symmetric, so each pair appears from both objects; keeping only j > i checks it once and also drops the object itself, which every query returns.","objective":"Build a uniform-grid spatial hash, insert objects by bounding box, query neighbors with deduplication, and count pair checks against the naive all-pairs loop.","question":"In the grid pair search, every object queries its own bounds. Why does the loop skip candidates with j <= i?","references":["https://gameprogrammingpatterns.com/spatial-partition.html","https://pkg.go.dev/math/rand/v2#NewPCG","https://pkg.go.dev/math#Floor","https://go.dev/ref/spec#For_statements"],"reviewAnswer":"So each unordered pair is checked once, not twice","reviewPrompt":"Why j > i in the pair loop?","sections":[{"body":"A spatial hash divides the plane into square cells of one size and maps each cell coordinate to the objects touching it. The key is the pair floor(x / size), floor(y / size). Floor matters: converting with int() truncates toward zero, so both -0.5 and 0.5 land in cell 0, the cell at the origin becomes twice as wide as the others, and collisions near negative coordinates start to misbehave in ways that are hard to reproduce. A struct of two ints is a perfectly good Go map key; packing the pair into a uint64 saves a little hashing at the cost of clarity. Choose the cell size from your objects: around the size of a typical object, and at least the largest diameter if every object should touch at most two cells per axis.","title":"Cells, keys and the truncation trap"},{"body":"The program builds a seeded scene of 500 circles with radii between 2 and 8 in an 800 by 600 world. Insert files each object under every cell its bounding box touches. Query walks the cells under a box and returns each object found there exactly once: an object spanning two cells sits in both buckets, so the grid keeps a mark per object and a stamp that increases with every query, which deduplicates without allocating a set. Pair finding queries each object's own bounds and keeps only candidates with a higher index, so every unordered pair is checked once, from its lower-indexed object. The naive loop runs as well, and the two lists of overlapping pairs are compared.","code":"package main\n\nimport (\n\t\"cmp\"\n\t\"fmt\"\n\t\"math\"\n\t\"math/rand/v2\"\n\t\"slices\"\n)\n\ntype Circle struct{ X, Y, R float64 }\n\nfunc overlap(a, b Circle) bool {\n\tdx, dy, rr := a.X-b.X, a.Y-b.Y, a.R+b.R\n\treturn dx*dx+dy*dy < rr*rr\n}\n\ntype cell struct{ X, Y int }\n\n// Grid is a spatial hash: a map from cell coordinates to object indices.\ntype Grid struct {\n\tsize  float64\n\tcells map[cell][]int\n\tmark  []uint32 // mark[i] == stamp: object i already returned by this query\n\tstamp uint32\n\tSeen  int // bucket entries read, duplicates included\n}\n\nfunc NewGrid(size float64, objects int) *Grid {\n\treturn &Grid{size: size, cells: map[cell][]int{}, mark: make([]uint32, objects)}\n}\n\n// key uses Floor so that -0.5 lands in cell -1, not cell 0.\nfunc (g *Grid) key(x, y float64) cell {\n\treturn cell{int(math.Floor(x / g.size)), int(math.Floor(y / g.size))}\n}\n\n// Insert files object i under every cell its bounding box touches.\nfunc (g *Grid) Insert(i int, c Circle) {\n\tlo, hi := g.key(c.X-c.R, c.Y-c.R), g.key(c.X+c.R, c.Y+c.R)\n\tfor y := lo.Y; y <= hi.Y; y++ {\n\t\tfor x := lo.X; x <= hi.X; x++ {\n\t\t\tg.cells[cell{x, y}] = append(g.cells[cell{x, y}], i)\n\t\t}\n\t}\n}\n\n// Query appends each object filed in a cell touched by the box, once.\nfunc (g *Grid) Query(dst []int, x0, y0, x1, y1 float64) []int {\n\tg.stamp++\n\tlo, hi := g.key(x0, y0), g.key(x1, y1)\n\tfor y := lo.Y; y <= hi.Y; y++ {\n\t\tfor x := lo.X; x <= hi.X; x++ {\n\t\t\tfor _, j := range g.cells[cell{x, y}] {\n\t\t\t\tg.Seen++\n\t\t\t\tif g.mark[j] != g.stamp {\n\t\t\t\t\tg.mark[j] = g.stamp\n\t\t\t\t\tdst = append(dst, j)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn dst\n}\n\ntype pair struct{ A, B int }\n\nfunc main() {\n\tconst n, width, height, maxR = 500, 800.0, 600.0, 8.0\n\trng := rand.New(rand.NewPCG(2026, 11)) // fixed seeds: same scene every run\n\tobjs := make([]Circle, n)\n\tfor i := range objs {\n\t\tobjs[i] = Circle{rng.Float64() * width, rng.Float64() * height, 2 + rng.Float64()*(maxR-2)}\n\t}\n\n\tnaiveChecks, naive := 0, []pair{}\n\tfor i := range objs {\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\tnaiveChecks++\n\t\t\tif overlap(objs[i], objs[j]) {\n\t\t\t\tnaive = append(naive, pair{i, j})\n\t\t\t}\n\t\t}\n\t}\n\n\tg := NewGrid(2*maxR, n) // cell edge = largest diameter\n\tfor i, c := range objs {\n\t\tg.Insert(i, c)\n\t}\n\tgridChecks, found, cands := 0, []pair{}, []int{}\n\tfor i, c := range objs {\n\t\tcands = g.Query(cands[:0], c.X-c.R, c.Y-c.R, c.X+c.R, c.Y+c.R)\n\t\tfor _, j := range cands {\n\t\t\tif j <= i { // self, or a pair already handled from j's side\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgridChecks++\n\t\t\tif overlap(c, objs[j]) {\n\t\t\t\tfound = append(found, pair{i, j})\n\t\t\t}\n\t\t}\n\t}\n\tslices.SortFunc(found, func(p, q pair) int {\n\t\treturn cmp.Or(cmp.Compare(p.A, q.A), cmp.Compare(p.B, q.B))\n\t})\n\n\tfmt.Printf(\"%d circles, %d occupied cells of %.0f units\\n\", n, len(g.cells), g.size)\n\tfmt.Printf(\"naive: %d pair checks, %d overlaps\\n\", naiveChecks, len(naive))\n\tfmt.Printf(\"grid: %d bucket reads, %d pair checks, %d overlaps\\n\", g.Seen, gridChecks, len(found))\n\tfmt.Printf(\"same pairs: %t, first %v\\n\", slices.Equal(naive, found), found[0])\n\n\tblast := Circle{400, 300, 40}\n\tnear := g.Query(nil, blast.X-blast.R, blast.Y-blast.R, blast.X+blast.R, blast.Y+blast.R)\n\thits := 0\n\tfor _, j := range near {\n\t\tif overlap(blast, objs[j]) {\n\t\t\thits++\n\t\t}\n\t}\n\tfmt.Printf(\"blast r=%.0f: %d candidates, %d hit\\n\", blast.R, len(near), hits)\n}","language":"go","title":"Insert by bounds, query with a stamp, count the work","walkthrough":"rand.NewPCG(2026, 11) fixes the scene, so the numbers repeat on every run with this toolchain. The naive loop makes 124,750 checks and finds 90 overlaps. The grid reads 2,254 bucket entries, counting duplicates and each object's own entry, and runs only 330 exact checks to find the same 90 pairs; slices.Equal confirms that the sorted lists match. The last query models an explosion of radius 40 at the center of the world: 7 objects are candidates and 4 of them actually intersect the blast."},{"body":"A broad phase produces two different duplicates. The first is one object found in several cells during a single query; the stamp removes it. The second is the pair (i, j) found once from i and again from j; the j > i rule removes it, and also drops the object itself, which every query returns. Miss either and overlaps are reported twice, so collision responses apply twice and objects bounce with double force. Ordering is the subtler issue. Iteration over a Go map is deliberately randomized, so a broad phase that produces pairs by ranging over the cell map yields a different pair order on every run; any resolution that moves objects then depends on that order, and the simulation stops being reproducible. This program never ranges over the map: it walks objects by index and reads cells by key, and it sorts the final list anyway before comparing.","title":"Two kinds of duplicates and one ordering trap"},{"body":"Most games rebuild the grid every tick, because moving objects change cells and incremental updates add bookkeeping that rarely pays off. A fresh map every tick allocates; resetting each bucket to length zero keeps the backing arrays but also keeps keys for cells nobody occupies any more, so clear the map now and then. For a bounded world, a dense grid indexed by row*cols + col avoids hashing entirely and keeps memory predictable. Tune the cell size by measurement: too small and large objects touch many cells, too large and buckets fill until the grid degenerates toward the naive loop. Heavily clustered scenes, such as a crowd packed into one room, defeat any uniform grid; quadtrees or sort-and-sweep along one axis handle those better.","code":"// DenseGrid covers a bounded world; buckets are reused every tick.\ntype DenseGrid struct {\n\tcols, rows int\n\tsize       float64\n\tbuckets    [][]int // index: row*cols + col\n}\n\nfunc (g *DenseGrid) Reset() {\n\tfor i := range g.buckets {\n\t\tg.buckets[i] = g.buckets[i][:0] // keep capacity for the next tick\n\t}\n}\n\nfunc (g *DenseGrid) cell(x, y float64) int {\n\tcol := min(max(int(math.Floor(x/g.size)), 0), g.cols-1)\n\trow := min(max(int(math.Floor(y/g.size)), 0), g.rows-1)\n\treturn row*g.cols + col\n}","language":"go","title":"Grids in production: rebuild, reuse, tune","walkthrough":"This fragment shows the bounded alternative to the map-based Grid and runs in your own project. Reset keeps each bucket's backing array, so after the first few ticks a rebuild allocates nothing. cell clamps coordinates into the world, which is a design decision: objects outside the bounds pile into the edge cells instead of disappearing, and the exact narrow-phase test still decides whether they collide."},{"body":"The strongest test for a broad phase is the one the program already runs: on seeded scenes, the set of overlapping pairs must equal the naive result exactly. Repeat it across several seeds, densities and cell sizes, including objects larger than a cell and objects at negative coordinates, and keep it in the test suite as the oracle for every later optimization. Then benchmark on realistic scenes and record pair checks next to nanoseconds, because the counts explain the timings. A broad phase that is fast but occasionally misses a pair is the kind of bug that surfaces as a bullet passing through an enemy once a week.","title":"Keep the naive loop as the oracle"}],"takeaway":"Bucket objects into cells with floor-based keys, query only nearby cells, deduplicate with a per-query stamp and a lower-index pair rule, never derive pair order from map iteration, and keep the naive loop as the correctness oracle.","title":"A spatial hash for the broad phase: bucket by cell, query neighbors, check each pair once","unitID":"gamedev-loop","wrongAnswers":["Lower-indexed objects were already removed from the grid","Objects with lower indices cannot overlap later ones"]},{"conceptTag":"gamedev.tilemaps-camera","designGuide":{"cautions":["int() truncation misplaces negative coordinates by one tile.","Rounding the camera inside the simulation makes smooth follow stutter."],"cost":"Two small conversion functions and a range calculation per frame; the real cost is discipline about which space every value lives in.","family":"gamedev","flow":["Center on target","Clamp to map bounds","Floor to tile range","Draw range, snap camera"],"ratings":[],"strengths":["Draw cost depends on the view size, not the map size.","One transform pair keeps drawing and picking consistent."]},"hint":"Compare how int() and math.Floor round -0.56.","id":"gamedev.tilemaps-camera","introduction":"The previous unit gave every entity a world position and a fixed-timestep update. A tile map lays a grid over that world, and a camera decides which part of it reaches the screen. Both are small pieces of arithmetic, and most tile-map bugs are one of three mistakes in it: the wrong coordinate space, the wrong rounding or the wrong edge.","nuance":"Go's float-to-int conversion discards the fraction, rounding toward zero, so negative positions land one tile too far right or down; math.Floor returns -1 and the bounds check rejects it.","objective":"Convert between tile, world and screen coordinates, keep a following camera inside the map and compute the exact range of tiles to draw.","question":"A click lands at world x = -9, in the margin left of the map. Why does int(x / 16) report the wrong tile?","references":["https://pkg.go.dev/github.com/hajimehoshi/ebiten/v2#GeoM","https://gameprogrammingpatterns.com/flyweight.html","https://pkg.go.dev/math#Floor"],"reviewAnswer":"int() truncates toward zero, so -0.5 maps to tile 0","reviewPrompt":"Why floor, not int(), for tiles?","sections":[{"body":"Tile coordinates are integer column and row indexes into the map. World coordinates are continuous positions in world pixels: with 16-pixel tiles, tile (c, r) covers x from c*16 up to, but not including, (c+1)*16. Screen coordinates are what the window shows after the camera offset and zoom. The map owns the tile-to-world rule and the camera owns the world-to-screen rule; no other code should do either conversion by hand. Simulation, collision and pathfinding stay in world or tile space. Screen space appears only at the two boundaries where the player meets the game: drawing, and turning a mouse or touch position back into a world point. Store each cell as a small index into a shared tileset rather than as an object with its own image. That is the flyweight pattern: a 40x30 map becomes 1200 bytes instead of 1200 sprite objects, and the tileset is loaded once.","title":"Three coordinate spaces, owned by two types"},{"body":"The program builds a 40x30 map of 16-pixel tiles and shows it through a 640x360 window at zoom 2, which is a 320x180 view in world pixels. It moves the target to the top-left corner, the middle and the bottom-right corner and prints where the camera settled and which tiles intersect the view. It then sends a click through the inverse transform, centers a room smaller than the view, and shows what integer conversion does to a click in the margin beside that room.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nconst tileSize = 16\n\ntype Vec struct{ X, Y float64 }\n\n// TileMap stores one tileset index per cell, row by row.\ntype TileMap struct {\n\tCols, Rows int\n\tTiles      []uint8\n}\n\nfunc (m TileMap) Size() Vec {\n\treturn Vec{float64(m.Cols * tileSize), float64(m.Rows * tileSize)}\n}\n\n// Camera.Pos is the world position of the top-left screen pixel.\ntype Camera struct {\n\tPos              Vec\n\tScreenW, ScreenH float64\n\tZoom             float64\n}\n\nfunc (c Camera) View() Vec { return Vec{c.ScreenW / c.Zoom, c.ScreenH / c.Zoom} }\n\nfunc (c Camera) WorldToScreen(p Vec) Vec {\n\treturn Vec{(p.X - c.Pos.X) * c.Zoom, (p.Y - c.Pos.Y) * c.Zoom}\n}\n\nfunc (c Camera) ScreenToWorld(p Vec) Vec {\n\treturn Vec{p.X/c.Zoom + c.Pos.X, p.Y/c.Zoom + c.Pos.Y}\n}\n\n// Follow centers the target, then keeps the view inside the map.\n// A map smaller than the view is centered instead.\nfunc (c *Camera) Follow(target Vec, m TileMap) {\n\tview, size := c.View(), m.Size()\n\tc.Pos.X = clampAxis(target.X-view.X/2, size.X-view.X)\n\tc.Pos.Y = clampAxis(target.Y-view.Y/2, size.Y-view.Y)\n}\n\nfunc clampAxis(v, limit float64) float64 {\n\tif limit < 0 {\n\t\treturn limit / 2\n\t}\n\treturn min(max(v, 0), limit)\n}\n\nfunc worldToTile(p Vec) (col, row int) {\n\treturn int(math.Floor(p.X / tileSize)), int(math.Floor(p.Y / tileSize))\n}\n\ntype TileRange struct{ MinCol, MaxCol, MinRow, MaxRow int }\n\n// Visible returns the inclusive tile range that touches the view.\nfunc (c Camera) Visible(m TileMap) TileRange {\n\tview := c.View()\n\tminCol, minRow := worldToTile(c.Pos)\n\tmaxCol := int(math.Ceil((c.Pos.X+view.X)/tileSize)) - 1\n\tmaxRow := int(math.Ceil((c.Pos.Y+view.Y)/tileSize)) - 1\n\treturn TileRange{\n\t\tMinCol: max(minCol, 0), MaxCol: min(maxCol, m.Cols-1),\n\t\tMinRow: max(minRow, 0), MaxRow: min(maxRow, m.Rows-1),\n\t}\n}\n\nfunc (r TileRange) Count() int { return (r.MaxCol - r.MinCol + 1) * (r.MaxRow - r.MinRow + 1) }\n\nfunc main() {\n\tlevel := TileMap{Cols: 40, Rows: 30, Tiles: make([]uint8, 40*30)}\n\tcam := Camera{ScreenW: 640, ScreenH: 360, Zoom: 2}\n\tfmt.Printf(\"map %.0fx%.0f px, view %.0fx%.0f px at zoom %.0f\\n\",\n\t\tlevel.Size().X, level.Size().Y, cam.View().X, cam.View().Y, cam.Zoom)\n\n\tfor _, target := range []Vec{{40, 30}, {300, 250}, {630, 470}} {\n\t\tcam.Follow(target, level)\n\t\tr := cam.Visible(level)\n\t\tfmt.Printf(\"target (%.0f,%.0f) camera (%.0f,%.0f) cols %d-%d rows %d-%d draw %d of %d\\n\",\n\t\t\ttarget.X, target.Y, cam.Pos.X, cam.Pos.Y,\n\t\t\tr.MinCol, r.MaxCol, r.MinRow, r.MaxRow, r.Count(), level.Cols*level.Rows)\n\t}\n\n\tclick := Vec{100, 50}\n\tworld := cam.ScreenToWorld(click)\n\tcol, row := worldToTile(world)\n\tback := cam.WorldToScreen(world)\n\tfmt.Printf(\"click (%.0f,%.0f) -> world (%.0f,%.0f) -> tile (%d,%d) -> screen (%.0f,%.0f)\\n\",\n\t\tclick.X, click.Y, world.X, world.Y, col, row, back.X, back.Y)\n\n\troom := TileMap{Cols: 12, Rows: 8, Tiles: make([]uint8, 12*8)}\n\tcam.Follow(Vec{96, 64}, room)\n\tr := cam.Visible(room)\n\tfmt.Printf(\"small room: camera (%.0f,%.0f) cols %d-%d rows %d-%d\\n\",\n\t\tcam.Pos.X, cam.Pos.Y, r.MinCol, r.MaxCol, r.MinRow, r.MaxRow)\n\n\tmargin := cam.ScreenToWorld(Vec{110, 40})\n\tcol, row = worldToTile(margin)\n\tfmt.Printf(\"margin click world (%.0f,%.0f): int() says (%d,%d), floor says (%d,%d)\\n\",\n\t\tmargin.X, margin.Y, int(margin.X/tileSize), int(margin.Y/tileSize), col, row)\n}","language":"go","title":"Follow, clamp and cull with one camera value","walkthrough":"Follow first centers the target (target minus half the view) and then clamps each axis to the range from 0 to mapSize - viewSize, so the corner targets print camera (0,0) and (320,300) instead of showing empty space past the edge. When the map is smaller than the view the limit is negative, and clampAxis returns half of it, which centers the 192x128 room at (-64,-26). Visible floors the top-left corner, takes ceil(edge / tileSize) - 1 for the bottom-right corner and clamps both to the map. A camera at x=140 therefore draws columns 8 to 28: 21 columns, one more than an aligned view, because partial tiles show at both edges. ScreenToWorld divides by the zoom and adds the camera position; WorldToScreen undoes it exactly, which the click line proves by returning to (100,50). The last line is the bug the next section explains."},{"body":"Go's conversion from float to int truncates toward zero, so int(-9.0/16) is 0, not -1. A click in the margin left of a centered room becomes a click on tile (0,0), and an entity standing just west of a chunk boundary is filed under the wrong chunk. math.Floor returns -1, which the bounds check then rejects. The same off-by-one hides at the far edge: a 320-pixel view starting at x=8 touches 21 columns, not 20, and a range computed as start + view / tileSize leaves a strip of unpainted background on the right. Clamping the range to the map is what makes culling safe as well as cheap: the draw loop can index the tile slice directly, because Visible never returns a column outside 0 to Cols-1, whatever the camera does. Keep the camera position as float64 in the simulation so smooth follow and screen shake stay smooth, and round it only at draw time. Pixel art drawn at fractional offsets shimmers and opens one-pixel seams between tiles; snapping the camera, not each tile, keeps neighbors exactly one tile apart.","title":"Floor at the edges, and snap only when drawing"},{"body":"In a real game the same Camera drives Draw. Ebitengine scales the logical screen size returned by Layout to the window, and each DrawImage call takes a GeoM matrix. Translate by the tile position minus the snapped camera, then scale by the zoom. GeoM applies operations in the order you call them, so this is exactly WorldToScreen from the program.","code":"func (g *Game) Layout(outsideW, outsideH int) (int, int) { return 640, 360 }\n\nfunc (g *Game) Draw(screen *ebiten.Image) {\n\tr := g.cam.Visible(g.level)\n\tcamX, camY := math.Floor(g.cam.Pos.X), math.Floor(g.cam.Pos.Y)\n\top := &ebiten.DrawImageOptions{}\n\tfor row := r.MinRow; row <= r.MaxRow; row++ {\n\t\tfor col := r.MinCol; col <= r.MaxCol; col++ {\n\t\t\top.GeoM.Reset()\n\t\t\top.GeoM.Translate(float64(col*tileSize)-camX, float64(row*tileSize)-camY)\n\t\t\top.GeoM.Scale(g.cam.Zoom, g.cam.Zoom)\n\t\t\tscreen.DrawImage(g.tiles[g.level.Tiles[row*g.level.Cols+col]], op)\n\t\t}\n\t}\n}","language":"go","title":"Draw the visible range in Ebitengine","walkthrough":"This fragment needs github.com/hajimehoshi/ebiten/v2 and runs in your own native environment, not in the app. g.tiles holds sub-images cut once from a single tileset image with SubImage at load time, so consecutive draws share one source texture and Ebitengine can merge them into fewer GPU draw calls. One DrawImageOptions value is reset and reused for the whole loop instead of being allocated per tile; the frame-budget lesson measures why that matters. Flooring the camera to whole world pixels means that at zoom 2 every tile lands on an even screen pixel."},{"body":"A camera locked rigidly to the player feels twitchy. Common refinements are a dead zone (move the camera only when the target leaves a central rectangle), look-ahead (offset toward the facing or velocity direction) and smoothing (move a fraction of the remaining distance each tick, which the tweening lesson builds properly). Apply all of them before the clamp so no refinement can push the view past the map edge. Parallax background layers reuse the same camera with its position multiplied by a factor below 1. Large worlds split the map into chunks and cull chunks first, then tiles inside each visible chunk, with the same floor-based range math. Test the camera as a table: targets at all four corners and the center, a map smaller than the view on one axis only, zoom 1, 2 and a fractional zoom such as 1.5, and a property check that every screen pixel converts back to a world point inside the reported tile range.","title":"Camera behavior players notice, and how to test it"}],"takeaway":"Keep the simulation in world space, convert through one camera type, floor (never truncate) from world to tile coordinates, clamp the camera before drawing and clamp the visible range so culling can never index outside the map.","title":"A camera is a coordinate transform: follow the target, clamp to the map, draw only visible tiles","unitID":"gamedev-systems","wrongAnswers":["Float division by 16 loses precision for negative values","The camera offset is applied twice for negative positions"]},{"conceptTag":"gamedev.pathfinding","designGuide":{"cautions":["Manhattan on an 8-way grid overestimates and loses optimality.","An unreachable goal explores every reachable cell; budget it."],"cost":"A heap, two arrays sized to the map and a careful Less method; time grows with the cells expanded times the log of the open-set size.","family":"gamedev","flow":["Push start, h to goal","Pop lowest f, h, seq","Relax open neighbors","Rebuild from parents"],"ratings":[],"strengths":["Optimal paths with far fewer expansions than Dijkstra.","Integer costs and a total order make results replayable."]},"hint":"Consider what a binary heap promises about entries that compare equal.","id":"gamedev.pathfinding","introduction":"Chasing the player in a straight line works until the first wall. Breadth-first search finds a way around but ignores terrain cost; Dijkstra respects cost but explores every cell closer than the goal, in all directions. A* keeps Dijkstra's guarantee while steering the search with an estimate of the remaining distance. Its quality depends on three choices that are easy to get subtly wrong: the cost model, the heuristic and the tie-break.","nuance":"Admissibility guarantees an optimal cost, not a unique route, and a binary heap is not stable; only a total order such as f, then h, then push sequence fixes which equal-cost path wins.","objective":"Implement grid A* with container/heap, choose a heuristic that matches the movement rules, make equal-cost choices deterministic and decide when a flow field beats per-unit searches.","question":"Two routes to the goal have the same cost. What makes an A* implementation keep choosing the same one after a refactor?","references":["https://pkg.go.dev/container/heap","https://www.redblobgames.com/pathfinding/a-star/introduction.html","https://www.redblobgames.com/pathfinding/a-star/implementation.html","https://www.redblobgames.com/pathfinding/tower-defense/"],"reviewAnswer":"Equal-cost paths otherwise depend on incidental order","reviewPrompt":"Why break A* ties explicitly?","sections":[{"body":"For each cell A* tracks g, the cheapest known cost from the start, and h, an estimate of the cost from the cell to the goal. The open set is a priority queue ordered by f = g + h; the search repeatedly expands the lowest-f cell and relaxes its neighbors. If h never overestimates the true remaining cost, it is admissible, and the first time the goal leaves the queue its path is optimal. With h = 0, A* is Dijkstra; a larger admissible h expands fewer cells. The pathfinder should not own the map. It asks a walkability question per cell, so the same search can run against static walls, a door table or a temporary obstacle overlay. Use integer costs, 10 per straight step and 14 per diagonal, so sums are exact and comparisons cannot depend on floating-point rounding.","title":"What A* tracks and what it guarantees"},{"body":"The program parses a small ASCII level, runs a 4-way search with the Manhattan heuristic and an 8-way search with the octile heuristic, and draws each path with asterisks. It then runs the 8-way search with a zero heuristic to compare the work done, and finally seals both gaps in the central wall to show what an unreachable goal costs.","code":"package main\n\nimport (\n\t\"container/heap\"\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n)\n\ntype Point struct{ X, Y int }\n\ntype Grid struct {\n\tW, H  int\n\twalls []bool\n}\n\nfunc ParseGrid(rows []string) (g Grid, start, goal Point) {\n\tg = Grid{W: len(rows[0]), H: len(rows), walls: make([]bool, len(rows[0])*len(rows))}\n\tfor y, row := range rows {\n\t\tfor x, ch := range row {\n\t\t\tswitch ch {\n\t\t\tcase '#':\n\t\t\t\tg.walls[y*g.W+x] = true\n\t\t\tcase 'S':\n\t\t\t\tstart = Point{x, y}\n\t\t\tcase 'G':\n\t\t\t\tgoal = Point{x, y}\n\t\t\t}\n\t\t}\n\t}\n\treturn g, start, goal\n}\n\nfunc (g Grid) Open(p Point) bool {\n\treturn p.X >= 0 && p.Y >= 0 && p.X < g.W && p.Y < g.H && !g.walls[p.Y*g.W+p.X]\n}\n\n// Costs are integers: 10 per straight step, 14 per diagonal (about 10*sqrt2).\nconst straight, diagonal = 10, 14\n\ntype Heuristic func(a, b Point) int\n\nfunc Manhattan(a, b Point) int { return straight * (abs(a.X-b.X) + abs(a.Y-b.Y)) }\n\nfunc Octile(a, b Point) int {\n\tdx, dy := abs(a.X-b.X), abs(a.Y-b.Y)\n\treturn straight*max(dx, dy) + (diagonal-straight)*min(dx, dy)\n}\n\nfunc abs(v int) int {\n\tif v < 0 {\n\t\treturn -v\n\t}\n\treturn v\n}\n\n// node ordering is total: lowest f, then lowest h, then oldest push.\ntype node struct {\n\tp    Point\n\tg, h int\n\tseq  int\n}\n\ntype openSet []*node\n\nfunc (o openSet) Len() int { return len(o) }\nfunc (o openSet) Less(i, j int) bool {\n\ta, b := o[i], o[j]\n\tif a.g+a.h != b.g+b.h {\n\t\treturn a.g+a.h < b.g+b.h\n\t}\n\tif a.h != b.h {\n\t\treturn a.h < b.h\n\t}\n\treturn a.seq < b.seq\n}\nfunc (o openSet) Swap(i, j int) { o[i], o[j] = o[j], o[i] }\nfunc (o *openSet) Push(x any)   { *o = append(*o, x.(*node)) }\nfunc (o *openSet) Pop() any {\n\told := *o\n\tn := old[len(old)-1]\n\t*o = old[:len(old)-1]\n\treturn n\n}\n\n// Fixed neighbor order: E, S, W, N, then diagonals SE, SW, NW, NE.\nvar steps = []Point{{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}}\n\nfunc FindPath(g Grid, start, goal Point, diagonals bool, h Heuristic) (path []Point, cost, expanded int) {\n\tdirs := steps[:4]\n\tif diagonals {\n\t\tdirs = steps\n\t}\n\tbest := make([]int, g.W*g.H) // cheapest known g per cell\n\tfor i := range best {\n\t\tbest[i] = math.MaxInt\n\t}\n\tfrom := make([]Point, g.W*g.H)\n\topen := &openSet{}\n\tseq := 0\n\theap.Push(open, &node{p: start, h: h(start, goal)})\n\tbest[start.Y*g.W+start.X] = 0\n\tfor open.Len() > 0 {\n\t\tcur := heap.Pop(open).(*node)\n\t\tif cur.g != best[cur.p.Y*g.W+cur.p.X] {\n\t\t\tcontinue // stale entry: a cheaper route was pushed later\n\t\t}\n\t\texpanded++\n\t\tif cur.p == goal {\n\t\t\tfor p := goal; p != start; p = from[p.Y*g.W+p.X] {\n\t\t\t\tpath = append(path, p)\n\t\t\t}\n\t\t\tpath = append(path, start)\n\t\t\tfor i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {\n\t\t\t\tpath[i], path[j] = path[j], path[i]\n\t\t\t}\n\t\t\treturn path, cur.g, expanded\n\t\t}\n\t\tfor _, d := range dirs {\n\t\t\tnext := Point{cur.p.X + d.X, cur.p.Y + d.Y}\n\t\t\tif !g.Open(next) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstep := straight\n\t\t\tif d.X != 0 && d.Y != 0 {\n\t\t\t\t// No corner cutting: both orthogonal cells must be open.\n\t\t\t\tif !g.Open(Point{cur.p.X + d.X, cur.p.Y}) || !g.Open(Point{cur.p.X, cur.p.Y + d.Y}) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tstep = diagonal\n\t\t\t}\n\t\t\tng := cur.g + step\n\t\t\ti := next.Y*g.W + next.X\n\t\t\tif ng >= best[i] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbest[i], from[i] = ng, cur.p\n\t\t\tseq++\n\t\t\theap.Push(open, &node{p: next, g: ng, h: h(next, goal), seq: seq})\n\t\t}\n\t}\n\treturn nil, 0, expanded\n}\n\nfunc Render(rows []string, path []Point) []string {\n\tout := make([][]byte, len(rows))\n\tfor y, row := range rows {\n\t\tout[y] = []byte(row)\n\t}\n\tfor _, p := range path {\n\t\tif out[p.Y][p.X] == '.' {\n\t\t\tout[p.Y][p.X] = '*'\n\t\t}\n\t}\n\tlines := make([]string, len(out))\n\tfor y := range out {\n\t\tlines[y] = string(out[y])\n\t}\n\treturn lines\n}\n\nfunc main() {\n\trows := []string{\n\t\t\"S....#........\",\n\t\t\".##..#..####..\",\n\t\t\"..#..#.....#..\",\n\t\t\"..#.....#..#..\",\n\t\t\"..####..#..##.\",\n\t\t\"........#....G\",\n\t}\n\tg, start, goal := ParseGrid(rows)\n\tfor _, run := range []struct {\n\t\tname      string\n\t\tdiagonals bool\n\t\th         Heuristic\n\t\tdraw      bool\n\t}{\n\t\t{\"4-way, Manhattan\", false, Manhattan, true},\n\t\t{\"8-way, octile\", true, Octile, true},\n\t\t{\"8-way, zero (Dijkstra)\", true, func(a, b Point) int { return 0 }, false},\n\t} {\n\t\tpath, cost, expanded := FindPath(g, start, goal, run.diagonals, run.h)\n\t\tfmt.Printf(\"%s: %d steps, cost %d, expanded %d\\n\", run.name, len(path)-1, cost, expanded)\n\t\tif run.draw {\n\t\t\tfmt.Println(strings.Join(Render(rows, path), \"\\n\"))\n\t\t}\n\t}\n\tfor _, p := range []Point{{8, 0}, {8, 2}} {\n\t\tg.walls[p.Y*g.W+p.X] = true // seal both gaps in column 8\n\t}\n\tpath, _, expanded := FindPath(g, start, goal, true, Octile)\n\tfmt.Printf(\"gaps sealed: path found %t, expanded %d\\n\", path != nil, expanded)\n}","language":"go","title":"A* with container/heap and a total order","walkthrough":"openSet implements heap.Interface, and heap.Push and heap.Pop keep it ordered by Less, which compares f, then h, then a sequence number assigned at push time, so no two entries ever compare equal. Instead of a decrease-key operation, a cheaper route simply pushes a new entry; when the outdated entry surfaces later, its g no longer matches best and it is skipped. A diagonal step is allowed only when both orthogonal neighbors are open, so a path never squeezes between two diagonal walls. The 4-way path costs 200 over 20 steps; diagonals cut it to 182 over 17. The zero heuristic finds the same cost but expands 57 cells instead of 43. With both gaps sealed, the search exhausts all 37 reachable cells before it can report that no path exists."},{"body":"Manhattan distance, 10*(dx+dy), is exact on an empty 4-way grid and admissible with walls. On an 8-way grid it overestimates: one diagonal step costs 14, but Manhattan charges 20, so the search can return a path that is not the cheapest. Octile distance, 10*max(dx,dy) + 4*min(dx,dy), is exact on an empty 8-way grid. Euclidean distance is admissible for both but underestimates, so it expands more cells than octile for no benefit on a grid. If some terrain costs less than 10 per step, such as roads, scale the heuristic by the cheapest step cost or it stops being admissible. An inadmissible heuristic is sometimes a deliberate choice: multiplying an admissible h by 1.2 finds paths faster and guarantees a result at most 20 percent longer than optimal, a trade many games accept for background units. Make that a named weight, not an accident of mixing movement rules.","title":"The heuristic must match the movement rules"},{"body":"On a grid many paths share the same cost, so the order of equal-f entries decides which path you get. A binary heap is not stable: entries that compare equal leave in whatever order the heap happens to hold them. The search is still repeatable for one fixed sequence of pushes, but a harmless-looking refactor, such as generating neighbors in another order, reusing a heap between searches or reading blocked cells from a map, silently changes the chosen route. That breaks golden tests, replays that rerun the simulation from recorded inputs, and any lockstep network model where peers must agree. A total order fixes it: lower f first; among equal f, lower h, which prefers entries closer to the goal and usually expands fewer cells; then the push sequence number. Keep the neighbor order in a fixed slice, never a map, and write the ordering rule in a comment, because the chosen path is now part of the contract.","title":"Tie-breaking is part of the result"},{"body":"A* answers one start for one goal. Thirty units converging on a base would run thirty searches over nearly the same cells. A flow field inverts the problem: one breadth-first or Dijkstra pass outward from the goal records, for every reachable cell, the neighbor one step closer, so each unit just follows next[cell] each tick. Its cost scales with the map, not with the number of units, and units spawned anywhere are handled for free. Rebuild it when the goal moves or walls change. For a few long-lived units with different goals, cache A* results keyed by start, goal and a map version counter that increments on every wall change, and revalidate a cached path lazily when its next step becomes blocked. When a search is expensive, give it a budget of expansions per tick and resume it on the next tick rather than letting one search consume the frame.","code":"// BuildFlowField runs one breadth-first search outward from the goal.\n// next[i] is the neighbor one step closer to the goal; dist[i] < 0 means\n// the cell cannot reach the goal at all.\nfunc BuildFlowField(g Grid, goal Point) (next []Point, dist []int) {\n\tnext = make([]Point, g.W*g.H)\n\tdist = make([]int, g.W*g.H)\n\tfor i := range dist {\n\t\tdist[i] = -1\n\t}\n\tdist[goal.Y*g.W+goal.X] = 0\n\tqueue := []Point{goal}\n\tfor len(queue) > 0 {\n\t\tcur := queue[0]\n\t\tqueue = queue[1:]\n\t\tfor _, d := range steps[:4] {\n\t\t\tn := Point{cur.X + d.X, cur.Y + d.Y}\n\t\t\tif !g.Open(n) || dist[n.Y*g.W+n.X] >= 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdist[n.Y*g.W+n.X] = dist[cur.Y*g.W+cur.X] + 1\n\t\t\tnext[n.Y*g.W+n.X] = cur\n\t\t\tqueue = append(queue, n)\n\t\t}\n\t}\n\treturn next, dist\n}","language":"go","title":"Many units, one goal: cache paths or build a flow field","walkthrough":"This fragment reuses Grid, Point and the steps slice from the program above; paste it below FindPath and call it from main to run it in your own native environment. It is a breadth-first search, so it assumes every step costs the same; weighted terrain needs the same loop driven by a heap, as in A*. dist doubles as the visited set and as the answer to whether a unit can reach the goal at all. That matters because the zero value of next would otherwise point every unreachable unit at cell (0,0). On the lesson level it reports a distance of 20 steps from S, matching the 4-way A* path."},{"body":"Keep golden ASCII fixtures like the ones printed above and compare the rendered path, its cost and the expansion count; a jump in expansions exposes a broken heuristic even when the path still looks right. Check that a start equal to the goal returns a one-cell path, that a goal inside a wall or behind a sealed wall returns no path, and that every returned path is contiguous, avoids walls and costs exactly the sum of its steps. For optimality, generate many seeded random maps and assert that the A* cost equals the zero-heuristic cost. Benchmark the worst case, an unreachable goal on the largest map, because that search explores everything; decide in game design whether units should even try, or should first check a cheap connectivity label for the two regions.","title":"Test the search, not the screenshot"}],"takeaway":"Use an admissible heuristic that matches the movement rules, give the open set a total order so equal-cost choices are reproducible, and switch to one shared flow field when many units travel to the same goal.","title":"A* on a grid: a heap, a heuristic that matches the moves, and tie-breaking you can replay","unitID":"gamedev-systems","wrongAnswers":["container/heap keeps equal entries in insertion order","An admissible heuristic guarantees one unique path"]},{"conceptTag":"gamedev.procedural-generation","designGuide":{"cautions":["Map iteration, goroutines or global rand silently break replays.","Floating-point results can differ across architectures through FMA."],"cost":"A few generator constructors and a validation pass; the lasting cost is keeping old generator versions alive while saved seeds depend on them.","family":"gamedev","flow":["Derive stream per system","Draw in fixed order","Smooth into second grid","Validate and fingerprint"],"ratings":[],"strengths":["A 64-bit seed rebuilds the whole level anywhere.","Named streams let systems change without reshuffling others."]},"hint":"Ask which code shares the sequence of values the cave consumes.","id":"gamedev.procedural-generation","introduction":"Procedural generation is only useful when the same seed builds the same world: a player shares a seed, a tester attaches one to a bug report, a replay regenerates the level instead of storing it. That property is not automatic. It depends on who owns each random generator, how many values each system draws and in what order, and whether any code path reaches for a generator nobody seeded.","nuance":"The cave reads the next values of whatever stream it uses; if loot draws from the same stream, every later value moves. A stream derived per system keeps each sequence private, and math/rand/v2 has no global Seed anyway.","objective":"Generate a seeded cave with a math/rand/v2 PCG source, keep each system on its own derived stream and explain why global or shared randomness breaks replays.","question":"A designer adds one loot roll at level start, and every seeded cave changes shape. Which design prevents this?","references":["https://pkg.go.dev/math/rand/v2#NewPCG","https://go.dev/blog/randv2","https://gameprogrammingpatterns.com/double-buffer.html"],"reviewAnswer":"Extra draws in one system cannot shift another's values","reviewPrompt":"Why one RNG stream per system?","sections":[{"body":"A seeded generator is a pure function of its seed and of the sequence of calls made on it. Store a 64-bit seed and a generator version and you can rebuild a whole cave on load, on a server or on a teammate's machine. The contract breaks in three ways: a different seed, which is obvious; different code, such as a tuned constant or a new pass; or a different number or order of draws from the same stream, which is subtle and the usual bug. The last one is why each system needs its own generator. In math/rand/v2, rand.New(rand.NewPCG(seed1, seed2)) returns a *rand.Rand over a PCG source with 128 bits of state, and nothing else in the process can draw from it unless you hand it over.","title":"A seed replaces the content you did not store"},{"body":"The program derives a terrain stream from a world seed and the name \"terrain\", fills a 36x12 grid with 45 percent walls and runs four smoothing passes in which a cell becomes wall when at least five of the nine cells in its 3x3 block are walls. It prints the cave, counts floor regions, regenerates with the same seed, tries the next seed, and then shows what a single extra loot roll does to a shared stream compared with separate streams.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"hash/fnv\"\n\t\"math/rand/v2\"\n\t\"strings\"\n)\n\nconst w, h = 36, 12\n\n// stream derives an independent generator for one named system.\n// The world seed picks the world; the name picks the system's stream.\nfunc stream(worldSeed uint64, name string) *rand.Rand {\n\tf := fnv.New64a()\n\tf.Write([]byte(name))\n\treturn rand.New(rand.NewPCG(worldSeed, f.Sum64()))\n}\n\n// Cave runs a cellular automaton: random fill, then smoothing passes.\nfunc Cave(r *rand.Rand) []bool {\n\twalls := make([]bool, w*h)\n\tfor i := range walls {\n\t\twalls[i] = r.IntN(100) < 45\n\t}\n\tnext := make([]bool, w*h)\n\tfor range 4 {\n\t\tfor y := range h {\n\t\t\tfor x := range w {\n\t\t\t\tedge := x == 0 || y == 0 || x == w-1 || y == h-1\n\t\t\t\tnext[y*w+x] = edge || wallsAround(walls, x, y) >= 5\n\t\t\t}\n\t\t}\n\t\twalls, next = next, walls // double buffer: never read a half-updated grid\n\t}\n\treturn walls\n}\n\n// wallsAround counts walls in the 3x3 block; the border counts as wall.\nfunc wallsAround(walls []bool, cx, cy int) int {\n\tn := 0\n\tfor y := cy - 1; y <= cy+1; y++ {\n\t\tfor x := cx - 1; x <= cx+1; x++ {\n\t\t\tif x < 0 || y < 0 || x >= w || y >= h || walls[y*w+x] {\n\t\t\t\tn++\n\t\t\t}\n\t\t}\n\t}\n\treturn n\n}\n\nfunc Render(walls []bool) string {\n\tvar b strings.Builder\n\tfor y := range h {\n\t\tfor x := range w {\n\t\t\tif walls[y*w+x] {\n\t\t\t\tb.WriteByte('#')\n\t\t\t} else {\n\t\t\t\tb.WriteByte('.')\n\t\t\t}\n\t\t}\n\t\tb.WriteByte('\\n')\n\t}\n\treturn b.String()\n}\n\n// Regions counts connected floor areas with an explicit-stack flood fill.\nfunc Regions(walls []bool) (count, largest int) {\n\tseen := make([]bool, len(walls))\n\tfor start := range walls {\n\t\tif walls[start] || seen[start] {\n\t\t\tcontinue\n\t\t}\n\t\tcount++\n\t\tsize, stack := 0, []int{start}\n\t\tseen[start] = true\n\t\tfor len(stack) > 0 {\n\t\t\ti := stack[len(stack)-1]\n\t\t\tstack = stack[:len(stack)-1]\n\t\t\tsize++\n\t\t\tfor _, d := range [4][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} {\n\t\t\t\tx, y := i%w+d[0], i/w+d[1]\n\t\t\t\tif x < 0 || y < 0 || x >= w || y >= h {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif n := y*w + x; !walls[n] && !seen[n] {\n\t\t\t\t\tseen[n] = true\n\t\t\t\t\tstack = append(stack, n)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlargest = max(largest, size)\n\t}\n\treturn count, largest\n}\n\nfunc fingerprint(s string) uint64 {\n\tf := fnv.New64a()\n\tf.Write([]byte(s))\n\treturn f.Sum64()\n}\n\nfunc main() {\n\tconst seed = 20261118\n\tcave := Cave(stream(seed, \"terrain\"))\n\tfirst := Render(cave)\n\tfmt.Print(first)\n\tregions, largest := Regions(cave)\n\tfmt.Printf(\"floor regions: %d, largest: %d cells\\n\", regions, largest)\n\n\tagain := Render(Cave(stream(seed, \"terrain\")))\n\tfmt.Printf(\"same seed, same map: %t (%016x)\\n\", again == first, fingerprint(first))\n\tother := Render(Cave(stream(seed+1, \"terrain\")))\n\tfmt.Printf(\"next seed, different map: %t (%016x)\\n\", other != first, fingerprint(other))\n\n\t// Shared stream: a new loot roll before generation shifts every later draw.\n\tshared := rand.New(rand.NewPCG(seed, 0))\n\tbefore := Render(Cave(shared))\n\tshared = rand.New(rand.NewPCG(seed, 0))\n\t_ = shared.IntN(6) // the loot system now rolls first\n\tafter := Render(Cave(shared))\n\tfmt.Printf(\"shared stream, map survives a new loot roll: %t\\n\", before == after)\n\n\t// Separate streams: the loot roll consumes only the loot stream.\n\tloot := stream(seed, \"loot\")\n\t_ = loot.IntN(6)\n\tisolated := Render(Cave(stream(seed, \"terrain\")))\n\tfmt.Printf(\"separate streams, map survives a new loot roll: %t\\n\", isolated == first)\n}","language":"go","title":"A cellular-automaton cave from a named stream","walkthrough":"stream hashes the system name with FNV-1a into seed2, so \"terrain\" and \"loot\" get unrelated sequences from one world seed and adding a system never requires renumbering the others. Cave draws exactly one IntN per cell in row-major order, then smooths into a second buffer and swaps the two. Reading and writing one grid would let already-updated cells bias their neighbors, and the result would depend on scan direction. Border cells are forced to wall so the cave is closed. Regions flood-fills floor cells with an explicit stack and finds 2 regions, the main cave and a sealed pocket on the left, which the last section deals with. The fingerprints are FNV hashes of the printed map, handy as golden values in tests. One IntN(6) before generation on a shared stream changes the whole map; on separate streams it changes nothing."},{"body":"The top-level functions in math/rand/v2, such as rand.IntN, draw from a process-wide source that is seeded randomly at startup and has no Seed function, so a map built with them can never be rebuilt. A seedable shared generator fails in the way the shared-stream line shows: any new call anywhere, from a particle effect, a library or a debug overlay, shifts every value drawn after it. Concurrency makes it worse. A *rand.Rand is not safe for concurrent use, and even behind a mutex, which goroutine draws next depends on the scheduler, so the world changes from run to run. The rule is ownership: each system or chunk gets its own *rand.Rand, passed explicitly as a parameter or held in a field and used by one goroutine. Name streams after what they generate, such as terrain, loot, enemies and weather, and derive them all from the single world seed the player sees.","title":"Why global and shared randomness break replays"},{"body":"Draw the same number of values in the same order on every run: loop over slices and fixed coordinate ranges, never over a map, whose iteration order Go randomizes on purpose. For streamed or endless worlds, derive a stream per chunk from the world seed and the chunk coordinates, so chunk (12, -3) is identical whether the player reaches it first or last. Prefer integer rules like the automaton above. Floating-point noise is reproducible on one platform, but the Go specification allows fused multiply-add, which compilers use on architectures such as arm64, so an arm64 client and an amd64 server can differ in the last bits; when generation must match bit for bit, use integer or fixed-point math or force rounding with explicit float64 conversions. Store a generator version beside the seed and keep old generators while saves reference them. The PCG source implements MarshalBinary and UnmarshalBinary, so a mid-run generator state can go into a save file. Finally, PCG itself is a fixed algorithm, but helpers such as IntN are library code; golden fingerprints in tests tell you at upgrade time whether a toolchain change altered any world.","title":"Rules that keep generation reproducible"},{"body":"A random fill does not promise a playable level. The cave printed above has two regions, and a player spawned in the small pocket is trapped. Make validation part of generation: flood-fill from the spawn point, fill unreachable pockets with wall or carve a tunnel to them, require a minimum floor area and confirm that the exit is reachable with the pathfinding code from the previous lesson. When a candidate fails, retry deterministically by deriving the next attempt from the seed and the attempt number, and cap the attempts so a pathological seed fails loudly instead of looping. Test with a few thousand seeds in CI: assert the invariants on each one, record the fingerprints of a handful as golden values, and keep every seed that ever produced a broken map as a permanent regression fixture.","title":"Validate the world before the player sees it"}],"takeaway":"Give every generating system its own seeded *rand.Rand derived from the world seed, never draw from global or shared generators in generation code, and validate and fingerprint the result so a seed stays a reliable save format.","title":"Reproducible worlds: one seed, one random stream per system, and no global rand","unitID":"gamedev-systems","wrongAnswers":["Reseeding the global generator with the world seed first","Switching the source from PCG to ChaCha8"]},{"conceptTag":"gamedev.tweening-animation","designGuide":{"cautions":["Wall-clock animation diverges from the simulation and replays.","Pointer targets outlive destroyed entities; use IDs."],"cost":"A few small structs and pure easing functions; motion granularity is one tick unless Draw interpolates between ticks.","family":"gamedev","flow":["Store from, to, duration","Step once per tick","Value from elapsed/total","Retarget on interrupt"],"ratings":[],"strengths":["Pause, slow motion and replays work without special cases.","Values land exactly on the target; nothing drifts."]},"hint":"Look at the value shown on the tick right after the cancel.","id":"gamedev.tweening-animation","introduction":"A panel slides in, a coin bounces, a character cycles through four walking frames. The tempting implementation reads time.Now in Draw and computes progress from it. That ties animation to the wall clock: it keeps running while the game is paused, it behaves differently at 60 Hz and 144 Hz, and a replay cannot reproduce it. The fixed-timestep loop from the previous unit already provides a better clock: the tick.","nuance":"Starting from the current value means the first eased step moves only a fraction away from where the panel already is; both alternatives teleport it to an end point first, which is the 37.5 to 75.0 jump in the program.","objective":"Drive easing curves, chained and retargeted tweens and sprite animation clips from tick counts so motion is deterministic, pausable and free of jumps.","question":"A menu is closed while its opening animation is halfway done. Which approach avoids a visible jump?","references":["https://gafferongames.com/post/fix_your_timestep/","https://gameprogrammingpatterns.com/update-method.html","https://pkg.go.dev/github.com/hajimehoshi/ebiten/v2#SetTPS"],"reviewAnswer":"Retarget: start a new tween from the current value","reviewPrompt":"Interrupted tween: what to do?","sections":[{"body":"Model a tween as a value holding a start, an end, a duration in ticks, the elapsed tick count and an easing function. Update calls Step once per tick and Draw reads Value. Because Value is computed from elapsed / duration instead of adding a small delta every tick, it cannot accumulate rounding error, and the last tick lands exactly on the target. Pausing means not calling Step, slow motion means stepping every other tick, and a replay reproduces every intermediate value. An easing function maps linear progress t from 0 to 1 onto eased progress with f(0) = 0 and f(1) = 1. It changes when the motion happens, not where it ends. Some easings leave the 0 to 1 range on purpose: outBack overshoots to give a panel a small bounce before it settles.","title":"A tween is data: from, to, duration and elapsed ticks"},{"body":"The program samples four easings over a 10-tick tween, plays a two-step chain, cancels a slide partway through and compares a naive restart with a retarget, and finally picks sprite frames for a looping walk clip and a one-shot attack clip at selected ticks. Every value prints with fixed precision, so the output is identical on every platform.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n// An Ease maps progress t in [0,1] to eased progress; f(0)=0 and f(1)=1.\ntype Ease func(t float64) float64\n\nfunc Linear(t float64) float64 { return t }\n\nfunc OutCubic(t float64) float64 {\n\tu := 1 - t\n\treturn 1 - u*u*u\n}\n\nfunc InOutQuad(t float64) float64 {\n\tif t < 0.5 {\n\t\treturn 2 * t * t\n\t}\n\tu := 2 - 2*t\n\treturn 1 - u*u/2\n}\n\n// OutBack overshoots past 1 before settling, like a panel that bounces.\nfunc OutBack(t float64) float64 {\n\tconst c1 = 1.70158\n\tu := t - 1\n\treturn 1 + u*u*((c1+1)*u+c1)\n}\n\n// Tween is plain data advanced once per simulation tick.\ntype Tween struct {\n\tFrom, To float64\n\tDuration int // in ticks\n\tElapsed  int\n\tEase     Ease\n}\n\nfunc (tw *Tween) Step() {\n\tif tw.Elapsed < tw.Duration {\n\t\ttw.Elapsed++\n\t}\n}\n\nfunc (tw Tween) Done() bool { return tw.Elapsed >= tw.Duration }\n\n// Value is computed from Elapsed, so it never accumulates rounding drift.\nfunc (tw Tween) Value() float64 {\n\tif tw.Duration <= 0 {\n\t\treturn tw.To\n\t}\n\tt := float64(tw.Elapsed) / float64(tw.Duration)\n\treturn tw.From + (tw.To-tw.From)*tw.Ease(t)\n}\n\n// Retarget starts a new tween from wherever the old one is now.\nfunc Retarget(cur Tween, to float64, ticks int, ease Ease) Tween {\n\treturn Tween{From: cur.Value(), To: to, Duration: ticks, Ease: ease}\n}\n\n// Chain plays tweens back to back; each starts where the previous ended.\ntype Chain struct {\n\tSteps []Tween\n\tindex int\n}\n\nfunc (c *Chain) Step() {\n\tif c.Steps[c.index].Done() && c.index < len(c.Steps)-1 {\n\t\tc.index++\n\t}\n\tc.Steps[c.index].Step()\n}\n\nfunc (c *Chain) Value() float64 { return c.Steps[c.index].Value() }\n\nfunc (c *Chain) Done() bool { return c.index == len(c.Steps)-1 && c.Steps[c.index].Done() }\n\n// Clip picks a sprite frame from the ticks elapsed since the clip started.\ntype Clip struct {\n\tFrames        []int // indexes into a sprite sheet\n\tTicksPerFrame int\n\tLoop          bool\n}\n\nfunc (c Clip) Frame(elapsed int) int {\n\ti := elapsed / c.TicksPerFrame\n\tif c.Loop {\n\t\ti %= len(c.Frames)\n\t} else {\n\t\ti = min(i, len(c.Frames)-1)\n\t}\n\treturn c.Frames[i]\n}\n\nfunc (c Clip) Finished(elapsed int) bool {\n\treturn !c.Loop && elapsed >= len(c.Frames)*c.TicksPerFrame\n}\n\nfunc main() {\n\teases := []struct {\n\t\tname string\n\t\tf    Ease\n\t}{{\"linear\", Linear}, {\"outCubic\", OutCubic}, {\"inOutQuad\", InOutQuad}, {\"outBack\", OutBack}}\n\tfmt.Printf(\"%4s %9s %9s %9s %9s\\n\", \"tick\", \"linear\", \"outCubic\", \"inOutQuad\", \"outBack\")\n\tfor tick := 0; tick <= 10; tick += 2 {\n\t\trow := []string{fmt.Sprintf(\"%4d\", tick)}\n\t\tfor _, e := range eases {\n\t\t\ttw := Tween{From: 0, To: 1, Duration: 10, Elapsed: tick, Ease: e.f}\n\t\t\trow = append(row, fmt.Sprintf(\"%9.3f\", tw.Value()))\n\t\t}\n\t\tfmt.Println(strings.Join(row, \" \"))\n\t}\n\n\tchain := Chain{Steps: []Tween{\n\t\t{From: 0, To: 100, Duration: 4, Ease: OutCubic},\n\t\t{From: 100, To: 40, Duration: 3, Ease: InOutQuad},\n\t}}\n\tsamples := []string{fmt.Sprintf(\"%.1f\", chain.Value())}\n\tfor !chain.Done() {\n\t\tchain.Step()\n\t\tsamples = append(samples, fmt.Sprintf(\"%.1f\", chain.Value()))\n\t}\n\tfmt.Println(\"chain:\", strings.Join(samples, \" \"))\n\n\tslide := Tween{From: 0, To: 100, Duration: 8, Ease: Linear}\n\tfor range 3 {\n\t\tslide.Step()\n\t}\n\tnaive := Tween{From: 100, To: 0, Duration: 4, Ease: Linear}\n\tnaive.Step()\n\tfmt.Printf(\"cancel at %.1f: naive restart jumps to %.1f\\n\", slide.Value(), naive.Value())\n\tback := Retarget(slide, 0, 4, Linear)\n\tsamples = samples[:0]\n\tfor !back.Done() {\n\t\tback.Step()\n\t\tsamples = append(samples, fmt.Sprintf(\"%.1f\", back.Value()))\n\t}\n\tfmt.Println(\"retarget from current value:\", strings.Join(samples, \" \"))\n\n\twalk := Clip{Frames: []int{4, 5, 6, 7}, TicksPerFrame: 6, Loop: true}\n\tattack := Clip{Frames: []int{8, 9, 10}, TicksPerFrame: 4}\n\tfor _, c := range []struct {\n\t\tname string\n\t\tclip Clip\n\t}{{\"walk\", walk}, {\"attack\", attack}} {\n\t\tvar frames []string\n\t\tfor _, t := range []int{0, 5, 6, 11, 12, 23, 24} {\n\t\t\tframes = append(frames, fmt.Sprint(c.clip.Frame(t)))\n\t\t}\n\t\tfmt.Printf(\"%s frames at ticks 0 5 6 11 12 23 24: %s (finished at 24: %t)\\n\",\n\t\t\tc.name, strings.Join(frames, \" \"), c.clip.Finished(24))\n\t}\n}","language":"go","title":"Ease, chain, retarget and animate in one program","walkthrough":"The table shows the character of each curve: outCubic covers almost half the distance in the first fifth of the time, inOutQuad starts and ends slowly, and outBack peaks at 1.099 before settling at exactly 1.000. Chain advances the current tween and moves to the next one only after the current one reports Done, so 100.0 appears once and the second step starts from it: eight samples for 4 + 3 ticks. The cancelled slide is at 37.5 after three of eight ticks. Restarting a tween from the original end point jumps to 75.0 on the next tick, while Retarget starts from the current value and glides down to 0.0. Clip.Frame divides elapsed ticks by ticks per frame. The walk loop wraps with a modulo, so tick 24 shows frame 4 again; the one-shot attack clamps to its last frame and reports Finished at tick 24, which a state machine can use to leave the attack state."},{"body":"Interruptions are where tweens go wrong. When a menu closes while it is still opening, there are three policies: hold (stop where it is), complete (jump to the end) and retarget (start a new tween from the current value toward the new target). Retarget is almost always what players expect; jumping to an end point first is the visible snap the program prints. Make the policy explicit in the API instead of letting each caller overwrite fields. Chains need a rule for the boundary tick: show either the last value of one tween or the first value of the next, never both and never neither. Completion callbacks are convenient, but a callback that starts another tween on the same object while the chain is still iterating is a classic source of skipped steps; prefer reporting Done and letting the owner decide. Refer to tween targets by entity ID resolved each tick, not by pointer, so a tween whose entity was destroyed finds nothing and ends instead of writing into a recycled slot.","title":"Cancelling and chaining without visible jumps"},{"body":"A clip is a list of sprite-sheet indexes and a ticks-per-frame rate. The current frame is computed from the ticks since the clip started, so an entity stores only the clip and its start tick, not a frame counter that must be incremented and reset correctly. Switching from walk to attack records a new start tick; switching to the clip that is already playing must not, or a held key restarts the walk cycle on every tick. Gameplay events tied to animation, such as the frame where a sword connects, belong in the simulation as tick offsets within the clip, not in Draw, so they happen on the same tick in a replay and on a server. In Ebitengine, Update runs at the tick rate (60 per second unless SetTPS changes it) while Draw can run at the display rate. That is the right split: step tweens and clips in Update, read them in Draw, and interpolate between the previous and current tick with the fixed-timestep alpha if motion looks steppy on fast displays.","title":"Sprite frames are a function of elapsed ticks"},{"body":"Because every value is a function of the tick, tests need no timers and no sleeps. Assert f(0) = 0 and f(1) = 1 for each easing, compare curves at fixed ticks against golden values formatted to three decimals like the table above, and check monotonicity wherever a curve promises it. Cover the edges: a zero-duration tween reports its target immediately, stepping past the end stays at the end, a retarget never moves the value on the retarget tick itself, and a one-shot clip with a single frame finishes after exactly its ticks-per-frame. If designers tune durations in seconds, convert them to ticks once at load time with an explicit rounding rule and test that the conversion is stable for your tick rate.","title":"Test animation as a table of samples"}],"takeaway":"Advance tweens and sprite clips by simulation ticks, compute values from elapsed ticks instead of accumulating deltas, retarget from the current value when interrupted, and keep animation-driven gameplay events in Update.","title":"Tweens and sprite frames advance with the simulation tick, not the wall clock","unitID":"gamedev-systems","wrongAnswers":["Restart the close tween from the menu's fully open position","Finish the open tween instantly, then play the close tween"]},{"conceptTag":"gamedev.save-games","designGuide":{"cautions":["os.Rename is not atomic on non-Unix platforms.","Checksums catch corruption, not deliberate tampering."],"cost":"A struct and a migration function per format version, one fixture per release, and a few extra system calls on every save.","family":"gamedev","flow":["Read version first","Migrate step by step","Decode strict, validate","Write temp, sync, rename"],"ratings":[],"strengths":["Old saves keep loading as the format evolves.","A crash during saving never destroys progress."]},"hint":"Picture the file if power fails halfway through the write.","id":"gamedev.save-games","introduction":"A save file outlives the build that wrote it, sits in a folder the player can edit and gets shared on forums. A loader that unmarshals it straight into game state will eventually meet a save from an older version, a save from a newer version, a file truncated by a crash and a hand-edited file with 999 health. Each of those needs a deliberate answer, and none of them should be a panic.","nuance":"On POSIX file systems rename swaps the directory entry in one step, so readers see the complete old save or the complete synced new one; writing in place truncates first and can leave a torn file.","objective":"Design a versioned JSON save format, migrate v1 saves to v2, reject unknown fields and out-of-range values, and replace a save file without ever leaving it half-written.","question":"Why does the save code write to a temporary file in the same directory and then rename it over the old save?","references":["https://pkg.go.dev/encoding/json#Decoder.DisallowUnknownFields","https://pkg.go.dev/os#Rename","https://pkg.go.dev/os#CreateTemp","https://go.dev/doc/security/fuzz/"],"reviewAnswer":"A crash leaves the old or new file, never half of each","reviewPrompt":"Why temp file + rename for saves?","sections":[{"body":"Old files: a field was renamed or restructured, the new struct silently decodes it as zero, and a v1 player loads with 0 health. Newer files: a player downgrades or copies a save from a newer build, the old build drops fields it does not know and then overwrites the file with less data than it read. Torn files: the game crashes or the device loses power during a write, and the only save is part old and part new. Crafted files: someone sets an inventory count to a billion or adds an item that does not exist, and the game indexes past a slice or grants a debug item. The answers are a version field read first, pure migration functions, strict decoding followed by explicit validation, and an atomic replace when writing.","title":"Four ways a naive loader fails"},{"body":"The program loads a v1 save (flat hp, a position array and a list of item names) and migrates it to v2 (structured health, a position object and item stacks). It loads a valid v2 save, then feeds the loader six bad files: an unknown field, impossible health, a position outside the map, an unknown item, a newer version and a file with a second JSON value appended. Finally it writes the last good save atomically into a fresh directory under os.TempDir, reloads it and confirms that no temporary file was left behind.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nconst (\n\tcurrentVersion = 2\n\tmaxSaveBytes   = 64 << 10\n\tmapW, mapH     = 640.0, 480.0\n)\n\n// SaveV1 is the format shipped by the first release: flat fields, one string per item.\ntype SaveV1 struct {\n\tVersion int        `json:\"version\"`\n\tName    string     `json:\"name\"`\n\tHP      int        `json:\"hp\"`\n\tPos     [2]float64 `json:\"pos\"`\n\tItems   []string   `json:\"items\"`\n}\n\n// Save is the current format (version 2).\ntype Save struct {\n\tVersion   int      `json:\"version\"`\n\tName      string   `json:\"name\"`\n\tHealth    Health   `json:\"health\"`\n\tPosition  Position `json:\"position\"`\n\tInventory []Stack  `json:\"inventory\"`\n}\n\ntype Health struct {\n\tCurrent int `json:\"current\"`\n\tMax     int `json:\"max\"`\n}\n\ntype Position struct {\n\tX float64 `json:\"x\"`\n\tY float64 `json:\"y\"`\n}\n\ntype Stack struct {\n\tItem  string `json:\"item\"`\n\tCount int    `json:\"count\"`\n}\n\nvar catalog = map[string]bool{\"potion\": true, \"rope\": true, \"lantern\": true}\n\n// migrateV1 is a pure function: old struct in, new struct out.\nfunc migrateV1(old SaveV1) Save {\n\ts := Save{\n\t\tVersion:  2,\n\t\tName:     old.Name,\n\t\tHealth:   Health{Current: old.HP, Max: 100}, // v1 had an implicit cap of 100\n\t\tPosition: Position{X: old.Pos[0], Y: old.Pos[1]},\n\t}\n\tfor _, item := range old.Items { // group in first-seen order, not map order\n\t\tfound := false\n\t\tfor i := range s.Inventory {\n\t\t\tif s.Inventory[i].Item == item {\n\t\t\t\ts.Inventory[i].Count++\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\ts.Inventory = append(s.Inventory, Stack{Item: item, Count: 1})\n\t\t}\n\t}\n\treturn s\n}\n\nfunc decodeStrict(data []byte, v any) error {\n\tdec := json.NewDecoder(bytes.NewReader(data))\n\tdec.DisallowUnknownFields()\n\treturn dec.Decode(v)\n}\n\nfunc Load(r io.Reader) (s Save, fromVersion int, err error) {\n\tdata, err := io.ReadAll(io.LimitReader(r, maxSaveBytes+1))\n\tif err != nil {\n\t\treturn Save{}, 0, err\n\t}\n\tif len(data) > maxSaveBytes {\n\t\treturn Save{}, 0, errors.New(\"save is larger than 64 KiB\")\n\t}\n\tvar head struct {\n\t\tVersion int `json:\"version\"`\n\t}\n\tif err := json.Unmarshal(data, &head); err != nil { // also rejects trailing data\n\t\treturn Save{}, 0, err\n\t}\n\tswitch {\n\tcase head.Version == 1:\n\t\tvar old SaveV1\n\t\tif err := decodeStrict(data, &old); err != nil {\n\t\t\treturn Save{}, 1, err\n\t\t}\n\t\ts = migrateV1(old)\n\tcase head.Version == currentVersion:\n\t\tif err := decodeStrict(data, &s); err != nil {\n\t\t\treturn Save{}, head.Version, err\n\t\t}\n\tcase head.Version > currentVersion:\n\t\treturn Save{}, head.Version, fmt.Errorf(\"version %d is newer than this build supports (%d)\", head.Version, currentVersion)\n\tdefault:\n\t\treturn Save{}, head.Version, fmt.Errorf(\"unknown version %d\", head.Version)\n\t}\n\tif err := Validate(s); err != nil {\n\t\treturn Save{}, head.Version, err\n\t}\n\treturn s, head.Version, nil\n}\n\n// Validate checks every invariant the game relies on after loading.\nfunc Validate(s Save) error {\n\tif s.Name == \"\" || len(s.Name) > 24 {\n\t\treturn errors.New(\"name must be 1 to 24 bytes\")\n\t}\n\tif s.Health.Max < 1 || s.Health.Max > 500 || s.Health.Current < 0 || s.Health.Current > s.Health.Max {\n\t\treturn fmt.Errorf(\"health %d/%d out of range\", s.Health.Current, s.Health.Max)\n\t}\n\tif !(s.Position.X >= 0 && s.Position.X < mapW && s.Position.Y >= 0 && s.Position.Y < mapH) {\n\t\treturn fmt.Errorf(\"position (%.1f,%.1f) is outside the map\", s.Position.X, s.Position.Y)\n\t}\n\tif len(s.Inventory) > 20 {\n\t\treturn errors.New(\"more than 20 inventory stacks\")\n\t}\n\tfor _, st := range s.Inventory {\n\t\tif !catalog[st.Item] {\n\t\t\treturn fmt.Errorf(\"unknown item %q\", st.Item)\n\t\t}\n\t\tif st.Count < 1 || st.Count > 99 {\n\t\t\treturn fmt.Errorf(\"stack of %d %s out of range\", st.Count, st.Item)\n\t\t}\n\t}\n\treturn nil\n}\n\n// WriteAtomic leaves either the old file or the complete new one, never half of each.\nfunc WriteAtomic(path string, s Save) (n int, err error) {\n\tdata, err := json.MarshalIndent(s, \"\", \"  \")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttmp, err := os.CreateTemp(filepath.Dir(path), \".save-*.tmp\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\ttmp.Close()\n\t\t\tos.Remove(tmp.Name())\n\t\t}\n\t}()\n\tif n, err = tmp.Write(data); err != nil {\n\t\treturn 0, err\n\t}\n\tif err = tmp.Sync(); err != nil {\n\t\treturn 0, err\n\t}\n\tif err = tmp.Close(); err != nil {\n\t\treturn 0, err\n\t}\n\treturn n, os.Rename(tmp.Name(), path)\n}\n\nfunc describe(s Save) string {\n\tvar items []string\n\tfor _, st := range s.Inventory {\n\t\titems = append(items, fmt.Sprintf(\"%s x%d\", st.Item, st.Count))\n\t}\n\treturn fmt.Sprintf(\"%s health %d/%d at (%.1f,%.1f) [%s]\", s.Name,\n\t\ts.Health.Current, s.Health.Max, s.Position.X, s.Position.Y, strings.Join(items, \", \"))\n}\n\nfunc main() {\n\tinputs := []string{\n\t\t`{\"version\":1,\"name\":\"scout\",\"hp\":42,\"pos\":[120.5,64],\"items\":[\"potion\",\"rope\",\"potion\"]}`,\n\t\t`{\"version\":2,\"name\":\"scout\",\"health\":{\"current\":42,\"max\":100},\"position\":{\"x\":120.5,\"y\":64},\"inventory\":[{\"item\":\"lantern\",\"count\":1}]}`,\n\t\t`{\"version\":2,\"name\":\"scout\",\"health\":{\"current\":42,\"max\":100},\"position\":{\"x\":1,\"y\":1},\"inventory\":[],\"godMode\":true}`,\n\t\t`{\"version\":2,\"name\":\"scout\",\"health\":{\"current\":999,\"max\":100},\"position\":{\"x\":1,\"y\":1},\"inventory\":[]}`,\n\t\t`{\"version\":2,\"name\":\"scout\",\"health\":{\"current\":5,\"max\":100},\"position\":{\"x\":-40,\"y\":1},\"inventory\":[]}`,\n\t\t`{\"version\":2,\"name\":\"scout\",\"health\":{\"current\":5,\"max\":100},\"position\":{\"x\":1,\"y\":1},\"inventory\":[{\"item\":\"debug-key\",\"count\":1}]}`,\n\t\t`{\"version\":3,\"name\":\"scout\"}`,\n\t\t`{\"version\":2}{\"version\":2}`,\n\t}\n\tvar last Save\n\tfor _, in := range inputs {\n\t\ts, from, err := Load(strings.NewReader(in))\n\t\tif err != nil {\n\t\t\tfmt.Println(\"reject:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"load v%d as v%d: %s\\n\", from, s.Version, describe(s))\n\t\tlast = s\n\t}\n\n\tdir, err := os.MkdirTemp(\"\", \"savegame-\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\tpath := filepath.Join(dir, \"slot1.json\")\n\tn, err := WriteAtomic(path, last)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treloaded, _, err := Load(f)\n\tf.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tleftovers, _ := filepath.Glob(filepath.Join(dir, \".save-*.tmp\"))\n\tfmt.Printf(\"atomic write: %d bytes, reload matches: %t, temp files left: %d\\n\",\n\t\tn, describe(reloaded) == describe(last), len(leftovers))\n}","language":"go","title":"Decode the version, migrate, then validate","walkthrough":"Load caps the input at 64 KiB with io.LimitReader before parsing anything. json.Unmarshal into a struct holding only the version reads the version and, because Unmarshal requires exactly one JSON value, also rejects the file with trailing data; a json.Decoder alone would stop after the first value and never notice it. The switch then decodes with a Decoder whose DisallowUnknownFields turns godMode into an error instead of silently ignoring it. migrateV1 is a pure function that groups items into stacks in first-seen order rather than through a map, so its output is stable. Validate checks every invariant the game relies on; the negated range test for position also rejects NaN produced by a buggy migration. WriteAtomic writes a temporary file in the destination directory, syncs it, closes it and renames it over the target, and the deferred cleanup removes the temporary file if any step fails."},{"body":"Each release that changes the format gets a new struct and one function from the previous version to the next. Loading a v1 file in a v4 build runs v1 to v2, v2 to v3 and v3 to v4, so each migration is written and tested once against its own fixtures and never needs to know about later versions. Migrations choose defaults explicitly: v1 had no maximum health, so the function writes 100 rather than letting a zero value slip through. Refuse versions newer than the build supports, because a downgraded game that loads a v3 file into v2 structs and saves it back destroys progress. Do not rewrite the original file on load; write the migrated save on the next normal save through the atomic path, and keep the previous file as a backup slot until the new one has loaded successfully once. Note that encoding/json matches field names case-insensitively and lets a repeated key overwrite the earlier one; the strict JSON lesson shows the encoding/json/v2 options that reject both when a format needs it.","title":"Migrate forward in small, pure steps"},{"body":"Writing a save in place truncates the file first, so a crash mid-write leaves neither version. Writing a temporary file in the same directory and renaming it over the old one gives readers either the complete old file or the complete new one, because on POSIX file systems rename replaces the directory entry in one step. The temporary file must live in the same directory, since a rename across file systems fails. Call Sync before Close so the bytes are durable before the name points at them, and on Unix also sync the directory if the rename itself must survive a power cut. The os.Rename documentation states that on non-Unix platforms it is not atomic even within one directory, so a Windows build should keep a backup slot and verify the new file on load. Console and mobile platforms usually provide save APIs with their own guarantees; prefer them there.","code":"// After os.Rename succeeds on Unix, persist the directory entry itself.\ndir, err := os.Open(filepath.Dir(path))\nif err != nil {\n\treturn err\n}\ndefer dir.Close()\nreturn dir.Sync()","language":"go","title":"Atomic replace: what rename does and does not promise","walkthrough":"This fragment belongs at the end of a function like WriteAtomic, runs in your own native environment and applies to Unix systems. Opening the parent directory and calling Sync asks the file system to persist the directory entry that rename changed; without it, a power loss right after the rename can bring back the old name on some file systems. It does not replace the Sync on the file itself, which persists the contents."},{"body":"Decoding proves only that the bytes matched the struct shape. Validation proves the game can use the result: ranges for every number, existence for every reference such as item IDs or level names, limits on every collection, and cross-field rules such as current health at most maximum health. Decide per field whether to reject the save or repair it with a logged clamp; rejecting is safer for anything that indexes memory, repairing is kinder for cosmetic settings. A checksum detects accidental corruption but is not tamper protection, because any key shipped in the client can be extracted; competitive or economy data belongs on a server. Keep a fixture directory with one real save from every released version and load all of them in CI, then fuzz the loader with those fixtures as the seed corpus.","code":"func FuzzLoad(f *testing.F) {\n\tfor _, data := range fixtureSaves(f) { // one real save per released version\n\t\tf.Add(data)\n\t}\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\ts, _, err := Load(bytes.NewReader(data))\n\t\tif err == nil {\n\t\t\tif verr := Validate(s); verr != nil {\n\t\t\t\tt.Fatalf(\"Load accepted an invalid save: %v\", verr)\n\t\t\t}\n\t\t}\n\t})\n}","language":"go","title":"Validate after decoding, and test the loader like a parser","walkthrough":"This test fragment lives in a _test.go file in your own module and runs with go test -fuzz=FuzzLoad on your machine; fixtureSaves is your helper that reads the fixture directory. The property is simple and strong: for any bytes, Load either returns an error or returns a save that passes Validate, and it never panics, hangs or allocates without bound. Crashing inputs found by the fuzzer are written under testdata/fuzz and become permanent regression cases."}],"takeaway":"Read the version first, migrate with pure per-version functions, decode strictly and validate every invariant, refuse newer formats, and replace saves by renaming a synced temporary file from the same directory.","title":"Save files are untrusted input: version them, migrate forward, validate and write atomically","unitID":"gamedev-systems","wrongAnswers":["It stops players from editing the save between sessions","os.WriteFile cannot replace a file that already exists"]},{"conceptTag":"gamedev.authoritative-server","designGuide":{"cautions":["A blocking broadcast lets one slow client stall the tick.","Strict rules without tolerance punish lossy connections."],"cost":"Server CPU for every player's simulation, a round trip of latency the client must hide, and a validation rule for every action.","family":"gamedev","flow":["Stamp sender identity","Drain and sort inputs","Validate, then apply","Publish copied snapshot"],"ratings":[],"strengths":["A modified client cannot teleport or exceed the speed cap.","One owner goroutine removes locks from game logic."]},"hint":"Which side decides where a modified client ends up?","id":"gamedev.authoritative-server","introduction":"In a multiplayer game every client is a program you do not control. If clients report their own positions, a modified client can teleport, fly or walk through walls, and the server has no grounds to refuse. An authoritative server inverts that: clients send what the player wants to do, the server decides what happens, and everyone receives the server's version of the world. Goroutines and channels fit this shape well, provided exactly one goroutine owns the state.","nuance":"With directions the server applies its own speed cap, collision and bounds, so a hacked client can at most choose where to walk; a reported position would let the client decide the outcome.","objective":"Build a server tick loop in which one goroutine owns all game state, clients send inputs over channels, movement is validated against speed and rate limits, and snapshots are copies in a deterministic order.","question":"Why does the authoritative server accept movement directions from clients instead of positions?","references":["https://gafferongames.com/post/what_every_programmer_needs_to_know_about_game_networking/","https://gafferongames.com/post/udp_vs_tcp/","https://pkg.go.dev/net#PacketConn","https://pkg.go.dev/sync#WaitGroup.Go"],"reviewAnswer":"Inputs with sequence numbers; the server computes moves","reviewPrompt":"What should a game client send?","sections":[{"body":"An input message carries a sequence number and a desired direction. It has no position, health or score field, so there is nothing to forge. The server tick applies inputs with its own speed, its own collision rules from the previous unit and its own map, then publishes a snapshot. Ownership is the other half of the design: the world lives in one goroutine. Network readers and timers talk to it through channels, and nothing outside that goroutine holds a pointer into the world. That removes locks from game logic, makes each tick a sequential function you can review and test, and gives every rule a single place to be enforced. The sender's identity comes from the connection, never from a field in the payload.","title":"Clients send intent; the server computes outcomes"},{"body":"The program starts a server goroutine that owns three players, creates one Session per simulated client and runs four ticks. In each tick every client goroutine sends its inputs concurrently; the main goroutine waits for all sends, asks the server for a tick and prints the snapshot. Player 1 walks right, player 2 uses keyboard diagonals and then turns, and player 3 cheats with an oversized direction, three moves in one tick, a replayed sequence number, a NaN direction and a forged player ID.","code":"package main\n\nimport (\n\t\"cmp\"\n\t\"fmt\"\n\t\"math\"\n\t\"slices\"\n\t\"strings\"\n\t\"sync\"\n)\n\nconst (\n\tspeed = 4.0   // world units per tick, decided by the server\n\tarena = 100.0 // the world is [0, arena] on both axes\n)\n\n// Input carries intent only. There is no position field to trust or forge.\ntype Input struct {\n\tPlayer int // stamped by the session, never read from the payload\n\tSeq    int\n\tDX, DY float64\n}\n\ntype PlayerState struct {\n\tID   int\n\tX, Y float64\n\tAck  int // last input sequence the server has consumed\n}\n\ntype Snapshot struct {\n\tTick    int\n\tPlayers []PlayerState\n}\n\ntype player struct {\n\tid, lastSeq, movedTick int\n\tx, y                   float64\n}\n\n// Server state is touched only by the goroutine running loop.\ntype Server struct {\n\tinputs  chan Input\n\tticks   chan chan Snapshot\n\tplayers []*player\n\tpending []Input\n\ttick    int\n\tnotes   []string\n}\n\nfunc NewServer(spawns map[int][2]float64, ids []int) *Server {\n\ts := &Server{inputs: make(chan Input), ticks: make(chan chan Snapshot)}\n\tfor _, id := range ids {\n\t\ts.players = append(s.players, &player{id: id, x: spawns[id][0], y: spawns[id][1]})\n\t}\n\treturn s\n}\n\nfunc (s *Server) loop(done chan<- struct{}) {\n\tdefer close(done)\n\tfor {\n\t\tselect {\n\t\tcase in := <-s.inputs:\n\t\t\ts.pending = append(s.pending, in)\n\t\tcase reply, ok := <-s.ticks:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\treply <- s.step()\n\t\t}\n\t}\n}\n\nfunc (s *Server) step() Snapshot {\n\ts.tick++\n\t// Arrival order depends on the scheduler; the server imposes its own.\n\tslices.SortFunc(s.pending, func(a, b Input) int {\n\t\treturn cmp.Or(cmp.Compare(a.Player, b.Player), cmp.Compare(a.Seq, b.Seq))\n\t})\n\tfor _, in := range s.pending {\n\t\ts.apply(in)\n\t}\n\ts.pending = s.pending[:0]\n\tsnap := Snapshot{Tick: s.tick}\n\tfor _, p := range s.players {\n\t\tsnap.Players = append(snap.Players, PlayerState{ID: p.id, X: p.x, Y: p.y, Ack: p.lastSeq})\n\t}\n\treturn snap\n}\n\nfunc (s *Server) apply(in Input) {\n\ti := slices.IndexFunc(s.players, func(p *player) bool { return p.id == in.Player })\n\tif i < 0 {\n\t\treturn\n\t}\n\tp := s.players[i]\n\tif in.Seq <= p.lastSeq {\n\t\ts.note(in, \"old or duplicate sequence dropped\")\n\t\treturn\n\t}\n\tp.lastSeq = in.Seq\n\tif p.movedTick == s.tick {\n\t\ts.note(in, \"second move in one tick dropped\")\n\t\treturn\n\t}\n\tlength := math.Hypot(in.DX, in.DY)\n\tif math.IsNaN(length) || math.IsInf(length, 0) {\n\t\ts.note(in, \"non-finite direction rejected\")\n\t\treturn\n\t}\n\tdx, dy := in.DX, in.DY\n\tif length > 1 {\n\t\tdx, dy = dx/length, dy/length\n\t\t// A keyboard diagonal arrives as (1,1); anything longer is no real controller.\n\t\tif length > math.Sqrt2+0.001 {\n\t\t\ts.note(in, fmt.Sprintf(\"direction length %.1f clamped to 1\", length))\n\t\t}\n\t}\n\tp.x = min(max(p.x+dx*speed, 0), arena)\n\tp.y = min(max(p.y+dy*speed, 0), arena)\n\tp.movedTick = s.tick\n}\n\nfunc (s *Server) note(in Input, msg string) {\n\ts.notes = append(s.notes, fmt.Sprintf(\"  tick %d p%d seq %d: %s\", s.tick, in.Player, in.Seq, msg))\n}\n\n// Session stands in for one authenticated connection.\ntype Session struct {\n\tid  int\n\tout chan<- Input\n}\n\nfunc (c Session) Send(in Input) {\n\tin.Player = c.id // whatever the client wrote here is overwritten\n\tc.out <- in\n}\n\nfunc main() {\n\tids := []int{1, 2, 3}\n\tsrv := NewServer(map[int][2]float64{1: {10, 10}, 2: {50, 50}, 3: {90, 10}}, ids)\n\tdone := make(chan struct{})\n\tgo srv.loop(done)\n\n\tnan := math.NaN()\n\tscript := [][][]Input{ // per tick, per player\n\t\t{{{Seq: 1, DX: 1}}, {{Seq: 1, DX: 1, DY: 1}}, {{Seq: 1, DX: 10}}},\n\t\t{{{Seq: 2, DX: 1}}, {{Seq: 2, DX: 1, DY: 1}}, {{Seq: 2, DX: 1}, {Seq: 3, DX: 1}, {Seq: 4, DX: 1}}},\n\t\t{{{Seq: 3, DX: 1}}, {{Seq: 3, DY: -1}}, {{Seq: 2, DX: 1}, {Seq: 5, DX: nan}}},\n\t\t{{{Seq: 4, DX: 1}}, {{Seq: 4, DY: -1}}, {{Seq: 6, DX: 1, Player: 1}}},\n\t}\n\tfor _, perPlayer := range script {\n\t\tvar wg sync.WaitGroup\n\t\tfor i, inputs := range perPlayer {\n\t\t\tsession := Session{id: ids[i], out: srv.inputs}\n\t\t\twg.Go(func() {\n\t\t\t\tfor _, in := range inputs {\n\t\t\t\t\tsession.Send(in)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\twg.Wait() // every send has been received by the server goroutine\n\n\t\treply := make(chan Snapshot)\n\t\tsrv.ticks <- reply\n\t\tsnap := <-reply\n\t\tvar parts []string\n\t\tfor _, p := range snap.Players {\n\t\t\tparts = append(parts, fmt.Sprintf(\"p%d (%.1f,%.1f) ack %d\", p.ID, p.X, p.Y, p.Ack))\n\t\t}\n\t\tfmt.Printf(\"tick %d: %s\\n\", snap.Tick, strings.Join(parts, \" | \"))\n\t}\n\tclose(srv.ticks)\n\t<-done\n\tfmt.Println(\"violations:\")\n\tfmt.Println(strings.Join(srv.notes, \"\\n\"))\n}","language":"go","title":"A tick loop with validation and deterministic order","walkthrough":"Inputs travel over an unbuffered channel, so each Send completes only when the server goroutine has received the value, and wg.Wait therefore proves that every input is in pending before the tick request is sent. Arrival order still depends on the scheduler, so step sorts by player and sequence before applying anything, and the output is identical on every run. apply drops a sequence at or below the last one seen, allows one move per player per tick, rejects non-finite directions and normalizes any direction longer than 1, logging only lengths that no real controller produces. Dropped extras still advance the ack so the client stops resending them. Positions are clamped to the arena, which is why player 3 stops at 100.0. Session overwrites Player, so player 3's attempt to send as player 1 just moves player 3. Snapshots copy values into PlayerState, so no client can alias server memory."},{"body":"Every rule needs a tolerance chosen with real networks in mind. Packets get duplicated and reordered, so an old sequence number is dropped quietly rather than treated as an attack. A burst of inputs after a lag spike is normal: a production server usually queues a few inputs per player and applies them over the next ticks, dropping only beyond that budget, whereas this program drops extras immediately to stay short. Normalizing direction vectors means a gamepad, a keyboard and a hacked client all move at the same maximum speed without the server guessing intent. Record violations with player, tick and sequence, and act on rates over time rather than on one event, because a single odd input is far more often a bug or a bad connection than a cheat. Never use a client-reported position even as a hint; if client and server disagree, the server is right and the client is corrected, which is the subject of the next lesson.","title":"Validation rules that do not punish honest players"},{"body":"The program drives ticks by hand to stay deterministic. A real server replaces the tick request with a time.Ticker and broadcasts each snapshot to per-client channels. The broadcast must never wait for a slow client: a full channel means that client misses this snapshot and gets the next one, which is harmless when each snapshot carries complete state rather than a delta.","code":"func (s *Server) Run(ctx context.Context) {\n\tticker := time.NewTicker(time.Second / 30)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase in := <-s.inputs:\n\t\t\ts.pending = append(s.pending, in)\n\t\tcase c := <-s.joins:\n\t\t\ts.clients = append(s.clients, c)\n\t\tcase <-ticker.C:\n\t\t\tsnap := s.step()\n\t\t\tfor _, c := range s.clients {\n\t\t\t\tselect {\n\t\t\t\tcase c.snapshots <- snap:\n\t\t\t\tdefault:\n\t\t\t\t\tc.dropped++ // slow client: skip it, the next snapshot supersedes this one\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}","language":"go","title":"The production loop: a ticker, one select and non-blocking fan-out","walkthrough":"This fragment runs in your own native environment; its ticks come from the wall clock, so its output is not reproducible the way the program's is. Joins arrive as messages in the same select, so the clients slice is touched only by the owner goroutine, and leaves would work the same way. Each client has a small buffered snapshots channel drained by its own writer goroutine that encodes and sends; all writers read the same snapshot, so treat it as immutable once published. A time.Ticker drops ticks when the receiver falls behind instead of queueing them, so measure each tick's duration and alert when it approaches the interval."},{"body":"The tick loop does not care whether inputs come from an in-process Session, UDP datagrams or WebSocket messages. Fast-paced games usually prefer UDP because a lost packet should not hold newer inputs back the way in-order TCP delivery does. The reader goroutine does the untrusted-input work: size limits, decoding, mapping the sender to an authenticated session, and dropping instead of blocking when the server is busy.","code":"func readInputs(conn net.PacketConn, sessions *Sessions, inputs chan<- Input) error {\n\tbuf := make([]byte, 512)\n\tfor {\n\t\tn, addr, err := conn.ReadFrom(buf)\n\t\tif err != nil {\n\t\t\treturn err // closed during shutdown, or a real error\n\t\t}\n\t\tid, ok := sessions.Verify(addr, buf[:n]) // token or MAC from the handshake\n\t\tif !ok {\n\t\t\tcontinue // unknown sender: no state change and no reply\n\t\t}\n\t\tin, err := decodeInput(buf[:n]) // fixed layout, length checked\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tin.Player = id\n\t\tselect {\n\t\tcase inputs <- in:\n\t\tdefault:\n\t\t\tsessions.CountDrop(id) // server busy: drop, never stall the reader\n\t\t}\n\t}\n}","language":"go","title":"A real transport feeds the same channel","walkthrough":"Run this fragment in your own environment with a conn from net.ListenPacket(\"udp\", \":7777\"); Sessions, decodeInput and the handshake are yours to define. A source address alone is not authentication, because UDP source addresses can be spoofed, so Verify checks a per-session token or message authentication code agreed during an authenticated connect. Ignoring unknown senders without replying keeps the server from becoming a traffic amplifier. The buffer is reused across reads, which is safe because decodeInput copies values into an Input before the next ReadFrom. A WebSocket transport, which needs a third-party package because the standard library has none, would feed the same channel."},{"body":"Most server logic lives in step, a function of world state and a batch of inputs. Test it directly with tables of inputs and expected snapshots, including the cheats from the program, duplicated and reordered sequences, players joining and leaving between ticks, and inputs for unknown players. Run the goroutine wrapper under the race detector to prove nothing else touches the world, and fuzz decodeInput with arbitrary bytes. Then add a few integration tests over a loopback socket with injected latency and loss; they are slower and noisier, but they catch framing and shutdown bugs. This model runs in one process. A production server adds authentication, matchmaking, persistence, interest management so each client receives only nearby entities, and metrics for tick duration and per-client drops.","title":"Test the tick, not the network"}],"takeaway":"Let one goroutine own the world, accept only intent with sequence numbers, take identity from the connection, validate direction, rate and order every tick, sort inputs before applying them, and publish copied snapshots without blocking on slow clients.","title":"An authoritative server owns the world in one goroutine and accepts only validated intent","unitID":"gamedev-systems","wrongAnswers":["Directions are smaller to encode, which is the main reason","Directions let clients keep moving while the server is busy"]},{"conceptTag":"gamedev.client-prediction","designGuide":{"cautions":["Prediction needs identical movement code on both sides.","Remote players are shown in the past; hits need lag compensation."],"cost":"A pending-input buffer, a snapshot buffer and replay work proportional to the round-trip time on every snapshot.","family":"gamedev","flow":["Predict and buffer input","Reset to server snapshot","Replay inputs after ack","Interpolate remote players"],"ratings":[],"strengths":["Local movement responds on the same tick as the input.","Corrections are limited to real server disagreement."]},"hint":"The server has not applied some of the inputs yet; which ones still matter?","id":"gamedev.client-prediction","introduction":"The authoritative server from the previous lesson is fair but feels slow. With 50 ms of latency each way, a player presses right and nothing moves for a tenth of a second. Client-side prediction runs the same movement rule locally so the press responds at once, reconciliation fixes the prediction when the server disagrees, and interpolation shows other players smoothly, slightly in the past. They solve three different problems with three different pieces of state.","nuance":"Inputs 4 to 8 are still in flight and the server will apply them; replaying them on top of the authoritative state predicts where the server will be and corrects only real disagreements, such as the closed door.","objective":"Hide round-trip latency by predicting local movement, reconcile with acknowledged server snapshots by replaying pending inputs, and draw remote players by interpolating a snapshot buffer.","question":"A snapshot arrives with the server position and ack = 3 while the client has already sent inputs up to 8. What should the client do?","references":["https://gafferongames.com/post/snapshot_interpolation/","https://gafferongames.com/post/state_synchronization/","https://gafferongames.com/post/what_every_programmer_needs_to_know_about_game_networking/"],"reviewAnswer":"Reset to server state, replay inputs after the ack","reviewPrompt":"Reconcile after a snapshot how?","sections":[{"body":"Prediction needs the local player's predicted state and a buffer of inputs that were sent but not yet acknowledged. Reconciliation needs each snapshot to carry the server's state for this player plus the last input sequence the server applied, the ack. Interpolation needs a short buffer of snapshots of the remote entities, each tagged with its server tick. The local player is drawn at the predicted present; everyone else is drawn at a deliberate point in the past, where two real snapshots surround the render time. Mixing those up causes familiar bugs: predicting remote players makes them jitter and snap whenever they change direction, and interpolating your own character makes the controls feel delayed.","title":"Three techniques, three pieces of client state"},{"body":"The program simulates both ends in one loop, with a one-way latency of 3 ticks and a snapshot every 2 ticks. The client presses right for ten ticks. At server tick 5 a door at x = 6 closes, which the client cannot predict. A second player runs right for five ticks and then turns back. Each snapshot arrival prints the reconciliation, and the remote lines show what the client draws for the other player next to what was true at that moment and what is true now.","code":"package main\n\nimport \"fmt\"\n\nconst (\n\tlatency     = 3 // one-way delay in ticks, in both directions\n\tsnapEvery   = 2 // the server sends a snapshot every second tick\n\tinterpDelay = 2 // remote entities are drawn this far behind the newest server time\n\tdoorX       = 6.0\n)\n\ntype Input struct {\n\tSeq int\n\tDX  float64\n}\n\ntype Snapshot struct {\n\tTick       int\n\tX          float64 // this client's player, authoritative\n\tAck        int     // last input sequence the server applied\n\tDoorClosed bool\n\tRemoteX    float64 // another player, for interpolation\n}\n\n// Move is the single movement rule compiled into both client and server.\nfunc Move(x float64, in Input, doorClosed bool) float64 {\n\tnext := x + in.DX\n\tif doorClosed && x <= doorX && next > doorX {\n\t\tnext = doorX\n\t}\n\treturn next\n}\n\ntype Client struct {\n\tX          float64\n\tpending    []Input // sent but not yet acknowledged, oldest first\n\tdoorClosed bool\n\tremote     []Snapshot\n}\n\nfunc (c *Client) Predict(in Input) {\n\tc.pending = append(c.pending, in)\n\tc.X = Move(c.X, in, c.doorClosed)\n}\n\n// Reconcile rewinds to the server's state and replays unacknowledged inputs.\nfunc (c *Client) Reconcile(s Snapshot) (replayed int, before float64) {\n\tbefore = c.X\n\tc.X, c.doorClosed = s.X, s.DoorClosed\n\tkeep := c.pending[:0]\n\tfor _, in := range c.pending {\n\t\tif in.Seq > s.Ack {\n\t\t\tkeep = append(keep, in)\n\t\t}\n\t}\n\tc.pending = keep\n\tfor _, in := range c.pending {\n\t\tc.X = Move(c.X, in, c.doorClosed)\n\t}\n\tc.remote = append(c.remote, s)\n\treturn len(c.pending), before\n}\n\n// RemoteAt interpolates between the two buffered snapshots around time t.\nfunc (c *Client) RemoteAt(t float64) float64 {\n\tfor len(c.remote) > 2 && float64(c.remote[1].Tick) <= t {\n\t\tc.remote = c.remote[1:] // older snapshots can never be needed again\n\t}\n\ta := c.remote[0]\n\tif len(c.remote) == 1 || t <= float64(a.Tick) {\n\t\treturn a.RemoteX\n\t}\n\tb := c.remote[1]\n\tif t >= float64(b.Tick) {\n\t\treturn b.RemoteX // no newer data: hold rather than guess\n\t}\n\talpha := (t - float64(a.Tick)) / float64(b.Tick-a.Tick)\n\treturn a.RemoteX + (b.RemoteX-a.RemoteX)*alpha\n}\n\ntype Server struct {\n\ttick       int\n\tx          float64\n\tack        int\n\tdoorClosed bool\n\tremoteX    float64\n}\n\nfunc (s *Server) Step(arrived []Input) {\n\ts.tick++\n\tif s.tick == 5 {\n\t\ts.doorClosed = true // an event the client cannot predict\n\t}\n\tfor _, in := range arrived {\n\t\tif in.Seq > s.ack {\n\t\t\ts.x = Move(s.x, in, s.doorClosed)\n\t\t\ts.ack = in.Seq\n\t\t}\n\t}\n\tif s.tick <= 5 {\n\t\ts.remoteX += 2 // the other player runs right, then turns back\n\t} else {\n\t\ts.remoteX -= 2\n\t}\n}\n\nfunc (s *Server) Snapshot() Snapshot {\n\treturn Snapshot{Tick: s.tick, X: s.x, Ack: s.ack, DoorClosed: s.doorClosed, RemoteX: s.remoteX}\n}\n\n// packet is a message on a link with a fixed delivery tick.\ntype packet[T any] struct {\n\tat int\n\tv  T\n}\n\nfunc deliver[T any](queue []packet[T], now int) (rest []packet[T], due []T) {\n\tfor _, p := range queue {\n\t\tif p.at == now {\n\t\t\tdue = append(due, p.v)\n\t\t} else {\n\t\t\trest = append(rest, p)\n\t\t}\n\t}\n\treturn rest, due\n}\n\nfunc main() {\n\tsrv := &Server{remoteX: 10}\n\tcl := &Client{}\n\tvar toServer []packet[Input]\n\tvar toClient []packet[Snapshot]\n\tvar remoteLines []string\n\thistory := []float64{srv.remoteX} // server-side truth per tick, for comparison only\n\n\tfor tick := 1; tick <= 17; tick++ {\n\t\tvar inputs []Input\n\t\ttoServer, inputs = deliver(toServer, tick)\n\t\tsrv.Step(inputs)\n\t\thistory = append(history, srv.remoteX)\n\t\tif tick%snapEvery == 0 {\n\t\t\ttoClient = append(toClient, packet[Snapshot]{tick + latency, srv.Snapshot()})\n\t\t}\n\n\t\tvar snaps []Snapshot\n\t\ttoClient, snaps = deliver(toClient, tick)\n\t\tfor _, s := range snaps {\n\t\t\treplayed, before := cl.Reconcile(s)\n\t\t\tdoor := \"open\"\n\t\t\tif s.DoorClosed {\n\t\t\t\tdoor = \"closed\"\n\t\t\t}\n\t\t\tfmt.Printf(\"t=%d snapshot@%d x=%.1f ack=%d door %s: replay %d -> %.1f (was %.1f, corrected %.1f)\\n\",\n\t\t\t\ttick, s.Tick, s.X, s.Ack, door, replayed, cl.X, before, before-cl.X)\n\t\t}\n\t\tif tick <= 10 {\n\t\t\tin := Input{Seq: tick, DX: 1}\n\t\t\tcl.Predict(in)\n\t\t\ttoServer = append(toServer, packet[Input]{tick + latency, in})\n\t\t}\n\t\tif tick >= 8 && tick <= 11 {\n\t\t\trenderAt := float64(tick - latency - interpDelay)\n\t\t\tremoteLines = append(remoteLines, fmt.Sprintf(\"t=%d remote drawn at server time %.0f: %.1f (true then %.1f, live now %.1f)\",\n\t\t\t\ttick, renderAt, cl.RemoteAt(renderAt), history[int(renderAt)], srv.remoteX))\n\t\t}\n\t}\n\tfor _, line := range remoteLines {\n\t\tfmt.Println(line)\n\t}\n\tfmt.Printf(\"after the last ack: client %.1f, server %.1f, pending %d\\n\", cl.X, srv.x, len(cl.pending))\n}","language":"go","title":"A deterministic network with fixed latency","walkthrough":"Predict appends the input to pending and moves immediately with the shared Move function. Reconcile resets to the snapshot's position and door state, keeps only inputs after the ack and replays them. Until the door closes the replay lands exactly on the prediction, so the correction is 0.0. At t=9 the snapshot from server tick 6 reports x=3.0, ack 3 and a closed door; replaying inputs 4 to 8 stops at the door, so the predicted 8.0 is corrected by 2.0 and later predictions stay at 6.0. The remote player is drawn at server time t - latency - interpDelay. At t=10 that is time 5, between the snapshots for ticks 4 and 6, which are both 18.0, so the true peak of 20.0 never appears: interpolation smooths over events that fall between snapshots. After the last ack, pending is empty and client and server agree."},{"body":"Snapping to the server position without a replay would discard every input still in flight and pull the character back by a full round trip on every snapshot. Replaying pending inputs on top of the authoritative state keeps corrections small: only the part the server actually disagreed with changes. That works only if client and server run the same movement code, which is easy in Go when both binaries import one simulation package. Bound the pending buffer to a few hundred milliseconds of inputs and treat overflow as a broken connection. Ignore any snapshot older than one already applied; this program never needs that check because its link never reorders. Keep the simulation state snapped to the corrected value, but let the rendered position chase it over a few frames, so a 2-unit correction looks like a slight drift rather than a teleport, and snap the rendered position too when the error is large, such as after a respawn.","title":"Reconcile by replaying, then smooth what the player sees"},{"body":"The client never sees other players' inputs, so it cannot predict them well. Instead it draws them at a render time behind the newest snapshot and interpolates between the two snapshots that bracket it. The delay must cover the snapshot interval plus network jitter; many games use two intervals so that one lost packet does not empty the buffer, while this program uses one to keep the output short. When the buffer runs dry, hold the last position or extrapolate for a short, capped time, then hold. The delay has a visible cost: you see opponents where they were, so a shot aimed at them would miss on the server unless the server performs lag compensation, rewinding other players to the moment the shooter saw before testing the hit. That decision is a fairness trade-off between shooter and target, and it belongs on the server, never in the client.","title":"Remote players live in the past on purpose"},{"body":"Prediction tolerates small divergence because reconciliation corrects it. Lockstep networking, where peers exchange only inputs, does not: it needs bit-identical simulation on every machine, which in Go means iterating slices instead of maps, avoiding goroutine-dependent order and remembering that floating-point fusion can differ between arm64 and amd64 builds. Test netcode the way this program runs: a simulated link with configurable latency, jitter, loss and reordering driven by a seeded generator, with no sockets and no sleeps. Assert convergence, meaning that after inputs stop and messages drain, client and server agree and pending is empty; assert zero corrections when no server-only event happens; and assert bounded corrections when one does. Then add adversarial schedules: a snapshot lost right before the door event, two snapshots arriving in one tick and a snapshot older than one already applied.","title":"How much determinism you need, and how to test it"}],"takeaway":"Predict the local player with shared movement code, keep unacknowledged inputs, reconcile by resetting to the server state and replaying inputs after the ack, and draw remote players interpolated between buffered snapshots at a fixed delay.","title":"Client prediction replays unacknowledged inputs; remote players are interpolated from the past","unitID":"gamedev-systems","wrongAnswers":["Keep its prediction, since the snapshot is already old","Snap to the server position and discard inputs 4 to 8"]},{"conceptTag":"gamedev.frame-budget","designGuide":{"cautions":["Non-zero allocation counts change between Go releases.","sync.Pool may drop pooled objects at any GC cycle."],"cost":"Scratch fields on the world, capacity planning at level load, and code that is slightly less obvious than allocating fresh values.","family":"gamedev","flow":["Budget from refresh rate","Count allocs per update","Reuse loop-owned storage","Profile, then tune GC"],"ratings":[],"strengths":["A zero-allocation assertion catches regressions in CI.","Loop-owned buffers are deterministic and cache-friendly."]},"hint":"Think about which number a test can assert reliably across Go releases.","id":"gamedev.frame-budget","introduction":"At 60 frames per second each frame has about 16.6 ms for input, simulation, drawing and whatever the runtime needs. Go's garbage collector runs concurrently, but its work is paid for by your program: the more a game allocates per frame, the more often a cycle starts and the more CPU the collector takes from the loop. The useful goal is not zero allocations ever; it is an update that allocates nothing in steady state, verified by a number a test can check.","nuance":"Allocation rate drives how often GC cycles start and how much assist work the loop pays; an update that allocates nothing in steady state removes that pressure, and asserting exactly zero stays valid when releases change non-zero counts.","objective":"Turn refresh rates into frame budgets, count allocations per update with testing.AllocsPerRun, remove per-frame slices, maps, closures and strings, and profile a game loop with pprof and execution traces.","question":"What allocation target should a game's per-frame update have, and how do you keep it there?","references":["https://pkg.go.dev/testing#AllocsPerRun","https://go.dev/doc/gc-guide","https://go.dev/doc/diagnostics","https://pkg.go.dev/runtime/trace#FlightRecorder"],"reviewAnswer":"Zero in steady state, enforced by an AllocsPerRun test","reviewPrompt":"Goal for allocations per update?","sections":[{"body":"Divide one second by the refresh rate: about 16.7 ms at 60 Hz, 8.3 ms at 120 Hz and 6.9 ms at 144 Hz. Ebitengine calls Update at the tick rate and Draw once per displayed frame, and both share that budget with the graphics driver and the operating system. A frame that misses its deadline is a visible hitch, and players notice a single 30 ms spike more than a steady 10 ms average. Allocation feeds that risk. The collector paces cycles by heap growth, so a loop that allocates a few megabytes per second starts cycles regularly; during a cycle, background workers take a share of the CPU and goroutines that keep allocating are charged assist work, which lands directly in your update. Reducing the allocation rate is therefore the first lever, and GOGC or GOMEMLIMIT tuning, covered by the GC budget lesson, comes after it.","title":"Where the 16.6 ms goes"},{"body":"testing.AllocsPerRun runs a function once to warm up, counts heap allocations over the requested number of runs and returns the integer average, with GOMAXPROCS set to 1 during the measurement. It works outside tests too, so the program uses it on paired implementations: a visibility query written the obvious way and one that reuses storage, deferred hit effects as closures and as values, and HUD text rebuilt every update versus cached. The two versions in each pair produce the same result; only their allocation behavior differs.","code":"package main\n\nimport (\n\t\"cmp\"\n\t\"fmt\"\n\t\"slices\"\n\t\"sort\"\n\t\"strconv\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype Entity struct {\n\tID    int\n\tX, Y  float64\n\tAlive bool\n\tHP    int\n}\n\ntype Hit struct{ Attacker, Target, Damage int }\n\ntype World struct {\n\tEntities []Entity\n\tScore    int\n\tvisible  []int    // scratch reused every update\n\tstamp    []int    // per-entity \"seen in update N\" marks instead of a map\n\tframe    int      // update counter used with stamp\n\tevents   []Hit    // queued effects as plain values\n\tpending  []func() // the closure version, for comparison\n}\n\nfunc NewWorld(n int) *World {\n\tw := &World{Entities: make([]Entity, n), stamp: make([]int, n)}\n\tfor i := range w.Entities {\n\t\tw.Entities[i] = Entity{ID: i, X: float64((i * 37) % 200), Y: float64(i % 50), Alive: i%7 != 0, HP: 100}\n\t}\n\tw.visible = make([]int, 0, n) // sized once, at level load\n\tw.events = make([]Hit, 0, n)\n\tw.pending = make([]func(), 0, n)\n\treturn w\n}\n\n// VisibleFresh is the obvious version: a new slice, a new map and a capturing sort closure.\nfunc (w *World) VisibleFresh(minX, maxX float64) []int {\n\tvar ids []int\n\tseen := map[int]bool{}\n\tfor _, e := range w.Entities {\n\t\tif e.Alive && e.X >= minX && e.X < maxX && !seen[e.ID] {\n\t\t\tseen[e.ID] = true\n\t\t\tids = append(ids, e.ID)\n\t\t}\n\t}\n\tsort.Slice(ids, func(i, j int) bool { return w.Entities[ids[i]].X < w.Entities[ids[j]].X })\n\treturn ids\n}\n\n// VisibleReuse produces the same result into storage the world already owns.\nfunc (w *World) VisibleReuse(minX, maxX float64) []int {\n\tw.frame++\n\tw.visible = w.visible[:0]\n\tfor _, e := range w.Entities {\n\t\tif e.Alive && e.X >= minX && e.X < maxX && w.stamp[e.ID] != w.frame {\n\t\t\tw.stamp[e.ID] = w.frame\n\t\t\tw.visible = append(w.visible, e.ID)\n\t\t}\n\t}\n\tslices.SortFunc(w.visible, func(a, b int) int {\n\t\treturn cmp.Compare(w.Entities[a].X, w.Entities[b].X)\n\t})\n\treturn w.visible\n}\n\n// QueueClosures defers each hit as a closure stored for later: every one escapes.\nfunc (w *World) QueueClosures(hits int) {\n\tw.pending = w.pending[:0]\n\tfor i := range hits {\n\t\ttarget := &w.Entities[i]\n\t\tdamage := 3 + i%4\n\t\tw.pending = append(w.pending, func() { target.HP -= damage })\n\t}\n\tfor _, f := range w.pending {\n\t\tf()\n\t}\n}\n\n// QueueValues defers the same hits as data and applies them in one loop.\nfunc (w *World) QueueValues(hits int) {\n\tw.events = w.events[:0]\n\tfor i := range hits {\n\t\tw.events = append(w.events, Hit{Attacker: -1, Target: i, Damage: 3 + i%4})\n\t}\n\tfor _, h := range w.events {\n\t\tw.Entities[h.Target].HP -= h.Damage\n\t}\n}\n\n// HUD rebuilds its text only when the value it shows changes.\ntype HUD struct {\n\tscore int\n\ttext  string\n}\n\nfunc (h *HUD) Text(score int) string {\n\tif h.text == \"\" || score != h.score {\n\t\th.score, h.text = score, \"score \"+strconv.Itoa(score)\n\t}\n\treturn h.text\n}\n\nvar (\n\tsink  []int\n\tlabel string\n)\n\nfunc main() {\n\tfor _, hz := range []int{60, 120, 144} {\n\t\tfmt.Printf(\"frame budget at %d Hz: %v\\n\", hz, time.Second/time.Duration(hz))\n\t}\n\tw := NewWorld(500)\n\tfresh := w.VisibleFresh(40, 120)\n\treused := w.VisibleReuse(40, 120)\n\tfmt.Printf(\"visible entities: %d, both versions agree: %t\\n\", len(reused), slices.Equal(fresh, reused))\n\n\treport := func(name string, f func()) {\n\t\tfmt.Printf(\"%-34s %3.0f allocs/update\\n\", name, testing.AllocsPerRun(200, f))\n\t}\n\treport(\"visible query, fresh slice+map:\", func() { sink = w.VisibleFresh(40, 120) })\n\treport(\"visible query, reused scratch:\", func() { sink = w.VisibleReuse(40, 120) })\n\treport(\"32 hits queued as closures:\", func() { w.QueueClosures(32) })\n\treport(\"32 hits queued as values:\", func() { w.QueueValues(32) })\n\tw.Score = 12345\n\thud := &HUD{}\n\treport(\"HUD text rebuilt every update:\", func() { label = fmt.Sprintf(\"score %d\", w.Score) })\n\treport(\"HUD text cached until it changes:\", func() { label = hud.Text(w.Score) })\n}","language":"go","title":"Count allocations per update with testing.AllocsPerRun","walkthrough":"time.Second / time.Duration(hz) prints exact budgets. VisibleFresh allocates 22 times per call: append growing a nil slice to 173 elements, the map growing as IDs are inserted, and sort.Slice, which receives the slice as an interface and builds a reflection-based swapper. VisibleReuse truncates a slice sized at level load, replaces the map with a stamp slice compared against a frame counter and sorts with slices.SortFunc; its comparison closure captures w but does not escape, so it lives on the stack and the count is 0. QueueClosures stores 32 capturing closures in a slice for later, so each one escapes to the heap: exactly 32. QueueValues queues the same hits as structs: 0. fmt.Sprintf allocates twice, once to box the int into its ...any parameter and once for the new string, while the HUD cache rebuilds only when the score changes. Results go into package-level variables so the compiler cannot discard the work. The counts are stable for one toolchain but can change between Go releases as escape analysis improves."},{"body":"Size scratch slices when a level loads and reuse them with s = s[:0], so append writes into existing capacity. Replace per-frame sets with data the world already owns: a stamp slice, a bit set, or a long-lived map emptied with clear(m), which keeps its storage. Queue effects as plain structs processed in one loop instead of closures that capture entities; values are also easier to log, replay and send over the network. Closures are not the problem by themselves, escaping closures are: a closure passed to a function that only calls it, like the SortFunc comparator, stays on the stack. Watch for hidden boxing, because passing an int or a struct as any to fmt, a logger or an interface-typed event bus can allocate, and so can converting []byte to string for text. Build HUD strings when the value changes, not every frame. To see why a line allocates, go build -gcflags=-m prints the compiler's escape decisions.","title":"Patterns that keep the steady state allocation-free"},{"body":"sync.Pool helps when many goroutines need short-lived buffers, such as a server encoding snapshots for hundreds of clients in parallel. It is a poor fit for game entities. The pool may drop any object during garbage collection, keeping one victim generation so an idle object survives about one extra cycle at most; Get may return a fresh object; and every Get and Put adds ownership rules, which the pool ownership lesson covers. A single-threaded update loop has a simpler, deterministic option: a free list. Keep particles or projectiles in a slice, mark dead ones and push their indexes onto a free list that the next spawn pops. Nothing is allocated once capacity is reached, nothing disappears behind your back, and iterating a dense slice is friendly to the CPU cache.","code":"type Particles struct {\n\titems []Particle\n\tfree  []int // indexes of dead particles, reused before items grows\n}\n\nfunc (p *Particles) Spawn(v Particle) int {\n\tif n := len(p.free); n > 0 {\n\t\ti := p.free[n-1]\n\t\tp.free = p.free[:n-1]\n\t\tp.items[i] = v\n\t\treturn i\n\t}\n\tp.items = append(p.items, v)\n\treturn len(p.items) - 1\n}\n\nfunc (p *Particles) Kill(i int) {\n\tp.items[i].Alive = false\n\tp.free = append(p.free, i)\n}","language":"go","title":"sync.Pool or a free list owned by the loop","walkthrough":"This fragment belongs to an update loop in your own game and runs in your native environment; Particle is your struct with an Alive flag that the update skips. Spawn reuses a dead slot before growing items, so once items and free reach their working capacity, spawning and killing allocate nothing. Kill must run once per particle, and other systems that hold an index can see a reused slot; a generation counter per slot, checked on every lookup, catches those stale indexes. Choose sync.Pool when objects cross goroutines and reuse is only an optimization, and a free list when the loop owns them."},{"body":"A number printed once is a curiosity; a test that fails when the hot path starts allocating is a guard. Assert exactly zero rather than a non-zero count, because zero stays valid when a Go release changes escape analysis. Pair it with a benchmark that reports time and allocations per update for a scripted scene with a fixed seed, so two runs are comparable.","code":"func TestUpdateDoesNotAllocate(t *testing.T) {\n\tw := NewWorld(500)\n\tw.Update() // reach steady state: scratch slices at working capacity\n\tif n := testing.AllocsPerRun(100, w.Update); n != 0 {\n\t\tt.Fatalf(\"Update allocates %v times per call, want 0\", n)\n\t}\n}\n\nfunc BenchmarkUpdate(b *testing.B) {\n\tw := NewWorld(500)\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tw.Update()\n\t}\n}","language":"go","title":"Turn the measurement into a test and a benchmark","walkthrough":"This fragment goes into a _test.go file beside your World type and runs with go test in your own module. The explicit warm-up call lets scratch slices reach their working capacity before measuring; AllocsPerRun also warms up once on its own. Passing the method value w.Update is fine here because it is created once, outside the measured runs. b.Loop, available since Go 1.24, runs the body the right number of times and keeps the setup above it out of the timing. Run the zero-allocation test without -race and without coverage, since instrumentation can change the counts."},{"body":"When the budget is blown, benchmarks and profiles answer where the time goes and which lines allocate, and traces show whether a slow frame overlapped a GC cycle. Use the same deterministic scene for every comparison.","code":"# Time and allocations per update, five samples for comparison\ngo test -run '^$' -bench 'Update' -benchmem -count 5 ./game\n\n# CPU and heap profiles from the same benchmark\ngo test -run '^$' -bench 'Update' -cpuprofile cpu.out -memprofile mem.out ./game\ngo tool pprof -top cpu.out\ngo tool pprof -sample_index=alloc_objects -list 'World.Update' mem.out\n\n# GC cycles while the real game runs, one line per cycle on stderr\nGODEBUG=gctrace=1 ./mygame 2> gc.log\n\n# Execution trace: GC, goroutines and processor use on one timeline\ngo test -run '^$' -bench 'Update' -trace trace.out ./game\ngo tool trace trace.out","language":"bash","title":"Profile the loop you actually ship","walkthrough":"Run these commands in your own module; ./game and ./mygame stand for your package and binary. -run '^$' skips ordinary tests so only benchmarks run. The heap profile written by -memprofile records allocation sites, and -sample_index=alloc_objects ranks them by count, which matches what AllocsPerRun measures; -list prints source lines with their numbers. gctrace prints one line per GC cycle while the game runs, and the execution trace puts GC, goroutines and processors on one timeline. For spikes that appear only in long sessions, runtime/trace's FlightRecorder keeps the last few seconds in memory, so a debug build can write it to a file when a frame exceeds its budget."}],"takeaway":"Budget each frame from the refresh rate, measure allocations per update with testing.AllocsPerRun, reach zero in steady state by reusing storage the loop owns, and confirm with benchmarks, pprof and traces before tuning the GC.","title":"A 16.6 ms frame budget: measure allocations per update and make the steady state allocate nothing","unitID":"gamedev-systems","wrongAnswers":["As few as possible, with runtime.GC called every frame","Any amount, since Go's concurrent GC never slows the loop"]}],"revision":"2026-11-18.1","schemaVersion":1,"solutions":{},"units":[{"id":"gamedev-loop","lessons":[{"conceptTags":["gamedev.fixed-timestep"],"explanation":"A game loop runs on two clocks. The display hands you frames of uneven length; the simulation should advance in identical steps. Decoupling the two with an accumulator makes physics independent of the frame rate, makes every run reproducible, and turns a long stall into bounded slow motion instead of a frozen game.","id":"gamedev.fixed-timestep","objective":"Advance a simulation in fixed steps from variable frame times, draw it with an interpolation factor and cap catch-up work after a stall.","task":{"reading":{}},"title":"Fix the timestep: an accumulator turns uneven frames into identical simulation steps"},{"conceptTags":["gamedev.ebitengine-structure"],"explanation":"Ebitengine runs the loop from the previous lesson for you. You implement three methods, Update, Draw and Layout, and the engine decides when to call each one. Getting that split right is the most important structural decision in an Ebitengine project: a single state change inside Draw makes the game run at a different speed on every monitor.","id":"gamedev.ebitengine-structure","objective":"Structure an Ebitengine game so every state change happens in Update, Draw is a read-only view, and the rules run headless in tests.","task":{"reading":{}},"title":"Ebitengine's Game interface: Update advances ticks, Draw only reads, Layout fixes the screen"},{"conceptTags":["gamedev.vectors-movement"],"explanation":"Almost every line of 2D movement code adds, scales or measures a pair of numbers. A tiny vector type with value methods makes that code read like the math, rules out aliasing bugs and costs nothing measurable. Combined with fixed ticks, it lets you tune movement in units a designer can reason about: pixels per tick, and a drag factor applied once per tick.","id":"gamedev.vectors-movement","objective":"Write a small value-semantics vector type and move a body with normalized input, per-tick acceleration and drag that behave the same on every display.","task":{"reading":{}},"title":"A 2D vector value type: normalized input, acceleration and drag in per-tick units"},{"conceptTags":["gamedev.input-actions"],"explanation":"Players do not press buttons on the exact tick the game expects. They press jump a few ticks before landing or a few ticks after running off a ledge, and a strict implementation swallows those presses and feels broken. Responsive platformer controls are built from three small pieces: an action layer over physical keys, edge detection on actions, and short grace windows measured in ticks.","id":"gamedev.input-actions","objective":"Map physical keys to actions, detect presses on the action level, and implement jump buffering and coyote time as tick counters that can be tested deterministically.","task":{"reading":{}},"title":"Input as actions: edge detection, jump buffering and coyote time in a tick-exact simulation"},{"conceptTags":["gamedev.state-machines"],"explanation":"Games are full of modes: menus, gameplay, pause overlays, and enemies that patrol, chase and attack. Encoding them as booleans such as paused, gameOver, chasing and attacking creates combinations that should be impossible and guards that must be repeated everywhere. Two explicit state machines replace them: a stack of scenes for the flow of the game, and one mode value with one transition function for each enemy.","id":"gamedev.state-machines","objective":"Run title, playing, paused and game-over scenes through a scene interface and a transition stack, and drive an enemy with a single-mode behavior machine.","task":{"reading":{}},"title":"Scenes and enemy behavior as explicit state machines instead of boolean flags"},{"conceptTags":["gamedev.entity-components"],"explanation":"The first instinct for game objects is a hierarchy: a base object, a character built on it, an enemy built on that. In Go such hierarchies fight the language, which has no inheritance, and the hardware, which prefers contiguous data. An entity-component design keeps an entity as a bare ID, stores each component type in its own dense slice, and writes behavior as systems that loop over those slices.","id":"gamedev.entity-components","objective":"Build a minimal entity-component store with generics, run systems over dense slices, remove with swap-delete, and judge when plain structs are the better design.","task":{"reading":{}},"title":"Entities as IDs, components in dense generic stores, systems as plain loops"},{"conceptTags":["gamedev.collisions"],"explanation":"Collision handling has two jobs: detect that two shapes overlap, and decide how to move them apart. Axis-aligned boxes and circles cover most 2D games, and both have exact tests that cost a few comparisons. The failure that bites later is speed: an object that moves farther in one tick than an obstacle is thick can pass through it without ever overlapping it.","id":"gamedev.collisions","objective":"Test boxes and circles for overlap, compute the minimum push that separates them, and stop fast objects from tunneling with sub-steps or a swept test.","task":{"reading":{}},"title":"AABB and circle collisions: detect overlap, push out along the shallow axis, sweep fast movers"},{"conceptTags":["gamedev.spatial-hash"],"explanation":"Checking every object against every other costs n(n-1)/2 tests: 124,750 for 500 objects, every tick, and almost all of those pairs are far apart. A broad phase discards distant pairs cheaply so the exact tests from the collision lesson run only on near candidates. A uniform grid stored in a hash map is the simplest broad phase that works well for most 2D games.","id":"gamedev.spatial-hash","objective":"Build a uniform-grid spatial hash, insert objects by bounding box, query neighbors with deduplication, and count pair checks against the naive all-pairs loop.","task":{"reading":{}},"title":"A spatial hash for the broad phase: bucket by cell, query neighbors, check each pair once"}],"summary":"Fixed timesteps, Ebitengine structure, vectors, input actions, state machines, components, collisions and spatial hashing.","title":"Game loop, input and physics","translationNote":"Runnable models are engine-free and deterministic. Build windowed games with Ebitengine in your own native environment; GopherForge does not run a graphics engine."},{"id":"gamedev-systems","lessons":[{"conceptTags":["gamedev.tilemaps-camera"],"explanation":"The previous unit gave every entity a world position and a fixed-timestep update. A tile map lays a grid over that world, and a camera decides which part of it reaches the screen. Both are small pieces of arithmetic, and most tile-map bugs are one of three mistakes in it: the wrong coordinate space, the wrong rounding or the wrong edge.","id":"gamedev.tilemaps-camera","objective":"Convert between tile, world and screen coordinates, keep a following camera inside the map and compute the exact range of tiles to draw.","task":{"reading":{}},"title":"A camera is a coordinate transform: follow the target, clamp to the map, draw only visible tiles"},{"conceptTags":["gamedev.pathfinding"],"explanation":"Chasing the player in a straight line works until the first wall. Breadth-first search finds a way around but ignores terrain cost; Dijkstra respects cost but explores every cell closer than the goal, in all directions. A* keeps Dijkstra's guarantee while steering the search with an estimate of the remaining distance. Its quality depends on three choices that are easy to get subtly wrong: the cost model, the heuristic and the tie-break.","id":"gamedev.pathfinding","objective":"Implement grid A* with container/heap, choose a heuristic that matches the movement rules, make equal-cost choices deterministic and decide when a flow field beats per-unit searches.","task":{"reading":{}},"title":"A* on a grid: a heap, a heuristic that matches the moves, and tie-breaking you can replay"},{"conceptTags":["gamedev.procedural-generation"],"explanation":"Procedural generation is only useful when the same seed builds the same world: a player shares a seed, a tester attaches one to a bug report, a replay regenerates the level instead of storing it. That property is not automatic. It depends on who owns each random generator, how many values each system draws and in what order, and whether any code path reaches for a generator nobody seeded.","id":"gamedev.procedural-generation","objective":"Generate a seeded cave with a math/rand/v2 PCG source, keep each system on its own derived stream and explain why global or shared randomness breaks replays.","task":{"reading":{}},"title":"Reproducible worlds: one seed, one random stream per system, and no global rand"},{"conceptTags":["gamedev.tweening-animation"],"explanation":"A panel slides in, a coin bounces, a character cycles through four walking frames. The tempting implementation reads time.Now in Draw and computes progress from it. That ties animation to the wall clock: it keeps running while the game is paused, it behaves differently at 60 Hz and 144 Hz, and a replay cannot reproduce it. The fixed-timestep loop from the previous unit already provides a better clock: the tick.","id":"gamedev.tweening-animation","objective":"Drive easing curves, chained and retargeted tweens and sprite animation clips from tick counts so motion is deterministic, pausable and free of jumps.","task":{"reading":{}},"title":"Tweens and sprite frames advance with the simulation tick, not the wall clock"},{"conceptTags":["gamedev.save-games"],"explanation":"A save file outlives the build that wrote it, sits in a folder the player can edit and gets shared on forums. A loader that unmarshals it straight into game state will eventually meet a save from an older version, a save from a newer version, a file truncated by a crash and a hand-edited file with 999 health. Each of those needs a deliberate answer, and none of them should be a panic.","id":"gamedev.save-games","objective":"Design a versioned JSON save format, migrate v1 saves to v2, reject unknown fields and out-of-range values, and replace a save file without ever leaving it half-written.","task":{"reading":{}},"title":"Save files are untrusted input: version them, migrate forward, validate and write atomically"},{"conceptTags":["gamedev.authoritative-server"],"explanation":"In a multiplayer game every client is a program you do not control. If clients report their own positions, a modified client can teleport, fly or walk through walls, and the server has no grounds to refuse. An authoritative server inverts that: clients send what the player wants to do, the server decides what happens, and everyone receives the server's version of the world. Goroutines and channels fit this shape well, provided exactly one goroutine owns the state.","id":"gamedev.authoritative-server","objective":"Build a server tick loop in which one goroutine owns all game state, clients send inputs over channels, movement is validated against speed and rate limits, and snapshots are copies in a deterministic order.","task":{"reading":{}},"title":"An authoritative server owns the world in one goroutine and accepts only validated intent"},{"conceptTags":["gamedev.client-prediction"],"explanation":"The authoritative server from the previous lesson is fair but feels slow. With 50 ms of latency each way, a player presses right and nothing moves for a tenth of a second. Client-side prediction runs the same movement rule locally so the press responds at once, reconciliation fixes the prediction when the server disagrees, and interpolation shows other players smoothly, slightly in the past. They solve three different problems with three different pieces of state.","id":"gamedev.client-prediction","objective":"Hide round-trip latency by predicting local movement, reconcile with acknowledged server snapshots by replaying pending inputs, and draw remote players by interpolating a snapshot buffer.","task":{"reading":{}},"title":"Client prediction replays unacknowledged inputs; remote players are interpolated from the past"},{"conceptTags":["gamedev.frame-budget"],"explanation":"At 60 frames per second each frame has about 16.6 ms for input, simulation, drawing and whatever the runtime needs. Go's garbage collector runs concurrently, but its work is paid for by your program: the more a game allocates per frame, the more often a cycle starts and the more CPU the collector takes from the loop. The useful goal is not zero allocations ever; it is an update that allocates nothing in steady state, verified by a number a test can check.","id":"gamedev.frame-budget","objective":"Turn refresh rates into frame budgets, count allocations per update with testing.AllocsPerRun, remove per-frame slices, maps, closures and strings, and profile a game loop with pprof and execution traces.","task":{"reading":{}},"title":"A 16.6 ms frame budget: measure allocations per update and make the steady state allocate nothing"}],"summary":"Tilemaps and cameras, A* pathfinding, seeded generation, tweens, save files, authoritative servers, prediction and frame budgets.","title":"Worlds, AI and multiplayer","translationNote":"Headless simulations stand in for rendering and sockets. Real transports, assets and platform builds belong to your own native project."}]}