Skip to content

C++ Fast Track for Games Programming Part 16: AI

C++ Fast Track

In part 15, the tanks got physics: they drive, slide along obstacles, and push drums around. But the red tank is still rather dumb: it drives back and forth along a road, whatever you do. In this part, we give it a brain. Artificial intelligence (AI) in games is about making computer-controlled characters behave in a way that looks smart, and is fun to play against. By the end of this part, you will have an arena battle against waves of enemy tanks that:

  1. see you (but only when you are in front of them, close enough, and not behind an obstacle),
  2. aim and fire at you (but not perfectly),
  3. and decide what to do: patrol, chase you, attack you, or search for you when they lose you.

One important idea before we start: intelligent doesn’t mean perfect. A computer can aim perfectly and react instantly, but an enemy that never misses isn’t fun. Good game AI makes mistakes on purpose, so that the player can win, and feels clever doing so.

For this tutorial, you will start where part 15 ended: the tank game with physics. Download it here:

Download the starting point for part 16 as a zip filepart-16.zip

Extract the zip file to C:\Projects\C++ Fast Track: it contains a Part 16 folder. Open tmpl8.slnx in the C:\Projects\C++ Fast Track\Part 16 folder.

The code from the end of part 15, with one difference: the tow cable is gone (and so is the code that only the cable used: KeepDistance, DrawCable, and the keys 1, 2 and 3). It has no job in a battle. The drums are still there: they make good cover. The assets folder has two new images: shells.png, a shell in 16 directions (a green one and a red one), and explosion.png, the 5 frames of an explosion. Like the other images, both are made from Top-down Tanks Remastered by Kenney, who shares them for free (under the CC0 license).

The starting point: the tank game of part 15. (Click the demo first, so that it gets the keys.)

A battle needs weapons. The player drives with the keys, aims the turret with the mouse, and fires with the left mouse button.

First, the game needs to know where the mouse is, and whether its left button is down. Open game.hpp, and change the mouse methods:

game.hpp
// button 1 is the left mouse button
void MouseUp( int button ) { if (button == 1) mouseDown = false; }
void MouseDown( int button ) { if (button == 1) mouseDown = mousePressed = true; }
void MouseMove( int x, int y ) { mousex = x, mousey = y; }

And add these variables, in the private part of the class (below frame):

game.hpp
int mousex = 0, mousey = 0; // the position of the mouse
bool mouseDown = false; // true while the left mouse button is held down
bool mousePressed = false; // true when the left mouse button went down (Tick sets it back to false)

The template calls MouseMove when the mouse moves, and MouseDown and MouseUp when a button goes down or up (button 1 is the left mouse button). mouseDown is true as long as the button is held down. But a quick click can go down and up between two frames: then Tick would never see mouseDown as true. That’s what mousePressed is for: it remembers that the button went down, until Tick has seen it.

The barrel of a tank can point in another direction than its body. Both have 16 frames, so we need the frame that faces a direction twice. Move that code out of Drive, into a function of its own:

game.cpp
// The frame (0 to 15) that faces a direction: 0 is up, 4 is right, 8 is down, 12 is left.
int FrameOf(vec2 direction)
{
const float angle = std::atan2(direction.x, -direction.y); // 0 is up, PI / 2 is right
return (static_cast<int>(std::round(angle / (2 * PI) * 16)) + 16) % 16;
}

Add a few constants for the weapons below the other constants:

game.cpp
constexpr float Acceleration = 0.003f; // how fast a tank speeds up, in pixels per millisecond per millisecond
constexpr float TankDrag = 0.02f; // how fast a tank slows down: this part of its speed is lost every millisecond
constexpr float TankMass = 10; // a tank is ten times as heavy as a drum
constexpr int MaxHealth = 100;
constexpr float ReloadTime = 400; // milliseconds between two shots

The tank gets two new methods, Aim and Fire, and three new variables:

game.cpp
class Tank
{
public:
Tank(vec2 startPosition, int startFrame, int startColor)
{
body.position = startPosition;
body.drag = TankDrag;
body.radius = 20;
body.inverseMass = 1 / TankMass;
frame = startFrame;
color = startColor;
}
void Drive(vec2 direction);
void Aim(vec2 target);
void Fire();
void Update();
void Draw(Surface& target) const;
Body body;
int frame; // the direction: 0 is up, 4 is right, 8 is down, 12 is left
int color; // the row in tank.png: 0 is green, 1 is red
vec2 aim = { 0, -1 }; // the direction of the barrel, with length 1
float reload = 0; // milliseconds until the tank can fire again
int health = MaxHealth;
float patrol = 1; // for the enemy: 1 drives to the right, -1 to the left
};
  • aim is the direction of the barrel, as a vector with length 1. It starts pointing up.
  • reload counts down: a tank can only fire when it is 0 (or less).
  • health starts at MaxHealth. Every hit takes some of it.

Update Drive to use FrameOf now:

game.cpp
// Drives the tank in a direction (a vector with length 1, or 0 to brake).
void Tank::Drive(vec2 direction)
{
body.drive = direction * Acceleration;
// face the direction in which the tank drives: one of the 16 frames
if (body.velocity.length() > 0.01f)
frame = FrameOf(body.velocity);
}

Aim turns the barrel towards a target: a position on the screen, for example the mouse:

game.cpp
// Turns the barrel towards a target: a position on the screen.
void Tank::Aim(vec2 target)
{
const vec2 difference = target - body.position;
const float length = difference.length(); // (one square root, for both the test and the normalization)
if (length > 0)
aim = difference / length;
}

The direction from the tank to the target is the difference of the two positions. Dividing it by its length gives it a length of 1. normalized would do that too, but we need the length anyway, for the test, and normalized would calculate it again: a second square root. So we calculate the length once, and use it twice. When the target is exactly the middle of the tank, there is no direction, and the barrel stays as it is.

Draw uses the direction of the barrel for the barrel’s frame, and draws a health bar above the tank:

game.cpp
void Tank::Draw(Surface& target) const
{
tank.SetFrame(frame, color);
barrel.SetFrame(FrameOf(aim), color);
const int x = static_cast<int>(body.position.x), y = static_cast<int>(body.position.y);
tank.Draw(target, x - 32, y - 32);
barrel.Draw(target, x - 32, y - 32);
// the health bar, above the tank: green for the health that is left, dark for the rest. Bar doesn't check the
// edges of the screen, so near the top of the map, the bar goes below the tank instead.
const int width = 32 * health / MaxHealth;
const int top = y >= 34 ? y - 34 : y + 28;
target.Bar(x - 16, top, x + 15, top + 3, 0x202020);
if (width > 0)
target.Bar(x - 16, top, x - 17 + width, top + 3, health > MaxHealth / 3 ? 0x40e040 : 0xe04040);
}

The health bar is a dark bar of 32 pixels, with a green part (red when the health is low) that is as wide as the part of the health that is left: 32 * health / MaxHealth.

A shell flies in a straight line, until it hits something, or its time is up. Shells are not bodies: they are much faster than the tanks, nothing pushes them around, and they disappear when they hit something anyway. (A shell does push a drum when it hits it, but we’ll handle that ourselves later, instead of leaving it to the physics engine.) Shells get a struct of their own, with an array of them. Add this below bodyCount:

game.cpp
// Shells fly in a straight line, until they hit something or their time is up. They are not bodies: they are too
// fast and too small for the physics, and they disappear when they hit something anyway.
struct Shell
{
vec2 position, velocity;
float time = 0; // milliseconds left; 0 when the shell isn't flying
int color; // the row in shells.png: 0 is green, 1 is red
};
constexpr int MaxShells = 32;
constexpr float ShellSpeed = 0.5f, ShellRadius = 4, ShellTime = 1500;
constexpr int ShellDamage = 20;
Shell shells[MaxShells];

Like the drums, there is a fixed number of shells. A shell with a time of 0 (or less) is free for reuse: when a tank fires, Fire looks for a free shell and sends it on its way.

UpdateShells uses Explode, which comes in the next section, with the rest of the explosion code. C++ reads the code from top to bottom, so it has to know about Explode before UpdateShells can use it. A forward declaration tells the compiler that a function exists before it is defined, just like the declarations of the methods in a class (see part 12). Add it below the shells:

game.cpp
// Explode is further down, with the rest of the explosion code. C++ reads the code from top to bottom, so we need to
// declare Explode here: that tells the compiler that the function exists, before UpdateShells uses it.
void Explode(vec2 position);

Every frame, the shells move, and we check what they hit. That’s the job of UpdateShells. It’s a long function, so we’ll break it down into a few parts. First, update the shell’s position:

game.cpp
// Moves the shells, and checks what they hit: a tank loses health, a drum gets a push, and an obstacle stops them.
void UpdateShells(float deltaTime, Tank* tanks[], int tankCount)
{
for (int i = 0; i < MaxShells; i++)
{
Shell& shell = shells[i]; // a reference: changing shell changes shells[i]
if (shell.time <= 0)
continue; // this shell isn't flying: on to the next one
// the shell flies on in a straight line, and has a bit less time left
shell.time -= deltaTime;
shell.position += shell.velocity * deltaTime;

The loop goes over all shells. shell is a reference, so changing shell changes the shell in the array. A shell with no time left isn’t flying: continue skips the rest of the loop for that shell, and goes on with the next one. A flying shell moves in a straight line, like the bodies of part 15 (but without drag), and has a bit less time left.

Then we check whether the shell hits a tank:

game.cpp
// What does the shell hit?
const Circle circle = { shell.position, ShellRadius };
bool hit = false;
for (int t = 0; t < tankCount; t++)
{
Tank& tank = *tanks[t]; // tanks[t] is a pointer so we need to use * to dereference it
if (tank.health > 0 && Overlaps(circle, Circle{ tank.body.position, tank.body.radius }))
{
tank.health -= ShellDamage; // a tank that is hit loses health (a destroyed tank can't be hit)
hit = true;
}
}

This uses the overlap tests of part 15: the shell is a small circle, and so is a tank. tanks is an array of pointers to tanks (see part 8), so that the function can change the health of the tanks themselves, not of copies. *tanks[t] is the tank that tanks[t] points to, and the reference tank gives it a short name, so that we don’t have to keep writing tanks[t]-> every time.

A shell that hits a tank takes ShellDamage of its health: 5 hits destroy a tank. A destroyed tank (with no health left) can’t be hit anymore. hit is a boolean variable which we’ll set to true if the bullet should explode.

The drums are next:

game.cpp
for (int d = 0; d < drumCount; d++)
{
Body& drum = drums[d];
if (Overlaps(circle, Circle{ drum.position, drum.radius }))
{
drum.velocity += shell.velocity * 0.5f; // a light drum gets a good push
hit = true;
}
}

A drum is a circle too, and drum is a reference to the drum in the array, like shell. A shell that hits a drum gives it a push: a part of the shell’s velocity. The drum is light, so it flies away.

Then the obstacles of the map:

game.cpp
// the obstacles of the map (trees, crates, walls, ...) simply stop the shell
for (int c = 0; c < circleCount; c++)
if (Overlaps(circle, circles[c]))
hit = true;
for (int b = 0; b < boxCount; b++)
if (Overlaps(circle, boxes[b]))
hit = true;

A shell that hits an obstacle (any of the colliders, including the walls around the map) just stops. Finally:

game.cpp
// a shell that hit something explodes, and is free again for the next shot
if (hit)
{
Explode(shell.position);
shell.time = 0;
}
}
}

Regardless of what the shell hit, it explodes, and its time becomes 0 so it’s free again for the next shot.

DrawShells draws the flying shells:

game.cpp
// Draws the flying shells: each one facing the direction in which it flies, in the colour of its tank.
void DrawShells(Surface& target)
{
for (int i = 0; i < MaxShells; i++)
{
const Shell& shell = shells[i];
if (shell.time > 0)
{
shellSprite.SetFrame(FrameOf(shell.velocity), shell.color);
shellSprite.Draw(target, static_cast<int>(shell.position.x) - 12, static_cast<int>(shell.position.y) - 12);
}
}
}

A shell’s frame is the frame of its direction (FrameOf again), and its row in shells.png is its colour. shell is a reference again, but a const one: drawing a shell doesn’t change it.

A shell that hits something explodes. An explosion is an animation that plays for a moment, so the game has to remember it for a few frames:

game.cpp
// An explosion is just an animation: 5 frames of explosion.png.
struct Explosion
{
vec2 position;
float time = 0; // milliseconds left; 0 when it is over
};
constexpr int MaxExplosions = 16;
constexpr float ExplosionTime = 400;
Explosion explosions[MaxExplosions];

Like the shells, there is a fixed number of explosions. To start one:

game.cpp
// Starts an explosion at a position, in a free spot of the array (if there is one).
void Explode(vec2 position)
{
for (int i = 0; i < MaxExplosions; i++)
if (explosions[i].time <= 0)
{
explosions[i] = { position, ExplosionTime };
return;
}
}

Explode starts an explosion in a free spot of the array (if there is one: with more than 16 explosions at the same time, one is simply not shown).

Every frame, the explosions get older, until they are over:

game.cpp
// The explosions get older: an explosion with no time left is over, and its spot in the array is free again.
void UpdateExplosions(float deltaTime)
{
for (int i = 0; i < MaxExplosions; i++)
explosions[i].time -= deltaTime;
}

DrawExplosions draws the explosions:

game.cpp
// Draws the explosions that aren't over yet.
void DrawExplosions(Surface& target)
{
for (int i = 0; i < MaxExplosions; i++)
{
const Explosion& explosion = explosions[i];
if (explosion.time > 0)
{
// the first frame when the explosion starts, the last one when it ends
explosionSprite.SetFrame(static_cast<int>((1 - explosion.time / ExplosionTime) * 5));
explosionSprite.Draw(target, static_cast<int>(explosion.position.x) - 32, static_cast<int>(explosion.position.y) - 32);
}
}
}

An explosion shows the first frame of explosion.png when it starts, and the last one when its time is almost up.

Now the tanks can fire. Fire sends a free shell on its way:

game.cpp
// Fires a shell from the end of the barrel, if the tank has reloaded.
void Tank::Fire()
{
if (reload > 0)
return;
for (int i = 0; i < MaxShells; i++)
if (shells[i].time <= 0)
{
shells[i] = { body.position + aim * 30, aim * ShellSpeed, ShellTime, color };
reload = ReloadTime;
return;
}
}

The shell starts 30 pixels in front of the middle of the tank (at the end of the barrel, and outside the tank’s own circle), and flies in the direction of the barrel. Its colour is the colour of the tank: green or red. Then the tank has to reload.

body.position: the middle of the tank aim * 30: 30 pixels along the barrel the new shell starts here 30 pixels from the middle, all around the tank's collision circle: a radius of 20 Made with Claude

Where a shell starts: 30 pixels from the middle of the tank, in the direction of the barrel (aim), not of the tank itself. That’s outside the tank’s own circle (a radius of 20), so the tank doesn’t shoot itself.

Finally, Tick. The player aims at the mouse, reloads, and fires:

game.cpp
player.Drive(direction);
player.Aim({ static_cast<float>(mousex), static_cast<float>(mousey) });
player.reload -= deltaTime;
if (mouseDown || mousePressed)
player.Fire(); // click, or hold the left mouse button to keep firing
mousePressed = false;

Then the shells move, the explosions get older, and when the enemy is destroyed, it explodes, and starts over at its starting point:

game.cpp
Simulate(deltaTime);
Tank* tanks[2] = { &player, &enemy };
UpdateShells(deltaTime, tanks, 2);
UpdateExplosions(deltaTime);
if (enemy.health <= 0)
{
// a big explosion, and the enemy starts over on the left, as good as new
Explode(enemy.body.position);
enemy.body.position = enemy.body.previous = { 32, 4 * TileSize + 32 };
enemy.body.velocity = {};
enemy.health = MaxHealth;
}

And the shells and the explosions are drawn on top of the tanks:

game.cpp
enemy.Draw(screen);
DrawShells(screen);
DrawExplosions(screen);

When you press Tab, the flying shells show their circles too, like the other colliders:

game.cpp
for (int i = 0; i < bodyCount; i++)
DrawCircle(screen, { bodies[i]->position, bodies[i]->radius }, 0xffff00);
for (int i = 0; i < MaxShells; i++)
{
const Shell& shell = shells[i];
if (shell.time > 0)
DrawCircle(screen, { shell.position, ShellRadius }, 0xffff00); // the flying shells too
}

Aim with the mouse, and click (or hold the button) to fire. Shells explode on obstacles, push drums away, and 5 hits destroy the red tank. (Click the demo first, so that it gets the keys.)

An enemy should only attack what it can see. That’s three questions: is the player close enough, is he in front of the enemy, and is there an obstacle in between?

For the obstacles, we need a new kind of test: does a line (from the enemy to the player) cross a collider? Add these two functions below the overlap tests. First a circle:

game.cpp
// Does the line from a to b cross the circle? Finds the point on the line that is closest to the middle of the
// circle, like ClosestPoint does for a box.
bool Crosses(vec2 a, vec2 b, const Circle& circle)
{
const vec2 line = b - a;
const float length2 = line.sqrLength();
// how far along the line the closest point is: 0 at a, 1 at b
const float t = length2 > 0 ? std::clamp((circle.center - a).dot(line) / length2, 0.0f, 1.0f) : 0;
const vec2 closest = a + t * line;
return (circle.center - closest).length() < circle.radius;
}

This is like the circle - box test of part 15, which looks for the point of the box that is closest to the middle of the circle. Here, we look for the point of the line that is closest to the middle of the circle. Every point of the line from aa to bb is a+t (b−a)a + t\,(b - a), for some tt between 0 (at aa) and 1 (at bb). The closest point has

t=(c−a)⋅(b−a)∣b−a∣2t = \frac{(c - a) \cdot (b - a)}{|b - a|^2}

where cc is the middle of the circle. The dot product measures how far cc lies along the line (part 15 used the dot product for that too, in Push). Clamping tt between 0 and 1 keeps the point on the line. Then the line crosses the circle when that point is closer to the middle than the radius.

Drag aa or bb to move one end of the line, drag the line itself to move both ends, or drag the circle to move it. The purple arrow is c−ac - a. The dot product with b−ab - a gives the yellow part: how far cc lies along the line, where a line from cc meets it at a right angle. Divided by the length of the line, that is tt: 0 at aa, 1 at bb. The axes at the bottom and the left show the same thing for xx and yy: the line from t=0t = 0 to t=1t = 1, the yellow part, and the closest point. When the closest point would be beyond aa or bb (the grey dot), tt is clamped to 0 or 1.

A box takes a different trick: look at one axis at a time:

game.cpp
// Does the line from a to b cross the box? The part of the line between the left and the right side of the box is
// a range of t (0 at a, 1 at b); so is the part between the top and the bottom. The line crosses the box when the
// two ranges overlap, somewhere between 0 and 1.
bool Crosses(vec2 a, vec2 b, const Box& box)
{
float first = 0, last = 1; // the range of t that is inside the box on both axes (so far)
const float start[2] = { a.x, a.y }, step[2] = { b.x - a.x, b.y - a.y };
const float low[2] = { box.min.x, box.min.y }, high[2] = { box.max.x, box.max.y };
for (int axis = 0; axis < 2; axis++)
{
if (step[axis] == 0)
{
// the line runs parallel to these sides: it is between them all the time, or never
if (start[axis] < low[axis] || start[axis] >= high[axis])
return false;
continue;
}
float t1 = (low[axis] - start[axis]) / step[axis], t2 = (high[axis] - start[axis]) / step[axis];
if (t1 > t2)
std::swap(t1, t2); // the line runs from high to low on this axis
first = std::max(first, t1);
last = std::min(last, t2);
if (first > last)
return false; // the ranges don't overlap: the line misses the box
}
return true;
}
  • On the x axis, the line enters the space between the left and the right side of the box at some tt, and leaves it at another tt. Same for the y axis: between the top and the bottom.
  • The line is inside the box where it is between the left and right sides and between the top and bottom sides: where both ranges of tt overlap. But the line starts at aa and ends at bb, so only values of tt between 0 and 1 count. That’s why first and last start as 0 and 1, and each axis can only make that range smaller.
  • When the range is empty (first > last), the line misses the box.
  • When the line is exactly horizontal (or vertical), it never crosses the left and right sides (or the top and bottom): it’s between them all the way, or never. Then there is nothing to divide by, so that is handled separately.

This is called the slab test: the space between two opposite sides is a slab, and a box is where the slabs of both axes overlap.

Drag aa or bb to move one end of the line, drag the line itself to move both ends, or drag the box to move it. The dots show where the line enters and leaves each slab. Along the bottom, the line runs from t=0t = 0 (at aa) to t=1t = 1 (at bb) next to the purple x slab; along the left, the same line next to the yellow y slab. The green part, on the line and on both axes, is where the line is inside both slabs: from first to last.

Now the three questions together. Add these below the Tank::Draw method:

game.cpp
constexpr float SightRange = 350; // how far a tank can see, in pixels
constexpr float FieldOfView = 0.5f; // the cosine of half the field of view: 0.5 is 60 degrees to each side
// Can the tank see the point? It must be close enough, in front of the turret (inside the field of view), and no
// obstacle may block the line from the tank to the point.
bool CanSee(const Tank& tank, vec2 point)
{
const vec2 difference = point - tank.body.position;
const float distance = difference.length();
if (distance > SightRange)
return false; // too far away
if (distance > 0 && tank.aim.dot(difference / distance) < FieldOfView)
return false; // outside the field of view
for (int i = 0; i < circleCount; i++)
if (Crosses(tank.body.position, point, circles[i]))
return false;
for (int i = 0; i < boxCount; i++)
if (Crosses(tank.body.position, point, boxes[i]))
return false;
return true;
}
  • Too far away: then it can’t see the point.
  • The field of view: the dot product of two vectors with length 1 is the cosine of the angle between them. 1 means the same direction, 0 means 90° apart, and -1 opposite directions. So when the dot product of the tank’s aim and the direction to the point is less than 0.5 (the cosine of 60°), then the point is more than 60° to the side and is outside the field of view of the enemy.
  • An obstacle in between: If the line from the tank to the point crosses a collider, then the enemy can’t see the player.

All of these points determine if the enemy can see the player. This is demonstrated in the interactive demo below:

Drag the tank, the end of its barrel (to aim), the player, or the obstacles. The three questions are at the top: the line turns red as soon as one of them says no, and the obstacles in the way turn red too. The sliders change SightRange and the field of view (FieldOfView is the cosine of the angle to each side).

Now let’s put CanSee to work: the enemy’s turret should follow the player while the enemy can see him. Until now, Tank::Update pointed the turret in the direction the enemy drives (aim = { patrol, 0 }). Remove that line, so that Update only drives the enemy:

game.cpp
// The enemy drives to the right and back; it turns around when it is blocked.
void Tank::Update()
{
if (body.velocity.x * patrol < 0.001f)
patrol = -patrol; // (almost) not moving in the patrol direction
Drive({ patrol, 0 });
}

The turret is aimed in Game::Tick instead, right after enemy.Update(): the enemy itself doesn’t know where the player is, but the game does.

game.cpp
enemy.Update();
// the enemy's turret follows the player while it can see him; otherwise, it looks where it drives
const bool seen = CanSee(enemy, player.body.position);
if (seen)
enemy.Aim(player.body.position);
else
enemy.Aim(enemy.body.position + vec2{ enemy.patrol, 0 }); // a point right in front of it
  • When the enemy can see the player, Aim turns its turret towards the player: the same Aim that turns the player’s turret towards the mouse.
  • When it can’t, the turret looks where the enemy drives again. Aim needs a position to aim at, not a direction, so we give it a point right in front of the enemy: its position plus { enemy.patrol, 0 }, one step to the right or to the left.
  • The answer of CanSee goes in a variable, seen, because we’ll use it once more below, for the debug drawing.

To see what the enemy sees, Tab draws its view cone: the two edges of its field of view, as long as it can see. And a line to the player: green when the enemy can see him, red when it can’t. Add this to the drawing of the colliders:

game.cpp
// what the enemy sees: its view cone (the two edges of the field of view), and the line to the player
const vec2 e = enemy.body.position, p = player.body.position;
const float c = FieldOfView, s = std::sqrt(1 - c * c); // the cosine and the sine of half the field of view
const vec2 left = { enemy.aim.x * c + enemy.aim.y * s, enemy.aim.y * c - enemy.aim.x * s };
const vec2 right = { enemy.aim.x * c - enemy.aim.y * s, enemy.aim.y * c + enemy.aim.x * s };
screen.Line(e.x, e.y, e.x + left.x * SightRange, e.y + left.y * SightRange, 0xffffff);
screen.Line(e.x, e.y, e.x + right.x * SightRange, e.y + right.y * SightRange, 0xffffff);
screen.Line(e.x, e.y, p.x, p.y, seen ? 0x40e040 : 0xe04040);

The edges are the direction of the turret, turned 60° to both sides. Turning a vector by an angle θ\theta uses its cosine and sine: here, they are 0.5 and 1−0.52\sqrt{1 - 0.5^2}.

Press Tab, and drive around the red tank: hide behind the trees and crates, get out of its range, or behind its back, and watch the line. (Click the demo first, so that it gets the keys.)

So far, the enemy can only patrol and aim at the player. In this section, we teach it to fire back. But not perfectly: an enemy that reacts instantly, turns its turret instantly and never misses, would destroy you before you even see it. So we add three imperfections:

  1. A reaction time: the enemy must see the player for a moment, before it reacts.
  2. A turret that turns at a limited speed: drive fast, and its aim lags behind.
  3. A spread: its shells fly a little bit off.

To turn the turret step by step, we need two helpers. Add them below FrameOf. The first one turns a vector by an angle:

game.cpp
// The vector v, turned by an angle (in radians, clockwise on the screen, because y points down).
vec2 Rotate(vec2 v, float angle)
{
const float c = std::cos(angle), s = std::sin(angle);
return { v.x * c - v.y * s, v.x * s + v.y * c };
}

This is the formula of a rotation: x′=xcos⁡θ−ysin⁡θx' = x \cos\theta - y \sin\theta and y′=xsin⁡θ+ycos⁡θy' = x \sin\theta + y \cos\theta. (The view cone of the last section used it already, with the cosine and the sine of 60°.)

The TurnTowards function turns a direction vector towards another direction, clamped to a maximum turn angle:

game.cpp
// Turns the direction from towards the direction to, but at most by maxAngle (both directions have length 1).
vec2 TurnTowards(vec2 from, vec2 to, float maxAngle)
{
const float cross = from.x * to.y - from.y * to.x; // positive: to is clockwise from from
const float angle = std::atan2(cross, from.dot(to)); // the angle from from to to, between -PI and PI
return Rotate(from, std::clamp(angle, -maxAngle, maxAngle));
}

TurnTowards finds the angle from one direction to the other: the cross product x1y2−y1x2x_1 y_2 - y_1 x_2 says on which side the other direction is, and the dot product how far it is. std::atan2 turns those two into an angle, between −π-\pi and π\pi. Then the angle is clamped to at most maxAngle, so the direction turns, but no further than that.

Drag the dots at the ends of from and to. The dashed arc is the angle from from to to, and the shaded wedge shows how far from may turn: maxAngle to both sides. The green arc is the turn that is made, and ends at the result. The sliders set how fast the turret turns, in degrees per second, and the number of frames per second (FPS). One frame takes deltaTime = 1 / FPS, and maxAngle is the turret speed times deltaTime.

Press Step to play one frame, or Play to play it at frames per second. With a few frames per second, from turns in big jumps that stop at the edge of the wedge. With 60 frames per second, the wedge is tiny, and from turns smoothly. Either way, it takes about the same time to get there.

Add the constants of the imperfections:

game.cpp
constexpr float ReactionTime = 400; // how long an enemy must see the player before it reacts, in milliseconds
constexpr float TurretSpeed = 0.003f; // how fast an enemy turns its turret, in radians per millisecond
constexpr float Spread = 0.06f; // how far an enemy's shell can be off, in radians (to both sides)

Fire gets a spread: the shell flies in the direction of the barrel, turned by a random angle between -spread and spread. (Rand comes with the template: Rand(x) is a random number from 0 up to x.) The player fires with a spread of 0: he aims himself.

game.cpp
// Fires a shell from the end of the barrel, if the tank has reloaded. With a spread, the shell flies in a random
// direction that is at most spread radians off.
void Tank::Fire(float spread)
{
if (reload > 0)
return;
for (int i = 0; i < MaxShells; i++)
if (shells[i].time <= 0)
{
const vec2 direction = Rotate(aim, Rand(2 * spread) - spread);
shells[i] = { body.position + aim * 30, direction * ShellSpeed, ShellTime, color };
reload = ReloadTime;
return;
}
}

The enemy’s Update becomes Think: it gets to know the target, and the time. Change the declarations in the Tank class:

game.cpp
void Fire(float spread = 0);
void Think(const Tank& target, float deltaTime);

The Fire method takes the spread parameter that that determines how accurate the bullet is. The = 0 is a default argument: when you leave the argument out, as the player’s Fire() does, spread is 0. (The default argument is only specified in the declaration of the method, not in it’s definition.) Think replaces Update, and gets the tank it should look for, and the change in time since the last frame.

The enemy also has to remember something from one frame to the next: how long it has been since it noticed the player. We’ll use this parameter to compute the reaction time. Add the noticed member variable below patrol:

game.cpp
float noticed = 0; // for the enemy: how long it has seen the player, in milliseconds

That’s the reaction time at work: Think adds to noticed every frame the enemy sees the player, and the enemy only reacts once noticed reaches ReactionTime.

Remove Update, and add Think below CanSee (it uses CanSee, so it must come after it):

game.cpp
// The enemy's brain. It drives to the right and back (it turns around when it is blocked). When it has seen the target
// for a moment, it turns its turret towards it, and fires when it aims well enough.
void Tank::Think(const Tank& target, float deltaTime)
{
if (body.velocity.x * patrol < 0.001f)
patrol = -patrol; // (almost) not moving in the patrol direction
Drive({ patrol, 0 });
if (CanSee(*this, target.body.position))
noticed += deltaTime;
else
noticed = 0;
vec2 wanted = { patrol, 0 }; // where the turret should point: where the tank drives...
if (noticed > ReactionTime)
wanted = (target.body.position - body.position).normalized(); // ...or at the target, once noticed
aim = TurnTowards(aim, wanted, TurretSpeed * deltaTime);
reload -= deltaTime;
if (noticed > ReactionTime && aim.dot(wanted) > 0.98f)
Fire(Spread); // aimed well enough: fire!
}
  • The driving is the same as before.
  • noticed adds up the time that the enemy has seen the target, and starts over at 0 when it loses sight of it. Only after ReactionTime, the enemy reacts.
  • wanted is where the turret should point: where the enemy drives, or at the target once it is noticed. TurnTowards turns the turret towards it, but at most TurretSpeed radians per millisecond.
  • The enemy fires when the turret points close enough at the target: the dot product of aim and wanted is more than 0.98, which is within 11°.

In Tick, the enemy thinks:

game.cpp
enemy.Think(player, deltaTime);

And the player can be destroyed now. For now, he starts over too:

game.cpp
if (player.health <= 0)
{
// for now, the player starts over where he started, as good as new
Explode(player.body.position);
player.body.position = player.body.previous = { 3 * TileSize + 32, 2 * TileSize + 32 };
player.body.velocity = {};
player.health = MaxHealth;
}

Now the red tank fires back. Drive past it quickly: its turret can’t keep up. Stay in its sight, and it hits you. (Click the demo first, so that it gets the keys.)

Try the constants: a ReactionTime of 0, a TurretSpeed of 1 and a Spread of 0 make an enemy that hits you every time. That’s not fun at all. Tuning these numbers is how game designers set the difficulty.

The enemy still drives back and forth, whatever happens. A real opponent decides what to do: drive around when it doesn’t know where you are, come after you when it sees you, stop to fire when you are close, and look for you when it loses you. The most common way to organize such decisions is a finite state machine: the enemy is always in one of a few states, each state has its own behaviour, and transitions say when it switches to another state.

Patrol Chase Attack Search sees the player close far away loses sight search time up sees the player Made with Claude

The four states of an enemy, and when it switches.

A state is one of a few fixed values: that’s what an enum class is for. Add the State enum and the AttackRange and SearchTime constants below the other constants:

game.cpp
constexpr float AttackRange = 250; // closer than this, an enemy stops to fire; further away, it chases
constexpr float SearchTime = 3000; // how long an enemy looks around where it lost the player, in milliseconds
// What an enemy is doing.
enum class State
{
Patrol, // driving to random spots, until it sees the player
Chase, // driving towards the player, who is too far away to attack
Attack, // standing still, and firing at the player
Search // driving to where it lost the player, and looking around there
};

State::Patrol, State::Chase and so on are the four possible values of a State. They are called enumerators: named constants of the type State. The compiler checks that you only use these values: a State can’t be 7, or the string "Chase", by accident.

The enemy remembers its state, its goal, and a timer, instead of patrol:

game.cpp
// for the enemy only:
State state = State::Patrol;
vec2 goal; // where it drives to: a random spot (Patrol), or where it saw the player (Search)
float noticed = 0; // how long it has seen the player, in milliseconds
float timer = 0; // milliseconds: how long it has been stuck (Patrol), or has searched (Search)

For the patrols, the enemy needs random places to drive to. Add this below CanSee:

game.cpp
// A random spot in the middle of a tile without an object: a goal for an enemy on patrol.
vec2 RandomSpot()
{
while (true)
{
const int x = IRand(MapWidth), y = IRand(MapHeight);
if (objects[y][x] == -1)
return { x * TileSize + 32.0f, y * TileSize + 32.0f };
}
}

IRand(n) comes with the template: a random whole number from 0 up to n - 1. The loop tries random tiles until it finds one without an object.

Now Think becomes the state machine. It’s a long function, so we’ll go through it piece by piece: replace Think with the code of the blocks below, from top to bottom.

First, the enemy finds out what it knows:

game.cpp
// The enemy's brain: a state machine. In each state, the enemy drives and aims in its own way, and it checks whether
// it should switch to another state.
void Tank::Think(const Tank& target, float deltaTime)
{
// what the enemy knows: whether it sees the target (long enough to react), and how far away the target and its goal are
if (CanSee(*this, target.body.position))
noticed += deltaTime;
else
noticed = 0;
const bool seen = noticed > ReactionTime;
const vec2 toTarget = target.body.position - body.position;
const float distance = toTarget.length();
const vec2 toGoal = goal - body.position;
const float goalDistance = toGoal.length();
vec2 direction; // where to drive (zero: brake)
vec2 look = aim; // where to point the turret
switch (state)
{
  • seen is true when the enemy has seen the target long enough to react, like before.
  • toTarget and distance say where the target is, and toGoal and goalDistance where the enemy’s goal is. They are calculated once, here at the top, because several states need them.
  • direction and look are what the states decide: where to drive, and where to point the turret. direction starts at zero, so a state that doesn’t set it makes the tank brake. look starts at aim, so a state that doesn’t set it leaves the turret where it is.
  • The switch picks the code of the current state. Each case ends with break, so only the code of that one state runs.

In the Patrol state, the enemy drives around, to random spots:

game.cpp
case State::Patrol:
if (goalDistance > 40)
direction = toGoal / goalDistance;
look = direction;
// a new goal when it got there, or when it is stuck (behind an obstacle) for a second
timer = body.velocity.length() < 0.02f ? timer + deltaTime : 0;
if (goalDistance <= 40 || timer > 1000)
{
goal = RandomSpot();
timer = 0;
}
if (seen)
state = State::Chase; // (Chase switches to Attack when the target is close)
break;

The enemy points its direction towards its goal, unless it is already within 40 pixels of it, and it wants to look in that same direction. When it gets to its goal, it picks another spot. It also picks another spot when it’s stuck behind an obstacle. The timer adds up the time that the tank hardly moves, and starts over at 0 as soon as it moves again. After a second of being stuck, it gives up on that spot. When it sees the target, it switches to the Chase state. It does that even when the target is close, because Chase switches to Attack in the next frame.

In the Chase state, the enemy comes after the target:

game.cpp
case State::Chase:
direction = toTarget / distance;
look = direction;
if (!seen)
{
state = State::Search;
timer = 0;
}
else if (distance < AttackRange)
state = State::Attack;
break;

Both direction and look point straight at the target. When the enemy loses sight of the target, it switches to the Search state, and the timer is reset to 0 so that it doesn’t keep searching forever. If the target is within attack range, it switches to the Attack state.

In the Attack state, the enemy stands still and fires at the target:

game.cpp
case State::Attack:
look = toTarget / distance; // stand still, and aim at the target
if (!seen)
{
state = State::Search;
timer = 0;
}
else if (distance > AttackRange * 1.2f)
state = State::Chase; // (a bit further than AttackRange, so that it doesn't switch back and forth)
else if (aim.dot(look) > 0.98f)
Fire(Spread); // aimed well enough at the target: fire!
break;

direction stays zero, so the tank will brake, and look points at the target. The enemy fires when the dot product of aim and look is more than 0.98, which means that its turret points within 11° of the target. (Fire itself checks whether the tank has reloaded.) When it loses sight of the target, it goes back to the Search state, and when the target is too far away, it goes back to the Chase state.

Note the AttackRange * 1.2f: if Attack switched to Chase at exactly the same distance as Chase switches to Attack, an enemy at that distance would switch every frame. The difference between the two distances is called hysteresis.

In the Search state, the enemy looks for the target where it last saw it:

game.cpp
case State::Search:
if (goalDistance > 40)
direction = toGoal / goalDistance; // drive to where it saw the target...
look = Rotate(aim, 0.002f * deltaTime); // ...and look around, by turning the turret
timer += deltaTime;
if (seen)
state = State::Chase;
else if (timer > SearchTime)
{
state = State::Patrol;
goal = RandomSpot();
timer = 0;
}
break;

Just like in Patrol, the enemy points its direction towards goal (the last known location of the target), unless it is already within 40 pixels of it. In that case, direction stays zero and the enemy brakes. To look around, the enemy wants to look a little to the side of where it is aiming now, so look is the current aim rotated by a small angle (0.002 radians per millisecond). The timer counts how long the enemy has been searching. If it sees the target again, it switches to Chase. If it searches for longer than SearchTime, it gives up and goes back to Patrol with a new random goal.

After the switch comes the code that all states share:

game.cpp
}
if (seen)
goal = target.body.position; // remember where it saw the target last, for Search
Drive(direction);
aim = TurnTowards(aim, look, TurretSpeed * deltaTime);
reload -= deltaTime;
}
  • While the enemy sees the target, it updates the target’s position in goal. When it loses the target, that’s where it will go to search.
  • It drives in the direction and turns its turret towards look. In Search, look is always a little ahead of the aim, so the turret keeps turning.
  • It counts down the reload timer. That happens in every state, not only in Attack (where it fires).

The enemy needs a goal to patrol to from the start. So let’s give it a random goal. Add this to the end of the Init method:

game.cpp
bodies[bodyCount++] = &player.body;
bodies[bodyCount++] = &enemy.body;
for (int i = 0; i < drumCount; i++)
bodies[bodyCount++] = &drums[i];
enemy.goal = RandomSpot(); // where the enemy patrols to first
}

When the enemy is destroyed in Tick, it starts over on the left. It should also start over in the Patrol state, with a new goal, and not go on chasing or searching where it left off:

game.cpp
if (enemy.health <= 0)
{
// a big explosion, and the enemy starts over on the left, as good as new
Explode(enemy.body.position);
enemy.body.position = enemy.body.previous = { 32, 4 * TileSize + 32 };
enemy.body.velocity = {};
enemy.health = MaxHealth;
enemy.state = State::Patrol;
enemy.goal = RandomSpot();
}

And with Tab, show the state of the enemy above it, and its goal as a small magenta circle:

game.cpp
const char* names[4] = { "PATROL", "CHASE", "ATTACK", "SEARCH" };
screen.Print(names[static_cast<int>(enemy.state)], static_cast<int>(e.x) - 16, static_cast<int>(e.y) - 44, 0xffffff);
DrawCircle(screen, { enemy.goal, 8 }, 0xff40ff); // its goal (a random spot, or where it saw the player)

The names are in the same order as the values of State. The static_cast<int> turns a state into its number (0 for Patrol, 1 for Chase, and so on), and that number is the index of its name in the array.

Press Tab to see the enemy’s state and goal. Let it find you, then hide behind a tree, and watch it search for you. (Click the demo first, so that it gets the keys.)

Time for a battle: waves of enemies. Wave 1 has 1 enemy, wave 2 has 2, and so on, up to 5 at the same time. Destroy all enemies of a wave, and the next wave comes. Every enemy destroyed is a point; and when you are destroyed, the game is over.

Instead of one enemy, there is an array of them. An array of objects needs a default constructor (a constructor that doesn’t take any arguments), to make the objects before the game knows their positions. The easiest way to do this is to give the constructor default arguments and let the compiler generate the constructors that take 0, 1, 2, or 3 arguments:

game.cpp
Tank(vec2 startPosition = {}, int startFrame = 0, int startColor = 1)

Now Tank enemies[MaxEnemies]; makes 5 tanks with the default values: red ones (colour 1) at position (0, 0). Replace enemy by the enemies, and the variables of the battle:

game.cpp
// The enemies of the arena. Wave 1 has 1 enemy, wave 2 has 2, and so on, up to MaxEnemies. An enemy that isn't in
// the battle (destroyed, or not needed in this wave) waits far outside the map, where it's never in the way.
constexpr int MaxEnemies = 5;
Tank enemies[MaxEnemies];
int wave = 0, score = 0;
float waveTimer = 0; // milliseconds until the next wave starts (when all enemies are destroyed)
bool gameOver = false;

The array of bodies needs room for all enemies:

game.cpp
Body* bodies[1 + MaxEnemies + MaxDrums];

An enemy that isn’t in the battle (it was destroyed, or the wave doesn’t use it yet) can’t just disappear, because it’s in the array of bodies and the physics moves all bodies. Instead, it hides far outside the map, where it’s never in the way. Add this Hide function above showColliders:

game.cpp
// Hides an enemy far outside the map: each one at its own spot, so that they don't push each other around.
void Hide(Tank& enemy, int i)
{
enemy.body.position = enemy.body.previous = { -(i + 1) * 500.0f, -(i + 1) * 500.0f };
enemy.body.velocity = {};
enemy.body.drive = {};
enemy.health = 0;
}

Each hidden enemy gets its own spot, 500 pixels apart from the others, so that the hidden enemies don’t overlap and push each other around. Its health is set to 0, which means that it’s not in the battle.

Below Hide, add the StartWave function, which starts the next wave:

game.cpp
// Starts the next wave: puts its enemies on random spots, not too close to the player.
void StartWave()
{
wave++;
for (int i = 0; i < MaxEnemies; i++)
{
if (i >= wave)
{
Hide(enemies[i], i);
continue;
}
vec2 spot;
do
spot = RandomSpot();
while ((spot - player.body.position).length() < 300);
enemies[i].body.position = enemies[i].body.previous = spot;
enemies[i].body.velocity = {};
enemies[i].health = MaxHealth;
enemies[i].state = State::Patrol;
enemies[i].goal = RandomSpot();
enemies[i].noticed = 0;
enemies[i].reload = ReloadTime;
}
}

StartWave puts the enemies of the next wave on random spots. The do-while loop keeps trying spots until it finds one that is at least 300 pixels away from the player, because an enemy that appears right next to you isn’t fair. The enemies that this wave doesn’t need are hidden.

Below StartWave, add the Restart function, which starts a whole new battle:

game.cpp
// A new battle: the player starts over, as good as new, and the first wave starts.
void Restart()
{
player.body.position = player.body.previous = { 3 * TileSize + 32, 2 * TileSize + 32 };
player.body.velocity = {};
player.health = MaxHealth;
wave = score = 0;
gameOver = false;
for (int i = 0; i < MaxShells; i++)
shells[i].time = 0;
StartWave();
}

The player is as good as new, the score goes back to 0, all shells disappear, and the first wave starts.

In Init, all enemies go into the array of bodies, and the first battle starts:

game.cpp
bodies[bodyCount++] = &player.body;
for (int i = 0; i < MaxEnemies; i++)
bodies[bodyCount++] = &enemies[i].body;
for (int i = 0; i < drumCount; i++)
bodies[bodyCount++] = &drums[i];
Restart();

In Tick, the player only drives and fires while the game isn’t over, and every enemy that is in the battle thinks:

game.cpp
if (gameOver)
direction = {}; // a destroyed tank doesn't drive
player.Drive(direction);
player.Aim({ static_cast<float>(mousex), static_cast<float>(mousey) });
player.reload -= deltaTime;
if ((mouseDown || mousePressed) && !gameOver)
player.Fire(); // click, or hold the left mouse button to keep firing
mousePressed = false;
for (int i = 0; i < MaxEnemies; i++)
if (enemies[i].health > 0)
enemies[i].Think(player, deltaTime);

The shells check all tanks: the player, and all enemies.

game.cpp
Tank* tanks[1 + MaxEnemies] = { &player };
for (int i = 0; i < MaxEnemies; i++)
tanks[1 + i] = &enemies[i];
UpdateShells(deltaTime, tanks, 1 + MaxEnemies);
UpdateExplosions(deltaTime);

After the shells done their damage, check whether the player was destroyed in this frame:

game.cpp
// destroyed tanks: the player's game is over; an enemy explodes and leaves the battle
if (player.health <= 0 && !gameOver)
{
Explode(player.body.position);
Hide(player, MaxEnemies); // out of sight, so that the enemies stop firing at the wreck
gameOver = true;
}

When the player’s health is gone, the player explodes and the game is over. The player also hides, just like a destroyed enemy, because otherwise the enemies would keep firing at the wreck. It gets the hiding spot after the last enemy’s, so that it doesn’t land on one of them. The !gameOver makes sure that all of this happens only once.

Next, count the enemies that are still in the battle, and take care of the ones that were just destroyed:

game.cpp
int remaining = 0; // the number of enemies that are still in the battle
for (int i = 0; i < MaxEnemies; i++)
{
if (enemies[i].health > 0)
remaining++;
else if (enemies[i].body.position.x > 0) // destroyed, but not hidden yet
{
Explode(enemies[i].body.position);
Hide(enemies[i], i);
score++;
}
}

An enemy with a health above 0 is still in the battle, so it counts towards remaining. An enemy with a health of 0 that is still on the map was destroyed in this frame. Hidden enemies are at negative positions, so position.x > 0 means that the enemy isn’t hidden yet. That enemy explodes and hides, and the score goes up. In the next frames it is hidden, so it doesn’t explode again.

When no enemies are left, the next wave comes after a short break:

game.cpp
// when all enemies of a wave are destroyed, the next wave comes after 2 seconds
if (remaining == 0 && !gameOver)
{
waveTimer += deltaTime;
if (waveTimer > 2000)
{
waveTimer = 0;
StartWave();
remaining = std::min(wave, MaxEnemies); // the new enemies are in the battle now
}
}

waveTimer adds up the time since the last enemy of the wave was destroyed. After 2 seconds, the timer starts over at 0 and StartWave brings in the next wave. The new enemies are in the battle now, so remaining is updated too. It’s used again at the end of Tick, to show that the next wave is coming. When the game is over, no new waves come.

Finally, when the game is over, the player can start a new battle:

game.cpp
if (gameOver && GetKeyPressed(KeyFor(SDLK_R)))
Restart();

Pressing R calls Restart, which starts over from the first wave.

The drawing of the tanks skips the destroyed ones:

game.cpp
if (!gameOver)
player.Draw(screen);
for (int i = 0; i < MaxEnemies; i++)
if (enemies[i].health > 0)
enemies[i].Draw(screen);
DrawShells(screen);
DrawExplosions(screen);

With Tab, every enemy shows what it sees. Rotate makes the view cone simpler now:

game.cpp
// what each enemy sees: its view cone (the two edges of its field of view), the line to the player, its
// state, and its goal
const float half = std::acos(FieldOfView); // half the field of view, in radians
for (int i = 0; i < MaxEnemies; i++)
{
const Tank& enemy = enemies[i];
if (enemy.health <= 0)
continue;
const vec2 e = enemy.body.position, p = player.body.position;
const vec2 left = Rotate(enemy.aim, -half) * SightRange, right = Rotate(enemy.aim, half) * SightRange;
screen.Line(e.x, e.y, e.x + left.x, e.y + left.y, 0xffffff);
screen.Line(e.x, e.y, e.x + right.x, e.y + right.y, 0xffffff);
screen.Line(e.x, e.y, p.x, p.y, CanSee(enemy, p) ? 0x40e040 : 0xe04040);
const char* names[4] = { "PATROL", "CHASE", "ATTACK", "SEARCH" };
screen.Print(names[static_cast<int>(enemy.state)], static_cast<int>(e.x) - 16, static_cast<int>(e.y) - 44, 0xffffff);
DrawCircle(screen, { enemy.goal, 8 }, 0xff40ff); // its goal (a random spot, or where it saw the player)
}

And at the end of Tick, a status line at the top, and a message in the middle of the screen when the game is over, or the next wave is coming (add #include <format> at the top of game.cpp for std::format):

game.cpp
// the status line at the top, and the end of the game
screen.Bar(0, 0, ScreenWidth - 1, 15, 0x202020);
screen.Print(std::format("WAVE {} SCORE {} HEALTH {}", wave, score, std::max(player.health, 0)), 4, 5, 0xffffff);
if (gameOver)
screen.Centre(std::format("GAME OVER: {} ENEMIES DESTROYED. PRESS R TO PLAY AGAIN", score), ScreenHeight / 2, 0xffffff);
else if (remaining == 0)
screen.Centre(std::format("WAVE {} IS COMING", wave + 1), ScreenHeight / 2, 0xffffff);

The arena battle. Drive with the arrow keys (or W, A, S and D), aim with the mouse, and click to fire. How many waves can you survive? Tab shows what the enemies see and do, and R starts a new battle when the game is over. (Click the demo first, so that it gets the keys.)

  1. Make the battle harder with every wave: the enemies of wave 1 react slowly, turn their turrets slowly and miss a lot; every next wave, they react a bit faster, turn a bit faster and aim a bit better, up to a limit.
  1. Every 10 seconds, put a repair kit on a random free spot. When the player drives over it, the player gets half of the maximum health back (but not more than the maximum), and the kit is gone, until the next one appears.

If you completed the basic assignment, the solution should look like this:

The result: enemies that get better every wave, and a repair kit every 10 seconds. (Click the demo first, so that it gets the keys.)

  1. The enemies aim at where the player is, so a player that keeps driving is hard to hit. Let the enemies lead the target: aim at the spot where the player will be when the shell gets there.
  1. Add a fifth state: Flee. When an enemy’s health drops to a quarter or less while it is fighting (in Chase, Attack or Search), it drives away from the player, with its turret still pointing at the player. When it is farther away from the player than SightRange (the distance an enemy can see, from What a Tank Can See), it goes back to Patrol.
  1. CanSee only checks the middle of the player (see the note Only a Point). Make the enemies see the player as soon as any part of him sticks out from behind an obstacle.

If you completed the intermediate assignment, the solution should look like this:

The result: enemies that lead their target, flee when they are badly damaged, and see you as soon as part of your tank sticks out from behind an obstacle (press Tab to see their states). (Click the demo first, so that it gets the keys.)

  1. An enemy in Chase drives straight at the player, so it gets stuck behind crates and trees. Give the enemies pathfinding: make a flow field over the tiles, with a breadth-first search from the player’s tile. A chasing enemy drives to the neighbouring tile that is closest to the player.
  1. The enemies hit each other when one of them is between another one and the player. Make sure that an enemy only fires when no other enemy is in the way.

If you completed the hard assignment, the solution should look like this:

The result: chasing enemies that drive around the obstacles, and don’t fire when a friend is in the way (press Tab to see the flow field). (Click the demo first, so that it gets the keys.)

Congratulations on getting here! You started with a black window and a “Hello world”, and now you have built a tank battle with physics and AI, from tiles and sprites to state machines. That’s the end of the C++ Fast Track. Keep building games: that’s the best way to keep learning.

Comments