The 12-Step Game Loop
A walkthrough of the 12-step pipeline that runs every agent turn: what each phase does, where the time goes, and how routine turns resolve in seconds while combat turns fall back to a slower agentic tool loop.
Updated 12 min read
How long a loop iteration takes depends almost entirely on one step, the executor, which now runs in one of two modes. Most turns are routine and resolve in a single structured-output call (a few seconds). Combat and housing emergencies fall back to an agentic tool loop with up to 7 LLM calls, which can stretch a turn toward half a minute. Everything else (screenshot, detection, ownership classification, context assembly) takes well under a second combined.
Two timescales in the same loop
AoE2's clock runs continuously, and the agent only samples it. The loop fires, takes a screenshot, runs detection, builds context, sends that to the LLM, executes whatever comes back, then sleeps and repeats.
The first half of that, from screenshot to context assembly, takes under 500ms. Then the executor starts. On a routine turn that's a single structured-output call (a few seconds). Routine turns are pipelined, so instead of blocking idle while the model computes, the loop fills the wait with cheap deterministic upkeep and with executing the previous turn's actions (more at step 9). On a combat or housing turn the executor enters an agentic tool loop instead. The first response arrives in 8–10 seconds, and each following tool call gets executed locally and sent back, adding another ~3 seconds per call. With up to 7 calls, that path alone can run ~20–30 seconds. Combat turns don't pipeline: their tool loop is already acting mid-turn, so they run synchronously.
The 0.3-second sleep at step 12 is a deliberate pause between iterations; it's negligible next to the executor either way.
A routine iteration takes a few seconds and a worst-case combat iteration takes ~30, and the game keeps running all the time. When you watch the agent play, it acts quickly most of the time, and sometimes it stops for a while to think through a fight.
The 12 steps
Every iteration runs these steps in order:
[ Guard ]
~200 ms worst case
- 01
Check the game is running
- 02
Focus the game window
[ Perceive ]
- 0310–30 ms
Capture screenshot
- 041 pass
Detect entities
- 05~5 ms
Classify ownership
- 06<1 ms
Check for threats
[ Decide ]
- 07
Maybe launch the strategist[ async ]
Runs in the background
- 08
Build the LLM context
- 092–4 s
Get actions from the executor
Up to ~30 s on combat turns
[ Act ]
- 10
Update memory and goals
- 11~50 ms each
Execute actions
- 120.3 s
Wait
back to step 01, next turn
Ownership classification, alarm checks and context building are covered in later episodes, so I won't spend long on them here.
How long each phase takes:
| Phase | Time |
|---|---|
| Window check + focus | ~200ms worst case |
| Screenshot capture | ~10–30ms |
| YOLO detection (single pass @640) | one forward pass |
| Ownership classification | ~5ms |
| Alarm check | <1ms |
| Executor, single-shot (routine turns) | ~2–4s |
| Executor, tool loop, first response (combat) | ~8–10s |
| Executor, per tool call (combat) | ~3s each, up to 7 |
| Action execution | ~50ms per action |
| Loop delay | 0.3s |
| Total per iteration | ~3–5s routine; up to ~30s on a combat turn (tool loop dominates) |
The strategist is not in that table because it runs asynchronously in the background (step 7 below).
Most of the time goes to the executor. On a routine turn that's one structured call. On a combat turn it's the tool loop: up to 7 calls at roughly 3 seconds each, plus the initial 8–10s response, which is where the ~30-second worst case comes from. Detection, screenshot capture and action execution together take under 500ms.
Step 3: Screenshot capture
The mss library grabs the game window region, converts from BGRA to RGB via PIL, and encodes as JPEG. The whole thing takes 10–30ms and returns (bytes, width, height).
Screenshots are taken relative to the game window instead of the full monitor, since the game can be anywhere on screen. Every coordinate downstream of this step is window-relative until the execution layer translates it back to screen-absolute coordinates for pyautogui. This translation happens once per action rather than once per turn, because the window can move while a batch of actions is executing.
Step 4: Entity detection
The YOLO model runs on every frame as a single forward pass at imgsz=640, the size the model trained on. My first idea was to tile the 3024×1672 screenshot to catch the small objects, but for this model it was the wrong choice. When I measured on real frames, a plain downscale-and-run-once beat SAHI tiling by about 10× on real F1, because tiling shows the model objects ~2.4× bigger than anything it saw in training. Episode 3 goes into the details, with the numbers. So the agent runs with adaptive_sahi=False, and the tiling code stays in the tree but switched off.
Detection has two live modes, plus one that's parked:
- Single pass @640: every turn. The deployed path (
detect_fast/detect_fast_multi). - Kalman prediction (~0ms): on rescans, when the tracker is more than 80% confident, the agent guesses where entities moved from their last known speed, without capturing a new screenshot or running inference. Episode 3 covers how the tracker keeps entity IDs stable across frames.
- SAHI tiling: built and tested, but off by default. It would only help if the model were retrained at the scale the tiles produce.
There's also a frame-differencing gate in front of rescans. If the screen hasn't changed by more than ~3% (with the always-ticking resource bar cropped out), the agent skips detection completely and reuses the previous entities.
Step 7: The strategist runs in the background
The strategist reads the resource bar and population count from the HUD with local OCR (RapidOCR) and sends those numbers to the model as a text-only prompt; no screenshot ever goes to Claude. It returns 3–5 prioritized goals. It runs every 10 turns in Castle Age, every 5 in Feudal, every 3 in Dark Age, or right away when an alarm fires.
It's launched with asyncio.create_task(), so it runs in the background while the rest of the loop continues, and the executor doesn't wait for it.
strategist_task = asyncio.create_task(
strategist.generate_goals(screenshot, game_state)
)On the first iteration, the executor uses default goals because no strategist result exists yet. After that, it uses whatever goals the last strategist call produced, which may be one or two iterations stale. I chose this on purpose: waiting for the strategist would add 3–8 seconds to every N-th iteration, and slightly old goals are almost always better than waiting.
If a strategist task is still running when a new one would fire, the loop reuses the existing task rather than launching a second one.
Step 9: Two executor paths
The executor is text-only, with no screenshot and no vision. It receives a structured context block (entity list, goals, resources, recent turn history, game knowledge), and get_actions() routes the turn down one of two paths (_use_single_shot):
- Routine turns (the common case) take a single-shot structured-output call: one
messages.parse, the model returns a list of actions, and the game loop executes them without a tool loop or any intermediate roundtrips. - Combat and housing turns, the ones that need mid-turn rescans or composite tools, fall back to the agentic tool loop below. The router scans the context for signals like
under attack,defend, or being housed, and keeps those turns on the loop.
Two things happen around this call. First, routine turns are pipelined. The executor call is launched in the background, and the loop uses the waiting time for other work: it executes the previous turn's committed head (re-validated against the latest detection, with any stale target dropped) and runs a deterministic reactive tier that queues a villager when population is below the age cap and puts idle villagers on the nearest resource, all with no LLM call. The plan computed this turn is then acted on next turn. Combat turns skip the pipeline and run synchronously, since their tool loop is already acting.
Second, after entity-affecting actions the loop verifies the effect by re-detecting. A successful build logs CONFIRMED; a miss logs the exact phrase no visible change, which feeds a stuck-loop detector, so the model notices when it repeats an action without any effect.
In the rest of this section, let's go through the tool-loop path, because it is the more complex one.
The context looks something like this:
## Detected Entities
sheep_0: sheep at (456, 789) [95%]
sheep_1: sheep at (512, 801) [91%]
villager_0: villager at (380, 720) [own] [88%]
town_center_0: town_center at (512, 640) [own] [99%]
## Active Goals
[HIGH] Queue villagers: 4/10 (40%)
[MED] Gather food: sheep available nearby
## Game State
Food: 250 | Wood: 180 | Gold: 50 | Stone: 100
Population: 8/10 | Age: Dark Age
## Last Turn
Turn 3: Queued villager, sent villager_1 to sheep_0Claude responds with a tool call. The executor runs it, the result goes back to Claude, and Claude decides what to do next. The available tools are 7 base action types (click, right_click, press, drag, scroll, wait, detect) plus 3 composite tools (build, send_villager, queue_villager) that bundle multi-step sequences.
When a turn runs the loop, it looks like this:
Look for idle villagers
detect
Send a villager to the sheep
send_villager · composite
Send a second villager to food
right_click
Queue a new villager
queue_villager · composite
Select the next idle villager
press
Send it to the lumber camp
right_click
Report population, resources and game state
Six tool calls, then Claude reports back its observations (population, resources, game state) in the final response and the iteration ends.
Each call takes ~3 seconds because every round trip is LLM latency. Claude generates the tool call, the executor runs it locally (pyautogui is ~50ms), the result is sent back, and Claude processes it and generates the next response. That last part, Claude reading the result and deciding what to do, takes ~3 seconds. The mouse click itself is negligible.
The "up to 7" is a hard cap (max_tool_iterations = 7). Simple iterations use far fewer; queueing a villager and sending two to food might take 3 calls. Complex ones, like the sequence above, can use all 7. The limit exists because game state keeps changing while the loop is blocked on the executor. At 7 calls the iteration is already ~30 seconds old. Letting the agent continue past that means acting on a screenshot that's half a minute stale, and the agent might send a villager to a sheep that's since been eaten by a wolf. Cutting off at 7 and starting fresh with a new screenshot is the better tradeoff.
Composite tools
Some actions require multiple steps in sequence: select an idle villager, open the build menu, press the building hotkey, click a placement location. Before composite tools, that was 4 separate tool calls and 4 API roundtrips, about 12 seconds just for one building placement.
Composite tools wrap those sequences:
# build(building_key, x, y):
# → select idle villager → open build menu → press hotkey → click placement
build("A", 600, 450) # lumber camp
# send_villager(target, x, y):
# → select idle villager → right-click destination
send_villager("sheep_0", 456, 789)
# queue_villager():
# → H (select TC) → Q (queue)
queue_villager()Each of these executes a multi-step sequence within a single tool call, with no intermediate API roundtrips. build() saves about 9 seconds. queue_villager() saves 3.
The downside is that the agent doesn't re-detect between the steps of a composite tool. If a villager dies in the middle of the sequence, the build still runs. This happens rarely, so I don't think it is worth the extra latency of a re-scan in the middle of an action.
Tuning pyautogui: PAUSE=0.02
pyautogui has a global delay between every mouse and keyboard event. The default is 0.1 seconds. I changed it to 0.02. The delay exists because pyautogui is a general-purpose automation library designed to control applications that weren't built to receive inputs at machine speed. A 100ms gap gives the target application time to process one event before the next arrives, preventing dropped or misregistered inputs on sluggish GUIs.
pyautogui.PAUSE = 0.02This saves 80 milliseconds per action. With 7 actions per iteration and 30 iterations per game, that's about 17 seconds over a game run. The bigger difference is that action sequences are less sluggish: the gap between "press H" and "press Q" shrinks from 100ms to 20ms, which is closer to how a human types hotkeys.
AoE2 handles it fine, with no input buffering problems at this speed.
The related setting is action_delay, a 50ms pause between separate tool call actions (not within a composite tool). That one stays at 50ms because the game needs a moment to process a click before the next one fires. Going lower on that causes missed inputs.
Steps 10 and 11: Memory and execution
After the agentic loop completes, the agent records what happened:
turn = memory.create_turn(
reasoning=response.reasoning,
actions=response.actions,
observations=response.observations
)The executor reports back what it observed: resources, population, game state. That structured JSON gets parsed and stored, then injected into the next turn's context as Layer 4. So the agent describes its own view of the game, and this description is fed back to it in the next turn. This works well most of the time. When the LLM misreports something ("Food: 500" when it's actually 50), that error propagates until the strategist's next OCR read corrects it.
Action execution translates window-relative coordinates to screen-absolute, applies the per-action window offset refresh (in case the window moved), and calls pyautogui. Failed actions (wrong coordinates, entity not found, game didn't respond) are logged back to memory as feedback for the next turn, so the agent knows if its last action failed.
When things break
The main loop wraps each step in error handling. Detection failures don't crash the loop: the iteration continues without an entity list and the agent works from a degraded context. Focus failures skip the iteration entirely. API errors in the executor return a wait action, because I think doing nothing is safer than attempting an action with incomplete state.
There is one failure the loop doesn't handle well. If the executor keeps repeating the same action with no visible effect, the loop keeps running. The stuck-loop detection that handles this lives in the memory layer rather than the game loop. After 3 consecutive turns with no observable change, it injects a correction into the next prompt. That's covered in Episode 6.
What's next
Most of what makes the loop useful happens inside steps 4 and 9, detection and reasoning. Episode 3 covers detection: how to build a 60-class YOLO model for an isometric game, why a plain single pass beat the tiling I expected to need, and how entity IDs stay stable across frames so the LLM can refer to the same sheep across turns.
Tools and references6
- mss
Fast game-window screen capture (~10–30ms)
- Pillow (PIL)
BGRA→RGB conversion and JPEG encoding
- asyncio (create_task)
Runs the strategist in the background so the loop never blocks on it
- Anthropic tool use
The agentic fallback loop for combat and housing turns
- SAHI
Sliced inference; built and measured, but disabled in v6 because it lowered real F1 (deep-dived in Episode 3)
- PyAutoGUI
Action execution; the `PAUSE=0.02` tuning lives here