Game loop, input and physics · 5 MIN READ
Scenes and enemy behavior as explicit state machines instead of boolean flags
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.
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.
gamedev · A MAP OF THE IDEA
- Scene returns Transition
- Stack applies the change
- Top scene updates
- All scenes draw bottom-up
Useful when
- Impossible state combinations cannot be represented.
- Pause and overlays need no checks inside gameplay code.
Watch out
- Without hysteresis, threshold transitions flicker every tick.
- Large machines outgrow one switch; split states into types.
Implementation & operation 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.
What boolean-flag soup costs
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.
type Enemy struct {
patrolling, chasing, attacking, recovering bool // 16 combinations, 4 legal
recoverTicks int
paused bool // and now 32
}
func (e *Enemy) Update() {
if !e.paused && e.chasing && !e.attacking { // every caller repeats a guard like this
// ...
}
}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.
A scene stack and an enemy mode machine
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.
package main
import (
"fmt"
"strings"
)
// Input is one tick's snapshot: actions plus the tick number for logging.
type Input struct {
Tick int
Confirm, Pause bool
Move int
}
// Op says what the scene stack should do after a scene's Update.
type Op int
const (
Stay Op = iota
Push
Pop
Replace
)
type Transition struct {
Op Op
Next Scene
}
type Scene interface {
Name() string
Update(in Input) Transition
Draw(b *strings.Builder)
}
// Stack updates only the top scene and draws every scene bottom-up.
type Stack struct{ scenes []Scene }
func (s *Stack) Update(in Input) {
top := len(s.scenes) - 1
t := s.scenes[top].Update(in)
switch t.Op {
case Stay:
return
case Push:
s.scenes = append(s.scenes, t.Next)
case Pop:
s.scenes = s.scenes[:top]
case Replace:
s.scenes[top] = t.Next
}
names := make([]string, len(s.scenes))
for i, sc := range s.scenes {
names[i] = sc.Name()
}
fmt.Printf("tick %2d: scenes [%s]\n", in.Tick, strings.Join(names, " "))
}
func (s *Stack) Draw() string {
var b strings.Builder
for _, sc := range s.scenes {
sc.Draw(&b)
}
return b.String()
}
type Title struct{}
func (Title) Name() string { return "title" }
func (Title) Update(in Input) Transition {
if in.Confirm {
return Transition{Replace, NewPlaying()}
}
return Transition{}
}
func (Title) Draw(b *strings.Builder) { b.WriteString("[press confirm]") }
type Playing struct {
PlayerX, HP int
Enemy Enemy
}
func NewPlaying() *Playing {
return &Playing{PlayerX: 10, HP: 2, Enemy: Enemy{X: 22, Dir: 1}}
}
func (*Playing) Name() string { return "playing" }
func (p *Playing) Update(in Input) Transition {
if in.Pause {
return Transition{Push, Paused{}}
}
p.PlayerX += in.Move
if p.Enemy.Update(in.Tick, p.PlayerX) {
p.HP--
}
if p.HP == 0 {
return Transition{Replace, GameOver{}}
}
return Transition{}
}
func (p *Playing) Draw(b *strings.Builder) {
fmt.Fprintf(b, "[player x=%d hp=%d, enemy x=%d %v]", p.PlayerX, p.HP, p.Enemy.X, p.Enemy.Mode)
}
type Paused struct{}
func (Paused) Name() string { return "paused" }
func (Paused) Update(in Input) Transition {
if in.Pause {
return Transition{Op: Pop}
}
return Transition{}
}
func (Paused) Draw(b *strings.Builder) { b.WriteString("[PAUSED overlay]") }
type GameOver struct{}
func (GameOver) Name() string { return "gameover" }
func (GameOver) Update(in Input) Transition {
if in.Confirm {
return Transition{Replace, Title{}}
}
return Transition{}
}
func (GameOver) Draw(b *strings.Builder) { b.WriteString("[game over]") }
// Mode is the enemy's behavior state: exactly one value at a time.
type Mode int
const (
Patrol Mode = iota
Chase
Attack
Recover
)
func (m Mode) String() string { return [...]string{"patrol", "chase", "attack", "recover"}[m] }
type Enemy struct {
X, Dir int
Mode Mode
inMode int // ticks spent in the current mode
}
func (e *Enemy) next(dist int) Mode {
switch e.Mode {
case Patrol:
if dist <= 5 {
return Chase
}
case Chase:
if dist <= 1 {
return Attack
}
if dist > 9 { // leave at 9, enter at 5: hysteresis stops flicker
return Patrol
}
case Attack:
return Recover
case Recover:
if e.inMode < 3 {
break
}
if dist > 9 {
return Patrol
}
return Chase
}
return e.Mode
}
// Update runs one tick and reports whether the enemy landed a hit.
func (e *Enemy) Update(tick, playerX int) (hit bool) {
dist := max(playerX-e.X, e.X-playerX) // absolute distance
if m := e.next(dist); m != e.Mode {
fmt.Printf("tick %2d: enemy %v -> %v at distance %d\n", tick, e.Mode, m, dist)
e.Mode, e.inMode = m, 0
hit = m == Attack
} else {
e.inMode++
}
switch e.Mode {
case Patrol:
e.X += e.Dir
if e.X <= 20 || e.X >= 26 {
e.Dir = -e.Dir
}
case Chase:
if playerX > e.X {
e.X++
} else if playerX < e.X {
e.X--
}
}
return hit
}
func inputAt(tick int) Input {
in := Input{Tick: tick}
switch {
case tick == 2 || tick == 40 || tick == 42:
in.Confirm = true
case tick == 24 || tick == 27:
in.Pause = true
case tick >= 3 && tick <= 12:
in.Move = 1
case tick >= 13 && tick <= 18:
in.Move = -2
case tick >= 28 && tick <= 36:
in.Move = 1
}
return in
}
func main() {
s := &Stack{scenes: []Scene{Title{}}}
for tick := 1; tick <= 42; tick++ {
s.Update(inputAt(tick))
if tick == 25 || tick == 42 {
fmt.Println("draw:", s.Draw())
}
}
}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.
Transitions are values, so ownership is clear
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.
Enemy modes: one value, timers per mode, hysteresis
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.
When to grow beyond a switch
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.
TAKE THIS WITH YOU
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.
Check your understanding
In a scene stack, why is the pause menu pushed on top of the playing scene instead of replacing it?
Go to the source
Progress stays in this browser. No account needed.