Game AI Exercises
Time to practise. Each exercise has a starter playground that already compiles and runs, but behaves wrongly. Fix the TODO parts, press ▶ Run, and compare your result with the expected output. When you're done, or stuck, open the solution.
Tip: There's always more than one correct solution. If your output matches, your answer is right.
Exercise 1: Stop the flicker
The guard below flips between Chase (c) and Attack (A) whenever the player hovers around 2 m. Add hysteresis: start attacking at 2.0 m, but only stop beyond 3.0 m. See Finite State Machines. Expected output:
retry HTTP 502
ccAAAAAcc switches: 2using System;
// The guard attacks within 2.0 m. TODO: only stop attacking beyond 3.0 m (hysteresis).
double[] distances = { 3.5, 2.4, 1.9, 2.1, 1.8, 2.6, 2.2, 3.1, 2.9 };
string state = "Chase", log = "";
int switches = 0;
foreach (double d in distances)
{
string next = state;
if (state == "Chase" && d <= 2.0) next = "Attack";
if (state == "Attack" && d > 2.0) next = "Chase";
if (next != state) switches++;
state = next;
log += state == "Attack" ? "A" : "c";
}
Console.WriteLine(quot;{log} switches: {switches}");ccAcAcccc switches: 4
Show solution
using System;
// Enter Attack at 2.0 m, leave it only beyond 3.0 m.
double[] distances = { 3.5, 2.4, 1.9, 2.1, 1.8, 2.6, 2.2, 3.1, 2.9 };
string state = "Chase", log = "";
int switches = 0;
foreach (double d in distances)
{
string next = state;
if (state == "Chase" && d <= 2.0) next = "Attack";
if (state == "Attack" && d > 3.0) next = "Chase";
if (next != state) switches++;
state = next;
log += state == "Attack" ? "A" : "c";
}
Console.WriteLine(quot;{log} switches: {switches}");With the wider exit threshold the guard commits to its attack until the player is clearly out of reach.
Exercise 2: Write a selector
The selector below always fails without ticking anything. Implement it: tick the children left to right and return the first status that isn't Failure; return Failure if every child fails. Notice that patrol must not be ticked. See Behavior Trees. Expected output:
flee (low health): Failure
attack (in range): Failure
chase (sees player): Running
Root returned Runningusing System;
// TODO: implement Selector.Tick: tick children in order, return the first status that isn't Failure.
var tree = new Selector("Root",
new Leaf("flee (low health)", Status.Failure),
new Leaf("attack (in range)", Status.Failure),
new Leaf("chase (sees player)", Status.Running),
new Leaf("patrol", Status.Running));
Console.WriteLine(quot;Root returned {tree.Tick()}");
enum Status { Success, Failure, Running }
abstract class Node { public abstract Status Tick(); }
class Leaf : Node
{
readonly string name; readonly Status result;
public Leaf(string name, Status result) { this.name = name; this.result = result; }
public override Status Tick() { Console.WriteLine(quot; {name}: {result}"); return result; }
}
class Selector : Node
{
readonly string name; readonly Node[] kids;
public Selector(string name, params Node[] kids) { this.name = name; this.kids = kids; }
public override Status Tick()
{
return Status.Failure; // TODO
}
}Root returned Failure
Show solution
using System;
var tree = new Selector("Root",
new Leaf("flee (low health)", Status.Failure),
new Leaf("attack (in range)", Status.Failure),
new Leaf("chase (sees player)", Status.Running),
new Leaf("patrol", Status.Running));
Console.WriteLine(quot;Root returned {tree.Tick()}");
enum Status { Success, Failure, Running }
abstract class Node { public abstract Status Tick(); }
class Leaf : Node
{
readonly string name; readonly Status result;
public Leaf(string name, Status result) { this.name = name; this.result = result; }
public override Status Tick() { Console.WriteLine(quot; {name}: {result}"); return result; }
}
class Selector : Node
{
readonly string name; readonly Node[] kids;
public Selector(string name, params Node[] kids) { this.name = name; this.kids = kids; }
public override Status Tick()
{
foreach (var k in kids)
{
Status s = k.Tick();
if (s != Status.Failure) return s; // Success or Running: stop here
}
return Status.Failure;
}
}chase returns Running, so the selector stops there: lower-priority branches aren't ticked at all.
Exercise 3: A panic curve
The soldier never retreats. Give Retreat a logistic response to danger, 1 / (1 + e^(-10 · (danger − 0.6))), multiplied by (1 − health), so a wounded soldier in danger falls back while a healthy one keeps fighting. See Utility AI. Expected output:
health 0.9 danger 0.2: attack 0.81 heal 0.08 retreat 0.00 -> Attack
health 0.9 danger 0.8: attack 0.54 heal 0.02 retreat 0.09 -> Attack
health 0.3 danger 0.8: attack 0.18 heal 0.14 retreat 0.62 -> Retreat
health 0.3 danger 0.3: attack 0.26 heal 0.49 retreat 0.03 -> Healusing System;
// A soldier picks the action with the highest score.
// TODO: give "Retreat" a logistic curve on danger: 1 / (1 + e^(-10 * (danger - 0.6))),
// multiplied by (1 - health). Right now it always scores 0.
foreach (var (health, danger) in new[] { (0.9, 0.2), (0.9, 0.8), (0.3, 0.8), (0.3, 0.3) })
{
double attack = health * (1 - danger * 0.5);
double heal = (1 - health) * (1 - danger);
double retreat = 0; // TODO
string best = attack >= heal && attack >= retreat ? "Attack" : heal >= retreat ? "Heal" : "Retreat";
Console.WriteLine(quot;health {health:F1} danger {danger:F1}: attack {attack:F2} heal {heal:F2} retreat {retreat:F2} -> {best}");
}health 0.9 danger 0.2: attack 0.81 heal 0.08 retreat 0.00 -> Attack
health 0.9 danger 0.8: attack 0.54 heal 0.02 retreat 0.00 -> Attack
health 0.3 danger 0.8: attack 0.18 heal 0.14 retreat 0.00 -> Attack
health 0.3 danger 0.3: attack 0.26 heal 0.49 retreat 0.00 -> Heal
Show solution
using System;
// A soldier picks the action with the highest score.
foreach (var (health, danger) in new[] { (0.9, 0.2), (0.9, 0.8), (0.3, 0.8), (0.3, 0.3) })
{
double attack = health * (1 - danger * 0.5);
double heal = (1 - health) * (1 - danger);
double retreat = 1 / (1 + Math.Exp(-10 * (danger - 0.6))) * (1 - health);
string best = attack >= heal && attack >= retreat ? "Attack" : heal >= retreat ? "Heal" : "Retreat";
Console.WriteLine(quot;health {health:F1} danger {danger:F1}: attack {attack:F2} heal {heal:F2} retreat {retreat:F2} -> {best}");
}The logistic curve barely reacts below a danger of about 0.4 and rises steeply around 0.6, which reads as "panic" rather than gradual nervousness.
Exercise 4: Arrive without overshooting
The agent moves at full speed until it reaches the target, overshoots, and then oscillates around it forever. Implement arrive: inside an 8-unit slowing radius, scale the speed by distance / slowRadius. See Seek, Flee & Arrive. Expected output:
step 1: x = 3.00
step 2: x = 6.00
step 3: x = 9.00
step 4: x = 12.00
step 5: x = 15.00
step 6: x = 16.88
step 7: x = 18.05
step 8: x = 18.78
step 9: x = 19.24
step 10: x = 19.52using System;
const double maxSpeed = 3, slowRadius = 8, dt = 1;
double x = 0, target = 20;
for (int step = 1; step <= 10; step++)
{
double toTarget = target - x;
double speed = maxSpeed; // TODO: inside slowRadius, use maxSpeed * distance / slowRadius
x += Math.Sign(toTarget) * speed * dt;
Console.WriteLine(quot;step {step,2}: x = {x,5:F2}");
}step 1: x = 3.00
step 2: x = 6.00
step 3: x = 9.00
step 4: x = 12.00
step 5: x = 15.00
step 6: x = 18.00
step 7: x = 21.00
step 8: x = 18.00
step 9: x = 21.00
step 10: x = 18.00
Show solution
using System;
const double maxSpeed = 3, slowRadius = 8, dt = 1;
double x = 0, target = 20;
for (int step = 1; step <= 10; step++)
{
double toTarget = target - x;
double dist = Math.Abs(toTarget);
double speed = dist < slowRadius ? maxSpeed * dist / slowRadius : maxSpeed;
x += Math.Sign(toTarget) * speed * dt;
Console.WriteLine(quot;step {step,2}: x = {x,5:F2}");
}The agent slows down smoothly and approaches 20 without ever passing it. In a game you'd also snap to the target once it's within a small tolerance.
Exercise 5: Fix the BFS
This breadth-first search never skips walls, cells outside the grid or cells it has already reached, so it runs away until a safety limit stops it. Add the three checks. See Breadth-First Search. Expected output:
S to G: 15 stepsusing System;
using System.Collections.Generic;
string[] grid =
{
"S..#....",
".#.#.##.",
".#...#..",
".####.#.",
"......#G",
};
(int x, int y) start = (0, 0), goal = (7, 4);
// BFS: distance in steps from S to every reachable cell.
var dist = new Dictionary<(int, int), int> { [start] = 0 };
var queue = new Queue<(int x, int y)>();
queue.Enqueue(start);
(int dx, int dy)[] dirs = { (1, 0), (-1, 0), (0, 1), (0, -1) };
while (queue.Count > 0)
{
var c = queue.Dequeue();
foreach (var (dx, dy) in dirs)
{
var n = (x: c.x + dx, y: c.y + dy);
// TODO: skip n if it is outside the grid, a wall '#', or already in dist
dist[n] = dist[c] + 1;
queue.Enqueue(n);
}
if (dist.Count > 200) { Console.WriteLine("runaway search: cells are visited again and again"); break; }
}
Console.WriteLine(dist.TryGetValue(goal, out int d) ? quot;S to G: {d} steps" : "G is unreachable");runaway search: cells are visited again and again
G is unreachable
Show solution
using System;
using System.Collections.Generic;
string[] grid =
{
"S..#....",
".#.#.##.",
".#...#..",
".####.#.",
"......#G",
};
(int x, int y) start = (0, 0), goal = (7, 4);
// BFS: distance in steps from S to every reachable cell.
var dist = new Dictionary<(int, int), int> { [start] = 0 };
var queue = new Queue<(int x, int y)>();
queue.Enqueue(start);
(int dx, int dy)[] dirs = { (1, 0), (-1, 0), (0, 1), (0, -1) };
while (queue.Count > 0)
{
var c = queue.Dequeue();
foreach (var (dx, dy) in dirs)
{
var n = (x: c.x + dx, y: c.y + dy);
if (n.y < 0 || n.y >= grid.Length || n.x < 0 || n.x >= grid[0].Length) continue;
if (grid[n.y][n.x] == '#' || dist.ContainsKey(n)) continue;
dist[n] = dist[c] + 1;
queue.Enqueue(n);
}
}
Console.WriteLine(dist.TryGetValue(goal, out int d) ? quot;S to G: {d} steps" : "G is unreachable");The dist.ContainsKey check is what makes BFS visit every cell once; the first time a cell is reached is via a shortest path.
Exercise 6: A vision cone
The guard "sees" everything within 10 units, even behind it. Add the angle test: the point is visible only if the cosine of the angle between facing and the direction to the point is at least cos(30°). Compute that cosine with a dot product. See Vision Cones. Expected output:
ahead dist 8.00 SEEN
slightly left dist 7.62 SEEN
wide left dist 6.40 -
behind dist 3.00 -
far ahead dist 12.04 -using System;
// A guard at (0, 0) faces along +x. It sees a point when the point is within 10 units
// and within 30 degrees of the facing direction (a 60-degree cone).
(double x, double y) facing = (1, 0);
var points = new (string name, double x, double y)[]
{
("ahead", 8, 0), ("slightly left", 7, 3), ("wide left", 4, 5), ("behind", -3, 0), ("far ahead", 12, 1),
};
foreach (var (name, x, y) in points)
{
double dist = Math.Sqrt(x * x + y * y);
bool sees = dist <= 10; // TODO: also require dot(facing, direction to point) >= cos(30°)
Console.WriteLine(quot;{name,-14} dist {dist,5:F2} {(sees ? "SEEN" : "-")}");
}ahead dist 8.00 SEEN
slightly left dist 7.62 SEEN
wide left dist 6.40 SEEN
behind dist 3.00 SEEN
far ahead dist 12.04 -
Show solution
using System;
// A guard at (0, 0) faces along +x. It sees a point when the point is within 10 units
// and within 30 degrees of the facing direction (a 60-degree cone).
(double x, double y) facing = (1, 0);
var points = new (string name, double x, double y)[]
{
("ahead", 8, 0), ("slightly left", 7, 3), ("wide left", 4, 5), ("behind", -3, 0), ("far ahead", 12, 1),
};
foreach (var (name, x, y) in points)
{
double dist = Math.Sqrt(x * x + y * y);
double cosAngle = (facing.x * x + facing.y * y) / dist; // facing is unit length
bool sees = dist <= 10 && cosAngle >= Math.Cos(30 * Math.PI / 180);
Console.WriteLine(quot;{name,-14} dist {dist,5:F2} {(sees ? "SEEN" : "-")}");
}Comparing cosines avoids calling Math.Acos for every target. In a real game you'd also compute cos(30°) once, not per check, and run the line-of-sight raycast last because it's the most expensive test.
Test yourself
In Exercise 5, what does the 'already in dist' check guarantee?
- That walls are skipped
- That each cell is enqueued once, so BFS terminates and the first distance found is the shortest
- That the grid wraps around
- That the goal is reachable
Why compare cos(angle) against cos(30°) instead of computing the angle with acos?
- acos doesn't exist in C#
- It gives the same answer without an extra trigonometric call, because cosine decreases as the angle grows from 0° to 180°
- It's less accurate on purpose
- Because angles must be in degrees