Mini Project: Stealth Guard
Time to put the course together in one complete, classic piece of game AI: a stealth guard. The guard walks a patrol route, notices the player gradually instead of instantly, goes to check out what it saw, chases when it's sure, and gives up when it loses you. This is the core loop of every stealth game, and it uses almost every section of the course:
| Feature | Lessons |
|---|---|
| Patrol, Suspicious, Investigate and Chase states with timers | Finite State Machines |
| Vision cone: range, angle (dot product) and line of sight | Vision Cones |
| Suspicion that builds faster up close and decays when unseen | Memory & Awareness |
| Footstep noise that the guard hears | Hearing & Noise |
| BFS paths around walls | Breadth-First Search |
| Separate sense, think and act stages | Sense, Think, Act |
| A visible suspicion meter and cone colours | Field Notes: Design |
We build it twice: first as a deterministic C# simulation on a grid, where a scripted player lets us test the guard's logic and read every decision, then as a playable canvas game with real-time movement, two guards and sneaking.
Step 1: the design
suspicion >= 0.3 suspicion = 1
┌────────┐ ──────────────────► ┌────────────┐ ───────────────► ┌───────┐
│ Patrol │ │ Suspicious │ │ Chase │──► Caught
└────────┘ ◄──┐ └────────────┘ └───────┘
│ looked around, │ unseen for 3 ticks │ unseen for 2 ticks
│ found nothing ▼ │
│ ┌─────────────┐ ◄──────────────────┘
└─────────────── │ Investigate │ ── sees player, suspicion = 1 ──► Chase
└─────────────┘| State | What the guard does | Leaves when |
|---|---|---|
| Patrol | walks the route slowly (1 cell every 2 ticks) | suspicion reaches 0.3 |
| Suspicious | stops and stares; the player has a moment to hide | suspicion reaches 1 (→ Chase) or the player has been unseen for 3 ticks (→ Investigate) |
| Investigate | walks to the last known position, then looks around (turns 4 times) | sees the player with full suspicion (→ Chase) or finishes looking (→ Patrol) |
| Chase | runs (1 cell per tick) to the player's last known position | adjacent to the player (→ Caught) or unseen for 2 ticks (→ Investigate) |
Two design choices make the guard fair. Suspicion grows over several ticks while the player is visible (faster when closer), so being glimpsed at the edge of the cone is a warning, not a game over. And the Suspicious state is a pause where the guard does nothing but stare: it telegraphs "I think I saw something" and gives the player time to react.
Step 2: the simulation
The level is a grid: an upper room, a corridor along the bottom and a gap in the wall at column 4 that leads up into the room. The guard's route crosses the corridor. Two scripted players try to reach the exit E: a careless one who just walks along the corridor, and a sneaky one who backs off when noticed, hides in the room until the guard leaves, and then follows the guard at a distance.
The log prints a line only when the guard changes state, and draws the map with the guard's vision cone (:) at the moment it first becomes suspicious, which is the kind of debug drawing you'd use in an engine.
using System;
using System.Collections.Generic;
string[] map =
{
"####################",
"#.........#........#",
"#..##.....#..##....#",
"#..##..........#...#",
"#..........#.......#",
"####.#######.###...#",
"#.................E#",
"####################",
};
Run("careless", "..............RRRRRRRRRRRR");
Run("sneaky ", "..................RRR.UULL" + new string('.', 24) + "RRDDRRRRRRRRRRRRRR");
void Run(string name, string moves)
{
var world = new World(map);
var guard = new Guard(world, new[] { (8, 4), (12, 4), (12, 6), (8, 6), (12, 6), (12, 4), (8, 4), (8, 1), (3, 1), (8, 1) });
(int x, int y) player = (1, 6);
Console.WriteLine(quot;=== {name} player ===");
string last = "";
for (int t = 0; t < 90; t++)
{
char m = t < moves.Length ? moves[t] : '.';
var step = m switch { 'R' => (1, 0), 'L' => (-1, 0), 'U' => (0, -1), 'D' => (0, 1), _ => (0, 0) };
if (!world.Wall(player.x + step.Item1, player.y + step.Item2)) player = (player.x + step.Item1, player.y + step.Item2);
guard.Tick(player);
string line = quot;t={t,2} guard {guard.Pos} facing {guard.FacingName} {guard.State,-11} suspicion {guard.Suspicion:F2} player {player}";
if (guard.State != last) Console.WriteLine(line);
if (guard.State == "Suspicious" && last == "Patrol") Draw(world, guard, player);
last = guard.State;
if (guard.State == "Caught") { Console.WriteLine(quot;t={t,2} CAUGHT at {player}"); break; }
if (map[player.y][player.x] == 'E') { Console.WriteLine(quot;t={t,2} player reached the exit"); break; }
}
}
void Draw(World w, Guard g, (int x, int y) p)
{
for (int y = 0; y < map.Length; y++)
{
var row = map[y].ToCharArray();
for (int x = 0; x < row.Length; x++)
if (row[x] == '.' && g.Sees((x, y))) row[x] = ':'; // debug-draw the vision cone
if (y == g.Pos.y) row[g.Pos.x] = 'G';
if (y == p.y) row[p.x] = '@';
Console.WriteLine(" " + new string(row));
}
}
class World
{
readonly string[] rows;
public World(string[] rows) => this.rows = rows;
public bool Wall(int x, int y) => rows[y][x] == '#';
public bool LineOfSight((int x, int y) a, (int x, int y) b)
{
int dx = Math.Abs(b.x - a.x), dy = -Math.Abs(b.y - a.y);
int sx = a.x < b.x ? 1 : -1, sy = a.y < b.y ? 1 : -1, err = dx + dy;
int x = a.x, y = a.y;
while (x != b.x || y != b.y)
{
int e2 = 2 * err;
if (e2 >= dy) { err += dy; x += sx; }
if (e2 <= dx) { err += dx; y += sy; }
if ((x != b.x || y != b.y) && Wall(x, y)) return false;
}
return true;
}
// First step of a BFS path from a to b (4-neighbour), or a if unreachable.
public (int x, int y) StepTowards((int x, int y) a, (int x, int y) b)
{
if (a == b) return a;
var prev = new Dictionary<(int, int), (int, int)>();
var q = new Queue<(int x, int y)>();
q.Enqueue(b); prev[b] = b; // search backwards from the target
(int, int)[] dirs = { (1, 0), (-1, 0), (0, 1), (0, -1) };
while (q.Count > 0)
{
var c = q.Dequeue();
foreach (var (dx, dy) in dirs)
{
var n = (x: c.x + dx, y: c.y + dy);
if (Wall(n.x, n.y) || prev.ContainsKey(n)) continue;
prev[n] = c;
if (n == a) return c;
q.Enqueue(n);
}
}
return a;
}
}
class Guard
{
const double Fov = 0.7071, Range = 6; // cos(45°): a 90° cone
readonly World world; readonly (int x, int y)[] route;
int waypoint, tick, lookTicks, unseenTicks;
public (int x, int y) Pos; (int x, int y) facing = (1, 0); (int x, int y) lastKnown;
public string State = "Patrol";
public double Suspicion;
public Guard(World w, (int, int)[] route) { world = w; this.route = route; Pos = route[0]; }
public string FacingName => facing switch { (1, 0) => "E", (-1, 0) => "W", (0, 1) => "S", _ => "N" };
public bool Sees((int x, int y) p)
{
double dx = p.x - Pos.x, dy = p.y - Pos.y, d = Math.Sqrt(dx * dx + dy * dy);
if (d > Range) return false;
if (d > 0 && (dx * facing.x + dy * facing.y) / d < Fov) return false;
return world.LineOfSight(Pos, p);
}
void MoveTo((int x, int y) target)
{
var next = world.StepTowards(Pos, target);
if (next != Pos) facing = (next.x - Pos.x, next.y - Pos.y);
Pos = next;
}
public void Tick((int x, int y) player)
{
tick++;
bool sees = Sees(player);
if (sees)
{
double dist = Math.Sqrt(Math.Pow(player.x - Pos.x, 2) + Math.Pow(player.y - Pos.y, 2));
Suspicion = Math.Min(1, Suspicion + 0.15 + 0.25 * (1 - dist / Range)); // closer = faster
lastKnown = player; unseenTicks = 0;
}
else { Suspicion = Math.Max(0, Suspicion - 0.04); unseenTicks++; }
switch (State)
{
case "Patrol":
if (Suspicion >= 0.3) { State = "Suspicious"; break; }
if (Pos == route[waypoint]) waypoint = (waypoint + 1) % route.Length;
if (tick % 2 == 0) MoveTo(route[waypoint]); // walk slowly
break;
case "Suspicious": // stop and stare
if (Suspicion >= 1) State = "Chase";
else if (unseenTicks >= 3) { State = "Investigate"; lookTicks = 0; }
break;
case "Investigate":
if (Suspicion >= 1 && sees) { State = "Chase"; break; }
if (Pos != lastKnown) MoveTo(lastKnown);
else if (++lookTicks <= 4) facing = (-facing.y, facing.x); // look around
else { State = "Patrol"; Suspicion = 0; }
break;
case "Chase":
if (!sees && unseenTicks >= 2) { State = "Investigate"; lookTicks = 0; break; }
MoveTo(lastKnown);
if (Math.Abs(Pos.x - player.x) + Math.Abs(Pos.y - player.y) <= 1) State = "Caught";
break;
}
}
}=== careless player ===
t= 0 guard (8, 4) facing E Patrol suspicion 0.00 player (1, 6)
t=19 guard (11, 6) facing W Suspicious suspicion 0.43 player (7, 6)
####################
#.........#........#
#..##.....#..##....#
#..##..........#...#
#..........#.......#
####.#######.###...#
#....::@:::G......E#
####################
t=21 guard (11, 6) facing W Chase suspicion 1.00 player (9, 6)
t=22 guard (10, 6) facing W Caught suspicion 1.00 player (10, 6)
t=22 CAUGHT at (10, 6)
=== sneaky player ===
t= 0 guard (8, 4) facing E Patrol suspicion 0.00 player (1, 6)
t=21 guard (10, 6) facing W Suspicious suspicion 0.30 player (4, 6)
####################
#.........#........#
#..##.....#..##....#
#..##..........#...#
#..........#.......#
####.#######.###...#
#...@:::::G.......E#
####################
t=24 guard (10, 6) facing W Investigate suspicion 0.18 player (3, 4)
t=35 guard (4, 6) facing W Patrol suspicion 0.00 player (2, 4)
t=67 player reached the exit
Read the two stories:
- Careless: the guard turns into the corridor at t=17 facing west, and at t=18 the player walks into the cone. Suspicion builds on every tick in view (0.19, 0.43, 0.70, 1.00), a little faster each time as the player gets closer, the guard switches to Chase at t=21 and catches the player one tick later.
- Sneaky: the guard glimpses the player at the far edge of its range (6 cells), so suspicion grows slowly and only reaches 0.30 at t=21. The player goes up through the gap and is out of sight; after three unseen ticks the guard investigates the last known position (4, 6), looks around, and finds nothing because the wall at (3, 5) blocks its view of the hiding spot. At t=35 it resumes the patrol. The player waits, follows the guard at a distance, and escapes at t=67.
Because the simulation is deterministic, these two stories are a regression test. Change a number (cone width, suspicion rate, search time) and rerun: if the careless player suddenly escapes or the sneaky one gets caught, you see exactly when and why.
Tip: The suspicion numbers are where the game's difficulty lives. Try
Range = 7or a faster suspicion rate and watch the sneaky player get caught. Real games expose these per guard type and per difficulty level, and playtest them heavily.
Step 3: the playable version
The canvas version uses the same states and rules with continuous movement, plus two additions:
- Hearing. Walking makes noise in a 70-pixel radius (the blue ring). A guard that hears you becomes suspicious and investigates the spot. Hold Shift to sneak: half speed, but silent.
- Two guards with their own routes. Each one is an independent copy of the same state machine.
Vision uses the same three tests as the C# model (range, angle, line of sight), with the angle test written with atan2 and the line of sight marched in 4-pixel steps through the tile map. The cone is drawn by casting 25 rays that stop at walls, so you see exactly what the guard can see. The cone colour and the meter above the guard's head show its state: white (patrol), yellow (suspicious or investigating), red with "!" (chase).
Click the frame and reach the green exit. Arrow keys or WASD move, Shift sneaks.
<style>
html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set(); // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
if (!e.repeat) pressed.add(e.code);
keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
ctx.save();
ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
ctx.restore();
}
function run(update, draw, help = '') {
const STEP = 1 / 60;
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
const dt = Math.min((now - last) / 1000, 0.1);
last = now;
if (active) {
acc += dt;
while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
draw();
} else if (!idleDrawn) {
draw(); banner('Click to play', help); idleDrawn = true;
}
requestAnimationFrame(frame);
});
}
// ---- end of play kit ----
// ---------- saving: localStorage if allowed, memory otherwise ----------
const store = (() => {
const mem = new Map();
try {
localStorage.setItem('__probe', '1');
localStorage.removeItem('__probe');
return { get: (k) => localStorage.getItem(k), set: (k, v) => localStorage.setItem(k, String(v)) };
} catch { // sandboxed frame, privacy mode...
return { get: (k) => mem.get(k) ?? null, set: (k, v) => mem.set(k, String(v)) };
}
})();
// ---------- the level ----------
const MAP = [
'########################',
'#......#...............#',
'#......#....######.....#',
'#..##..#.........#.....#',
'#..##............#..#..#',
'####.#####.......#..#..#',
'#........#.....###..#..#',
'#........#.............#',
'#..##....######.....####',
'#..##..................#',
'#..........#..........E#',
'########################',
];
const T = 20, TOP = 30; // tile size, HUD height
const COLS = MAP[0].length, ROWS = MAP.length;
const wallAt = (tx, ty) => tx < 0 || ty < 0 || tx >= COLS || ty >= ROWS || MAP[ty][tx] === '#';
const solid = (x, y) => wallAt(Math.floor(x / T), Math.floor(y / T));
const centre = (tx, ty) => ({ x: tx * T + T / 2, y: ty * T + T / 2 });
// Is the straight line from a to b free of walls? (march in small steps)
function lineOfSight(a, b) {
const d = Math.hypot(b.x - a.x, b.y - a.y), n = Math.ceil(d / 4);
for (let i = 1; i < n; i++) if (solid(a.x + (b.x - a.x) * i / n, a.y + (b.y - a.y) * i / n)) return false;
return true;
}
// Next tile centre on a BFS path from point a to point b.
function nextWaypoint(a, b) {
const sx = Math.floor(a.x / T), sy = Math.floor(a.y / T), gx = Math.floor(b.x / T), gy = Math.floor(b.y / T);
if (sx === gx && sy === gy) return b;
const prev = new Map([[gy * COLS + gx, -1]]), queue = [[gx, gy]]; // search back from the goal
while (queue.length) {
const [x, y] = queue.shift();
for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
const nx = x + dx, ny = y + dy, k = ny * COLS + nx;
if (nx === sx && ny === sy) return y === gy && x === gx ? b : centre(x, y); // even if we clipped a wall
if (wallAt(nx, ny) || prev.has(k)) continue;
prev.set(k, y * COLS + x);
queue.push([nx, ny]);
}
}
return a;
}
// ---------- guards: Patrol -> Suspicious -> Investigate -> Chase ----------
const RANGE = 140, HALF_FOV = 0.7, HEAR = 70; // pixels, radians (an 80° cone), pixels
function makeGuard(route) {
const p = centre(...route[0]);
return { x: p.x, y: p.y, angle: 0, route, wp: 0, state: 'Patrol', suspicion: 0, unseen: 0, look: 0, last: null };
}
let guards, player, result, timeTaken, best = Number(store.get('stealth-guard-best')) || 0, noise = 0;
function reset() {
guards = [
makeGuard([[11, 3], [21, 3], [21, 7], [16, 9], [11, 9], [11, 7]]),
makeGuard([[2, 6], [7, 7], [7, 10], [2, 10]]),
];
player = { ...centre(1, 1), r: 6 };
result = null; timeTaken = 0;
}
function canSee(g, p) {
const dx = p.x - g.x, dy = p.y - g.y, d = Math.hypot(dx, dy);
if (d > RANGE) return false;
let diff = Math.atan2(dy, dx) - g.angle;
diff = Math.atan2(Math.sin(diff), Math.cos(diff)); // wrap to -PI..PI
return Math.abs(diff) <= HALF_FOV && lineOfSight(g, p);
}
function turnTowards(g, target, rate, dt) {
let diff = Math.atan2(target.y - g.y, target.x - g.x) - g.angle;
diff = Math.atan2(Math.sin(diff), Math.cos(diff));
g.angle += Math.max(-rate * dt, Math.min(rate * dt, diff));
}
function walk(g, target, speed, dt) {
const wp = nextWaypoint(g, target);
const dx = wp.x - g.x, dy = wp.y - g.y, d = Math.hypot(dx, dy);
if (d < 1) return true;
const s = Math.min(d, speed * dt);
g.x += dx / d * s; g.y += dy / d * s;
turnTowards(g, wp, 6, dt);
return Math.hypot(target.x - g.x, target.y - g.y) < 2;
}
function updateGuard(g, dt) {
const d = Math.hypot(player.x - g.x, player.y - g.y);
const sees = canSee(g, player);
if (sees) {
g.suspicion = Math.min(1, g.suspicion + dt * (0.6 + 1.8 * (1 - d / RANGE))); // closer = faster
g.last = { x: player.x, y: player.y }; g.unseen = 0;
} else {
g.unseen += dt;
if (g.state !== 'Chase') g.suspicion = Math.max(0, g.suspicion - 0.12 * dt);
}
if (noise > 0 && d < HEAR && g.state !== 'Chase') { // heard footsteps
g.suspicion = Math.max(g.suspicion, 0.4);
g.last = { x: player.x, y: player.y };
}
switch (g.state) {
case 'Patrol': {
if (g.suspicion >= 0.35) { g.state = 'Suspicious'; break; }
const target = centre(...g.route[g.wp]);
if (walk(g, target, 40, dt)) g.wp = (g.wp + 1) % g.route.length;
break;
}
case 'Suspicious':
turnTowards(g, g.last, 3, dt);
if (g.suspicion >= 1) g.state = 'Chase';
else if (g.unseen > 1.2) { g.state = 'Investigate'; g.look = 0; }
break;
case 'Investigate':
if (g.suspicion >= 1 && sees) { g.state = 'Chase'; break; }
if (g.look === 0 && !walk(g, g.last, 60, dt)) break;
g.look += dt; g.angle += 2.2 * dt; // arrived: look around
if (g.look > 2.8) { g.state = 'Patrol'; g.suspicion = 0; }
break;
case 'Chase':
if (!sees && g.unseen > 1.5) { g.state = 'Investigate'; g.look = 0; g.suspicion = 0.6; break; }
walk(g, g.last, 88, dt);
if (d < 14) result = 'caught';
break;
}
}
function movePlayer(dt) {
let mx = 0, my = 0;
if (keys.has('ArrowLeft') || keys.has('KeyA')) mx -= 1;
if (keys.has('ArrowRight') || keys.has('KeyD')) mx += 1;
if (keys.has('ArrowUp') || keys.has('KeyW')) my -= 1;
if (keys.has('ArrowDown') || keys.has('KeyS')) my += 1;
const sneaking = keys.has('ShiftLeft') || keys.has('ShiftRight');
const len = Math.hypot(mx, my) || 1, speed = sneaking ? 38 : 75;
const r = player.r;
const blocked = (x, y) => solid(x - r, y - r) || solid(x + r, y - r) || solid(x - r, y + r) || solid(x + r, y + r);
const nx = player.x + mx / len * speed * dt;
if (!blocked(nx, player.y)) player.x = nx; // move one axis at a time
const ny = player.y + my / len * speed * dt;
if (!blocked(player.x, ny)) player.y = ny;
noise = (mx || my) && !sneaking ? 0.3 : Math.max(0, noise - dt); // footsteps linger briefly
if (MAP[Math.floor(player.y / T)][Math.floor(player.x / T)] === 'E') result = 'escaped';
}
function update(dt) {
if (result) {
if (pressed.has('Space') || pressed.has('Enter') || pressed.has('KeyR')) reset();
return;
}
timeTaken += dt;
movePlayer(dt);
for (const g of guards) updateGuard(g, dt);
if (result === 'escaped' && (!best || timeTaken < best)) { best = timeTaken; store.set('stealth-guard-best', best.toFixed(1)); }
}
// ---------- drawing ----------
const CONE = { Patrol: 'rgba(255,255,255,0.12)', Suspicious: 'rgba(255,200,0,0.22)', Investigate: 'rgba(255,160,0,0.18)', Chase: 'rgba(255,60,60,0.28)' };
function drawCone(g) {
ctx.beginPath(); ctx.moveTo(g.x, g.y);
for (let i = 0; i <= 24; i++) { // one ray per edge point, clipped by walls
const a = g.angle - HALF_FOV + (2 * HALF_FOV * i) / 24;
let len = 0;
while (len < RANGE && !solid(g.x + Math.cos(a) * len, g.y + Math.sin(a) * len)) len += 3;
ctx.lineTo(g.x + Math.cos(a) * len, g.y + Math.sin(a) * len);
}
ctx.closePath(); ctx.fillStyle = CONE[g.state]; ctx.fill();
}
function draw() {
ctx.fillStyle = '#12141c'; ctx.fillRect(0, 0, W, H);
ctx.save(); ctx.translate(0, TOP);
for (let y = 0; y < ROWS; y++) for (let x = 0; x < COLS; x++) {
const c = MAP[y][x];
ctx.fillStyle = c === '#' ? '#3a3f52' : c === 'E' ? '#2e9e5b' : '#1b1f2b';
ctx.fillRect(x * T, y * T, T, T);
}
for (const g of guards) drawCone(g);
if (noise > 0) { ctx.strokeStyle = 'rgba(120,180,255,0.35)'; ctx.beginPath(); ctx.arc(player.x, player.y, HEAR, 0, Math.PI * 2); ctx.stroke(); }
ctx.fillStyle = '#5fb3ff'; ctx.beginPath(); ctx.arc(player.x, player.y, player.r, 0, Math.PI * 2); ctx.fill();
for (const g of guards) {
ctx.fillStyle = '#e8e8e8'; ctx.beginPath(); ctx.arc(g.x, g.y, 7, 0, Math.PI * 2); ctx.fill();
ctx.strokeStyle = '#000'; ctx.beginPath(); ctx.moveTo(g.x, g.y); ctx.lineTo(g.x + Math.cos(g.angle) * 7, g.y + Math.sin(g.angle) * 7); ctx.stroke();
if (g.suspicion > 0) { // the suspicion meter telegraphs danger
ctx.fillStyle = '#000'; ctx.fillRect(g.x - 10, g.y - 16, 20, 4);
ctx.fillStyle = g.suspicion >= 1 ? '#ff4040' : '#ffc800'; ctx.fillRect(g.x - 10, g.y - 16, 20 * g.suspicion, 4);
ctx.font = 'bold 12px system-ui, sans-serif'; ctx.textAlign = 'center';
ctx.fillText(g.state === 'Chase' ? '!' : '?', g.x, g.y - 19);
}
}
ctx.restore();
ctx.fillStyle = '#ddd'; ctx.font = '12px system-ui, sans-serif'; ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
ctx.fillText(`Reach the green exit time ${timeTaken.toFixed(1)} s best ${best ? best.toFixed(1) + ' s' : '-'}`, 8, TOP / 2);
ctx.textAlign = 'right';
ctx.fillText(`guards: ${guards.map((g) => g.state).join(', ')}`, W - 8, TOP / 2);
if (result === 'caught') banner('Caught!', 'Press Space to try again');
if (result === 'escaped') banner(`Escaped in ${timeTaken.toFixed(1)} s`, 'Press Space to play again');
}
reset();
run(update, draw, 'Arrows/WASD to move, hold Shift to sneak');
</script>How the pieces map to the course:
| In the code | Concept |
|---|---|
canSee |
a vision cone: distance, angle wrapped to −π..π, then the expensive line-of-sight test last |
g.last, g.unseen |
memory: the last known position and how long ago it was seen |
noise, HEAR |
hearing: a radius around the player while walking; footsteps linger for 0.3 s |
nextWaypoint |
BFS on the tile grid, searched backwards from the goal so the first step is read directly |
updateGuard's switch |
the state machine from Step 1 |
| cone colours, suspicion meter, "?" and "!" | telegraphing the AI's state to the player (Field Notes: Design) |
The best escape time is saved through a small storage wrapper: localStorage when the page allows it, and an in-memory Map otherwise. Inside the lesson's sandboxed frame storage is blocked, so the record lasts until you reload.
Extensions
Pick one or two and build them on top of either version:
- Shared alerts. When a guard enters Chase, it writes the player's position to a squad blackboard and the other guard investigates it.
- Distractions. Press E to throw a stone: a noise event at a point the player chooses, so the guard walks away from the route.
- Smoother paths. Apply path smoothing so the guard walks in straight lines instead of tile by tile.
- Search pattern. Instead of turning on the spot, Investigate visits the 2–3 nearest hiding spots around the last known position, scored like cover points.
- A behavior tree. Rewrite
updateGuardas a behavior tree with Chase, Investigate and Patrol branches, and compare which version is easier to extend. - Difficulty levels. Put range, cone angle, suspicion rate and chase speed in a table per difficulty, and make the simulation from Step 2 check that the sneaky route still escapes on Normal.
Test yourself
Why does the guard build suspicion over several ticks instead of chasing as soon as the player is in the cone?
- To save CPU
- So a brief glimpse is a warning the player can react to, which makes stealth fair and readable
- Because line-of-sight checks are slow
- Because the cone is too small
In the sneaky run, why didn't the guard find the player while looking around at (4, 6)?
- The player was out of range
- A wall blocked the line of sight to the hiding spot
- The guard was in Patrol
- Suspicion was 1
What is the benefit of running the guard logic as a deterministic simulation with scripted players?
- It looks better
- It acts as a regression test: tuning changes show exactly when and why outcomes change
- It replaces playtesting
- It makes the guard smarter