Build a Turn-Based Maze Capture Game with AI Coding Tools
This article walks through the design and implementation of a small turn-based maze capture game created through human–AI collaboration with an intelligent coding tool. It reverses the classic Pac-Man-style chase: instead of playing the runner collecting dots, the player commands four ghosts to corner an AI-driven evader on a turn-based maze. Systematically broken down across six areas—gameplay abstraction, data modeling, pathfinding and coordination, evader AI, difficulty balancing, and tuning/verification—it includes reference code and a prompt structure that let a single developer take a playable prototype from idea to working build in a day or two.
Build a Turn-Based Maze Capture Game with AI Coding Tools
A small game called Ghost Hunter has quietly launched. Its prototype was built by a developer working together with an intelligent coding tool. The gameplay is unusual: in the classic maze-chase genre, the player usually plays the one being chased, frantically collecting dots and dodging enemies. This game completely flips the perspective. The player commands four ghosts to hunt down an AI-driven “Pac-Man” across a turn-based maze.
The technical depth goes far beyond “swapping roles.” Once the perspective is reversed, what decides the outcome shifts from real-time reflexes to strategic play: how to coordinate an encirclement, how to cut off escape routes, and how to hold the line when the opponent gains a counterattack ability. Add route planning, auto-pilot delegation, and level-by-level progression, and it becomes a small but complete turn-based strategy game.
Drawing on practical experience with this kind of “human–AI collaborative creation,” this article breaks down the design thinking and implementation essentials across six layers: gameplay abstraction, data modeling, pathfinding and coordination, evader AI, difficulty balancing, and tuning/verification. It also provides reference code and a prompt structure that anyone can adapt. With an intelligent coding tool, a single developer can describe requirements in natural language, iterate quickly, and get a playable prototype running in a day or two.
1. From “being chased” to “capturing”: a gameplay reversal worth dissecting
1.1 What the perspective flip changes
Maze chase is a classic two-agent structure: one side keeps moving through the maze and collecting targets, the other side pursues. When the player takes the chased perspective, the challenge lies in spatial memory, route prediction, and split-second reactions. The pursuer AI only needs to balance two behaviors—“chase” and “random walk”—to generate enough pressure.
After the perspective flips, three key elements change accordingly:
- Command units go from one to many: the player moves from controlling a single character to coordinating four ghosts with distinct abilities, naturally introducing resource allocation and role division.
- The information advantage shifts: once the evader is AI-controlled, the player knows its position and next intent, so they can set traps and intercept in advance, raising the depth of decision-making.
- The time model changes: keeping real-time movement would make micro-managing multiple units consume a lot of attention and make it hard to express strategic depth. Switching to turn-based play turns each turn’s combination of commands into a puzzle-like local optimization problem.
So “multiple units + turn-based + AI opponent” is a strong combination. It lowers the operational barrier while fully preserving the depth of strategic play.
1.2 Three engineering benefits of turn-based play
Turn-based play may seem “slow,” but it actually simplifies engineering significantly:
- Solving time decouples from interaction time: hunter decisions and the evader AI only run at the end of a turn, free from the render frame rate. Even a somewhat heavier algorithm can be masked behind a “thinking” animation.
- Clear, reproducible state: the game state is sliced into a series of discrete snapshots, making save, replay, step-by-step review, and single-step debugging natural. If something goes wrong on a turn, you only need to reproduce that turn’s input.
- Easy to validate automatically: each turn’s input is just a handful of commands, so you can script hundreds or thousands of simulated matches to compute win rates and back up balance tuning with data. This point gets expanded later.
2. Core mechanics breakdown: turning “capture” into verifiable rules
Good design has to land on rules that can each be verified. When collaborating with an intelligent coding tool, the more precise your rule statements, the less you drift into “the code runs but the gameplay is wrong.” It’s worth spelling out the following on paper first.
2.1 The maze and action units
The maze is described as a character grid. # denotes a wall, . a collectible dot, o a power pellet, P the evader’s starting position, and G a ghost’s starting position:
##################o......#......o##.####.#.#.####.##......#.#......#####.#.###.#.#####....#..P..#....##.####.###.####.##G.............G##################
The maze doesn’t need to be large. Ten-odd rows and about twenty columns are enough to carry one interesting round of play. The key is to make the paths form “loops” as much as possible. Few loops mean many dead ends, and the evader is more easily cornered, which raises the hunters’ win rate.
2.2 Turn flow and resolution order
A complete turn should be split into five stages with a fixed order and non-overlapping logic:
- Issue commands: the player picks a movement direction for each ghost. A ghost moves one cell per turn, can’t pass through walls, and can’t move onto a cell already occupied by another ghost.
- Resolve movement: execute in a fixed order (e.g., by ghost index). If a ghost moves onto the evader’s cell, capture is decided immediately.
- Evader acts: first compute chase pressure (the step distance from each cell to the nearest ghost), then move; after moving, it eats the dot or power pellet on its cell.
- State update: refresh the duration of the power state and the cooldown turns of ghost skills.
- Win/loss check: if the objective is met, go to level settlement; otherwise proceed to the next turn.
The resolution order must be written into the rules. For example, when a ghost and the evader swap positions in the same turn, the result depends on which side acts first. Also, whether a ghost can enter the opponent’s spawn cell, and whether the evader can pass through the ghost den, all need to be decided in advance and written into unit tests.
2.3 Junction decisions and route planning
The fun of this kind of gameplay concentrates at “junctions.” On a long straight corridor both sides only have “advance” and “retreat,” which is meaningless; at a fork, the ghost’s choice determines whether the encirclement succeeds or gets broken through.
To make this fun visible, the interaction design can have three layers:
- Default manual: the player picks a direction for each ghost one at a time.
- Single-ghost delegation: delegate automatic decisions for individual ghosts so the player can focus on commanding the rest. This both lowers the operational load and makes a good “tutorial level” design.
- Full-team delegation: the whole set of commands is generated by the algorithm; the player watches the capture unfold, and this can also be used to verify level difficulty.
2.4 Collection and counterattack mechanics
The evader’s goal can’t just be “escape,” or it only needs to keep its distance from the hunters and the game quickly degenerates into an in-place standoff. Borrowing from classic chase gameplay, give it two behavioral motivations:
- Collection pressure: the evader must eat every dot on the map to clear the level, and the dot distribution forces it to repeatedly pass through dangerous areas.
- Counterattack window: after the evader eats a power pellet, it enters a “counterattack state” that lasts several turns. During this time, a ghost entering a cell adjacent to the evader is “stunned” and sent back to its spawn, and can only actively avoid it.
This design keeps hunters from just hugging the target and chasing mindlessly; “should I chase or retreat?” thus becomes a real decision point.
2.5 Level-by-level progression
Difficulty progression should aim for “single-variable adjustment,” i.e., each level changes only one or two parameters, such as the number of ghosts, which abilities are unlocked, the number of power pellets, or the evader AI’s strategy tier. This lets players clearly perceive what changed and lets developers more easily pinpoint the cause of any imbalance.
3. Data modeling: maze, grid, and turn state
3.1 Use one coordinate system to unify “algebra” and “geometry”
The most common bug in grid games is mixing up rows and columns: interchanging array indices (r, c) with screen coordinates (x, y) results in correct rendering but wrong pathfinding, or vice versa. A good convention: internally use only row/column coordinates (r, c), and convert to x = c × cellWidth, y = r × cellHeight only at render time.
3.2 Separate level data from runtime state
Level data (maze, spawn points, power pellets, numeric parameters) is static and lives in a config file; runtime state (each character’s position, remaining time, turn count, random seed) is dynamic. Separating the two has three benefits: you don’t touch logic code when tuning numbers; different levels can reuse the same set of rules; and the state can be fully serialized, so saving and replaying are no longer hard.
{"level": 1,"maze": ["#################","#o......#......o#","#.####.#.#.####.#","#......#.#......#","####.#.###.#.####","#....#..P..#....#","#.####.###.####.#","#G.............G#","#################"],"hunters": [{ "pos": [7, 1], "speed": 1, "skill": null },{ "pos": [7, 15], "speed": 1, "skill": null }],"evader": { "pos": [5, 8], "speed": 1 },"powerTurns": 6,"turnLimit": 200}
3.3 Use a distance field instead of frame-by-frame pathfinding
A turn-based maze doesn’t need fine frame-by-frame pathfinding. All tactical judgments can be reduced to a single field: the step distance from any cell to the target. For a grid maze, breadth-first search (BFS) yields the shortest path: the maze is unweighted, BFS naturally gives the shortest path, and with no complex heuristics it’s simple to implement and easy to verify.
// Maze representation: '#' wall, '.' dot, 'o' power pellet, 'P' evader spawn, 'G' hunter spawnconst MAZE = ['#################','#o......#......o#','#.####.#.#.####.#','#......#.#......#','####.#.###.#.####','#....#..P..#....#','#.####.###.####.#','#G.............G#','#################'];const DIRS = [[-1, 0], [1, 0], [0, -1], [0, 1]]; // up, down, left, rightconst key = ([r, c]) => r + ',' + c;function parseLevel(rows) {const walls = [], dots = new Set(), powers = new Set();const hunters = []; let evader = null;rows.forEach((row, r) => {walls[r] = [];[...row].forEach((ch, c) => {walls[r][c] = ch === '#';if (ch === '.') dots.add(key([r, c]));if (ch === 'o') { powers.add(key([r, c])); dots.add(key([r, c])); }if (ch === 'P') evader = { pos: [r, c] };if (ch === 'G') hunters.push({ pos: [r, c], stunned: 0 });});});return { h: rows.length, w: rows[0].length, walls, dots, powers, hunters, evader };}/** From start, return a distance field { cell key -> shortest steps } */function bfs(maze, start) {const dist = new Map([[key(start), 0]]);const queue = [start];for (let i = 0; i < queue.length; i++) {const [r, c] = queue[i];for (const [dr, dc] of DIRS) {const nr = r + dr, nc = c + dc;if (nr < 0 || nc < 0 || nr >= maze.h || nc >= maze.w) continue;if (maze.walls[nr][nc] || dist.has(key([nr, nc]))) continue;dist.set(key([nr, nc]), dist.get(key([r, c])) + 1);queue.push([nr, nc]);}}return dist;}function neighbors(maze, [r, c]) {const out = [];for (const [dr, dc] of DIRS) {const nr = r + dr, nc = c + dc;if (nr < 0 || nc < 0 || nr >= maze.h || nc >= maze.w) continue;if (!maze.walls[nr][nc]) out.push([nr, nc]);}return out;}
4. Coordinated pathfinding: making four ghosts “encircle” rather than “chase”
4.1 The swarm-chase problem: why pathfinding alone isn’t enough
The most intuitive implementation is to have each ghost follow the shortest path toward the evader’s current cell. In turn-based play this creates a serious problem. Suppose four ghosts are in the same area and all target “the evader’s current cell,” so their next landing cells will very likely be the same cell. If the rules forbid overlap, they’ll “traffic jam” each other, leaving an obvious gap.
Worse, a single hunter at equal speed struggles to catch an omniscient evader, for three reasons:
- The evader can see the latest distance field on every move and always picks the direction farthest from all hunters;
- The more loops in the maze, the more room to maneuver;
- A distance field only reflects “steps” and can’t convey that a particular ghost is closing in.
So the hunters’ difficulty isn’t “how to find a path,” but “how to coordinate to cut off paths.”
4.2 Triple pressure: making “capture” computable
A clean and effective framework is to split each cell’s threat into three independent “pressure fields,” then combine them with weights:
- Pursuit pressure: the step-distance field from the evader’s current cell. Fewer steps means a more dangerous cell.
- Blocking pressure: compute the shortest path toward the evader, then spread the pressure of each cell on that path outward by several steps. Having to cross a blocking ring naturally compresses the evader’s range of movement.
- Encirclement pressure: occupy the key junctions or branch points near the evader. The more precisely you hold them, the fewer branches the evader can choose.
For an intuitive understanding, you can overlay the three pressure fields into a “heat map”: cells where red concentrates are ones the evader dares not approach, while blue areas are safe zones where hunters can advance steadily.
// Build the pressure field jointly applied by the hunters.length ghosts each turnfunction buildDangerField(maze, state, opts) {const E = state.evader.pos;const dE = bfs(maze, E);const occupied = new Set(state.hunters.map(h => key(h.pos)));const danger = new Map();for (const [k, d] of dE) {let score = 1 / (d + 1); // pursuit pressureif (d <= opts.blockRadius) score += 0.5; // blocking pressure: cut the evader's shortest pathconst [r, c] = k.split(',').map(Number);for (const nb of neighbors(maze, [r, c])) { // encirclement pressure: spread to neighboring cellsif (!occupied.has(key(nb))) danger.set(key(nb), (danger.get(key(nb)) || 0) + 0.2 / (d + 1));}danger.set(k, (danger.get(k) || 0) + score);}// In counterattack state, cells adjacent to hunters are "minefields" and need extra markingif (state.powerTurns > 0) {for (const h of state.hunters) for (const nb of neighbors(maze, h.pos)) {danger.set(key(nb), (danger.get(key(nb)) || 0) + 5);}}return { danger, dE };}// Evader decision: minimize "landing-cell pressure + pressure along the way" with a bit of randomnessfunction chooseEvaderMove(maze, state, field, opts) {const paths = neighbors(maze, state.evader.pos).map(next => {const dNext = bfs(maze, next);let cost = field.danger.get(key(next)) || 0;for (const [k, d] of dNext) {if (d <= 2) cost += 0.3 * (field.danger.get(k) || 0); // avoid paths near danger zones}return { next, cost };});paths.sort((a, b) => a.cost - b.cost || (a.next === opts.prev ? 1 : -1));// randomize on ties to avoid players memorizing the patternconst best = paths.filter(p => p.cost <= paths[0].cost + 1e-6);return best[Math.floor(opts.rng() * best.length)].next;}
4.3 Role division and overlap prevention
If four ghosts have the same “personality,” the team degenerates into a single ghost. Give each ghost a role:
- Chaser: targets a cell on the shortest path and keeps applying pressure.
- Blocker: targets a spot on the shortest path to the evader’s current cell about half a step away, cutting off the forward direction.
- Flanker: targets the nearest junction behind the evader, sealing off retreat.
- Watcher: targets, among the evader’s current cell and nearby exits, the one “most likely to lead to a large open area,” guarding a strategic point.
Two points matter when assigning roles:
- Use a “reservation cell” mechanism: destinations already chosen by other ghosts in the same turn are removed from contention, eliminating “traffic jams” at the root.
- Add task locking: the team re-plans once each time the evader reaches a new junction or travels a certain number of steps. This keeps up with the evolving situation while avoiding every ghost flip-flopping and doubling back every turn.
function chooseHunters(maze, state, field, opts) {const occupied = new Set(state.hunters.map(h => key(h.pos)));const choices = state.hunters.map((h, i) => {if (h.stunned > 0) return { i, move: h.pos }; // stunned, stay in placeconst dE = bfs(maze, state.evader.pos);const dH = bfs(maze, h.pos);const role = state.roles[i]; // role assigned when the team replansconst goals = role === 'blocker'? [...dE.keys()].filter(k => dE.get(k) === opts.halfStep): role === 'flanker'? junctionBehind(maze, state, field) // junction behind the evader: role === 'watcher'? chokepoints(maze, state) // key chokepoint cells: [key(state.evader.pos)];let best = null;for (const nb of neighbors(maze, h.pos)) {const nk = key(nb);if (occupied.has(nk)) continue; // prevent overlapconst target = goals.reduce((a, b) =>(dH.get(a) ?? 1e9) <= (dH.get(b) ?? 1e9) ? a : b);const score = -(dH.get(target) ?? 1e9); // score by "steps to target"if (!best || score > best.score) best = { i, move: nb, score };}return best || { i, move: h.pos };});for (const c of choices) occupied.add(key(c.move)); // lock in chosen destinationsreturn choices;}
4.4 Breakout logic when surrounded
Even the best hunters can find themselves “surrounded.” At that point the pressure field’s “spread” term makes nearby cells carry higher danger values, pushing ghosts to flee far away. The fix is to add an “encirclement degree” metric: the number of reachable cells within a two-cell radius centered on a given cell.
- Open ground: low encirclement degree, so advance normally under the pressure field.
- Pocket areas: encirclement degree clearly below the average, meaning the space is compressed, so head toward a direction with higher connectivity rather than continuing to hug the evader.
This may look like a detail, but it noticeably helps both the perceived quality and the win rate of the “AI hunters.”
5. Evader AI: the art of tiered difficulty
5.1 Three behavior baselines
The evader AI isn’t better the smarter it is; it should be a “difficulty dial.” The common approach is to write three baselines first:
- Random walk: pick a legal direction with equal probability, suitable for beginner levels.
- Greedy distance-keeping: each turn, pick the direction “farthest from the nearest hunter.” Simple but easy to trap.
- Pressure-field evaluation: fully account for pursuit, blocking, and encirclement pressure, and re-evaluate risk in the counterattack state. This is the implementation of
chooseEvaderMoveabove.
5.2 Behavioral motivations: collection and counterattack
A pure “hide” AI makes levels dull, because the player can win just by advancing slowly. With two added motivations, the game has real tension:
- Collection tendency: when the density of remaining dots somewhere is high and the path pressure is acceptable, the evader will actively go eat dots instead of just staying away.
- Counterattack timing: several turns before the counterattack state ends, the evader will deliberately approach the hunters to lure them into dangerous adjacent cells.
5.3 Memory and prediction
At higher difficulties, you can let the evader remember the player’s habitual patterns—for example, “which ghost always likes to flank” or “which corridor often gets blocked”—and adjust its route accordingly. Implementation needs no machine learning; just maintain a simple “corridor heat table”: the more often a corridor is blocked, the more the evader tends to avoid it.
5.4 Difficulty curve design
| Level | Ghosts | Ghost speed | Evader strategy | Power pellets | Design goal |
|---|---|---|---|---|---|
| 1 | 2 | 1 | Random walk | 2 | Learn junction decisions and basic capture |
| 2 | 3 | 1 | Greedy distance-keeping | 2 | Learn role division and blocking |
| 3 | 4 | 1 | Pressure-field evaluation | 1 | Appreciate the importance of encirclement and overlap prevention |
| 4 | 4 | 1 | Pressure field + memory | 1 | Cope with the evader’s pattern-based counters |
| 5 | 4 | 2 | Pressure field + prediction | 0 | High-pressure level testing route planning |
Each level is best changed by only one or two variables. This lets players clearly perceive why it got harder and makes it easier for developers to pinpoint the root of any imbalance.
6. Engineering the auto-pilot and level-by-level progression
6.1 Auto-pilot: turning “AI thinking” into a readable process
Auto-pilot isn’t just “clicking for the player”; it’s an important debugging and teaching tool. Engineering-wise, three things need handling:
- Asynchronous execution: run AI computation after the turn ends, and play back each ghost’s movement step by step as an animation. Players can see “why the AI moved this way.”
- Interruptible: the player can take over any ghost at any time, switching freely between delegated and manual states.
- Explainable: highlight each ghost’s current target cell in the UI so players understand the role division.
6.2 Level-by-level progression: config-driven, not hard-coded
Level progression is best achieved through “config + strategy parameters” rather than writing a separate logic set for each level:
const LEVELS = [{ hunters: 2, evader: 'random', powerTurns: 6 },{ hunters: 3, evader: 'greedy', powerTurns: 4 },{ hunters: 4, evader: 'field', powerTurns: 3 },{ hunters: 4, evader: 'memory', powerTurns: 2 },{ hunters: 4, evader: 'predict', powerTurns: 1, hunterSpeed: 2 }];
Combined with level progress saving and difficulty selection, players can advance step by step or jump straight to hard levels.
7. Collaborating with an intelligent coding tool: from prompt to playable prototype
7.1 Translating “gameplay intent” into an executable spec
The most error-prone part of human–AI collaboration isn’t the code itself but “vague requirement descriptions.” The gameplay in a developer’s head usually contains many implicit rules: who can enter whose cell, the turn order, the failure conditions. These must be written out explicitly.
A good prompt usually has four parts:
- Gameplay objective: what the player does and the win condition;
- Rule details: action order, collision判定 (collision resolution), special states;
- Data contract: level file format, function signatures;
- Acceptance criteria: runnable, reproducible, no out-of-bounds errors.
A sample structure is below (containing no specific product names):
Role: senior 2D mini-game developer, familiar with grid mazes and turn-based strategy gameplay.Task: implement a single-file HTML turn-based maze-chase game, pure frontend, zero dependencies, runnable by double-clicking.Gameplay rules:1. The player commands N ghosts to chase an AI-controlled "evader" through a character maze.2. Each turn: the player picks a direction for each ghost -> resolve movement and collisions -> the evader moves and eats dots -> check win/loss.3. After the evader eats a power pellet it enters a counterattack state for M turns; a ghost entering a cell adjacent to it is stunned and sent back to its spawn.4. A ghost cannot enter a cell already occupied; the evader cannot pass through walls.Technical requirements:- Maze, power pellets, turn limit, etc. are all provided as a config object for easy tuning;- Pathfinding uses BFS; provide a reusable distanceField(maze, start) function;- All randomness uses an injectable random source to guarantee reproducibility under the same seed;- Provide a "full auto-pilot" mode: the whole team's commands are generated by the algorithm, for automated verification.Acceptance criteria:- Run 1000 consecutive turns with no out-of-bounds, overlap, or deadlock;- In a 15×15 maze, the hunters' win rate is configurable and outputs statistics.
7.2 Iteration rhythm: get it working, then tune, then polish
It’s recommended to split development into three phases rather than generating the whole game in one shot:
- Close the loop (~1 hour): implement only “grid + turn loop + collision detection” so the game becomes playable, verifying that the rule statements are accurate.
- Tuning and balancing (~2–3 hours): plug in the distance field and pressure field, run automated matches, compute win rates and average turn counts, and adjust the number of power pellets, ghost speed, and AI strategy tier accordingly.
- Presentation polish (~1–2 hours): add animations, sound effects, a settlement screen, and mobile adaptation.
7.3 Acceptance criteria should be “measurable”
“Fun” can’t serve as an acceptance criterion, but the following metrics can:
- 1000 turns of stress testing with no anomalies;
- Results fully reproducible under a fixed random seed;
- Each level’s win rate falling within a preset range (e.g., 45%–65%);
- Average turn count within a reasonable range (e.g., 30–80 turns).
These metrics both constrain the quality of AI-generated code and serve as a basis for regression testing.
7.4 Common deviations and corrections
Three kinds of deviation are common in human–AI collaboration:
- Rule drift: the AI “optimizes” the rules on its own—for example, letting ghosts overlap or letting the evader ignore walls. The fix is to write the rules as assertions and verify them at the end of each turn.
- Value imbalance: too many power pellets keep hunters permanently at a disadvantage, or a too-weak evader AI offers no challenge. The fix is configuration + automated win-rate statistics.
- Presentation masking logic: flashy animations but wrong collision detection. The fix is to write logic tests first, then layer on the presentation.
8. Debugging checklist and troubleshooting
| Symptom | Likely cause | Where to look |
|---|---|---|
| Ghosts stay still or double back | Target cell changes every turn, no task locking | Add a lock duration and a re-planning interval |
| Four ghosts crowd onto one path | No overlap-prevention mechanism | Add reservation cells and role division |
| The evader always escapes easily | Imbalanced pressure-field weights, too many loops | Adjust weights, reduce path redundancy, or add dead ends |
| Hunters “donate kills” in the counterattack state | Insufficient penalty for danger-adjacent cells | Raise the minefield weight and add an encirclement-degree check |
| Different results under the same seed | Random source not injected, unstable iteration order | Use an injectable random source uniformly, avoid relying on object iteration order |
| Lag on mobile | Pathfinding recomputed every render frame | Move it to turn end, reuse results during the animation |
9. Conclusion: a big method behind a small game
A small game about “commanding ghosts to catch Pac-Man” isn’t a large technical undertaking, but it fully demonstrates a reusable path: write gameplay intent into precise rules, drive levels with configuration, turn “capture” into a computable strategy with a distance field and a pressure field, then use automated matches to validate balance.
The value of an intelligent coding tool isn’t writing all the code for the developer; it’s compressing the “idea to prototype” cycle down to hours. What truly decides the quality of the finished product is still the developer’s understanding of the gameplay, the rigor of their rule statements, and repeated polishing of details.
