Appearance
Chapter 10: Enemies and Collision
In Chapter 09: The Capture Service, you turned a finished trail into claimed ground. The arena is still empty, so nothing can go wrong. A trail is only a risk when something is out there to cross it.
In this chapter, you add the threat. Enemies roam the open ground, bounce off claims and walls, turn towards you while you draw, and vanish when a capture encloses them. A touch from an enemy cancels your trail, for now. Chapter 11 replaces that rule with lives.
| Figure 10-1: The chapter 10 window. An enemy roams the open space while the player draws a trail. This is a drawn illustration, not a screenshot. |
Time: [TODO Simon: time estimate for chapter 10]
In this chapter, you will:
- Learn why every enemy variant is the same algorithm with different numbers.
- Build
EnemySystem.Updatein three steps: probes and bounce, timed retargeting, and recovery. - Blend a random heading with pursuit of the player, weighted by variant.
- Rescue an enemy that a capture left standing on claimed ground.
- Build
CollisionSystemwith its two tests: the player and the trail. - Remove the enemies that a capture encloses, and cancel the trail when an enemy touches it.
Requirements in this chapter
| ID | Short name |
|---|---|
| ENM-02 | Enemies stay on unclaimed ground |
| ENM-03 | Bounce per axis |
| ENM-04 | Timed retargeting |
| ENM-05 | Pursuit while the player draws |
| ENM-06 | Variant speed |
| ENM-09 | Recovery to free ground |
| ENM-10 | Frozen enemies do not move |
| ENM-11 | Seedable randomness |
| ENM-12 | Enclosed enemies are removed |
| COL-01 | Player hit, only while drawing |
| COL-02 | Trail hit |
One algorithm, three variants
The game has three kinds of enemy: the Wanderer, the Hunter and the Splitter. They do not need three classes. They all move the same way, so the difference is two numbers per variant. The first is how strongly the enemy turns towards the player each time it picks a new heading. The second is a speed multiplier. Table 10-1 lists them.
| Variant | Pursuit weight | Speed multiplier |
|---|---|---|
| Wanderer | 0.4 | 1.0 |
| Splitter | 0.5 | 1.05 |
| Hunter | 0.7 | 1.12 |
Table 10-1: What separates the three variants. The base speed is 90 pixels per second.
You build all three now, because the numbers cost nothing. The level in this chapter creates only a Wanderer. Chapter 14: Levels and Difficulty adds the roster that uses the other two. The Splitter also splits into temporary clones. That behaviour arrives in Chapter 14, but its constants and the clone check at the top of Update are typed here, so the class does not change shape later.
Five probes
An enemy is a circle, and it must never overlap claimed ground or leave the arena. Asking about its centre is not enough. The centre can be on free ground while the edge of the circle is already on a claim. So the enemy asks five questions: the centre, and the four points one radius away to the left, right, above and below. The enemy can stand at a position only when all five points are on unclaimed ground. ArenaSystem.IsUnclaimedWorld from Chapter 03: The Service Pattern and the Arena already rejects points outside the arena, so this check covers the arena edge too.
The enemy moves by its velocity each frame. It tests the move along X and the move along Y separately. If the X move is blocked, only the X part of the velocity flips. If the Y move is blocked, only the Y part flips. A diagonal mover that hits a wall therefore slides along it instead of sticking to it or bouncing back the way it came. A blocked axis also sets the retarget timer to 0.05 seconds, so the enemy plans a new heading almost at once. Figure 10-2 shows the probes and the two tests.
Figure 10-2: The five probes of CanOccupy, and the separate tests for the X move and the Y move |
Pursuit as a blend
Every 0.65 seconds or so, the enemy picks a new heading. This is called retargeting. The new heading is a blend of two directions. The first is the direction the enemy is already travelling. The second is the direction towards the player. The pursuit weight of the variant decides how much of each goes in. A Wanderer at 0.4 mostly keeps its course. A Hunter at 0.7 mostly follows you.
The enemy only knows where you are while you draw a trail. On the wall, the simulation passes no target, so every variant keeps wandering. This is the pressure on the player: leaving the wall makes the enemies notice you.
After the blend, the heading is rotated by a random angle of up to 35 degrees either way. Without the random turn, a Hunter would trace a straight line to you, and a Wanderer would trace a straight line forever. The timer for the next retarget is also varied, between 75 and 125 per cent of the base interval, so a group of enemies never turns in step. Figure 10-3 shows the blend for each variant.
| Figure 10-3: Retargeting blends the current heading with the direction to the player, then adds a random turn |
An enemy that froze for good
The game once shipped with a bug that is worth understanding, because it shows why the five probes need a second rule. When a capture lands, it claims every tile of the enclosed region and the trail. An enemy that was close to the new edge could find that one of its probes now sat on claimed ground, while its centre was still free.
Look at what the movement code does next. It tests the X move, and the probe that is on claimed ground fails the test at the new position too. It tests the Y move, and the same probe fails again. Both axes are blocked, so the velocity flips on both, and the flipped move fails as well. The enemy stays where it is. The retarget timer is set to a tiny value, so the next frame repeats the whole sequence. The enemy never moves again, for the rest of the level.
The fix is a rule at the top of Update. If the enemy cannot stand where it is, it first steps to the nearest free position, and only then does it try to move. The search is a ring search. It tries 16 directions at a distance of 1 pixel, then 16 directions at 2 pixels, and so on up to 24 pixels. The first free position found is the closest one. If nothing is free within 24 pixels, the enemy stays put and the capture rules deal with it. You write this rule as the third step of Update, with a test that reproduces the freeze.
Two collision tests
The game asks two questions about collisions. Is the player touching an enemy? Is an enemy touching the trail? Both avoid a square root, which would cost time for no gain.
The player hit is circle against circle. Two circles overlap when the distance between their centres is no greater than the sum of their radii. Comparing squared values gives the same answer without the root. The test only counts while the player is drawing. On the wall, the player is safe. This is the rule that makes the wall a place to stand and think.
The trail hit is a point against each segment of the trail. The code finds the closest point on the segment to the enemy centre, and the enemy is hit when that point is within its radius plus 1 pixel. Trail.ContainsPoint, which you wrote in Chapter 07: The Trail Service, already runs this test, so CollisionSystem only has to call it. Figure 10-4 shows both tests.
| Figure 10-4: The two collision tests, circle against circle and point against segment |
Randomness you can repeat
Retargeting uses random numbers. A test cannot check a result that changes on every run. So EnemySystem takes a Random in its constructor and uses only that one. A test passes new Random(42) and gets the same headings every time. The real game passes new Random() and gets a different level each time. Later, Chapter 19: Seeds, the Clock and the Daily Challenge replaces this single Random with separate streams for separate jobs.
Setting up the enemy data
Open a terminal in the LastPerimeter folder. The folders you need already exist. This section adds one enum, two settings and the Enemy class.
Open Source/Data/Enums.cs. Add the following enum at the end of the file, below the TileState enum:
add-type Source/Data/Enums.cs
csharp
public enum EnemyVariant
{
Wanderer,
Hunter,
Splitter,
}Open Source/Data/GameConfig.cs. Add the following property to the GameConfig record, below the MinimumTrailLength property. EnemySpeed is the base speed in pixels per second.
add-member Source/Data/GameConfig.cs after=MinimumTrailLength
csharp
public float EnemySpeed { get; init; } = 90f;Add the following property below the EnemySpeed property. EnemyRetargetIntervalSeconds is the base time between new headings.
add-member Source/Data/GameConfig.cs after=EnemySpeed
csharp
public float EnemyRetargetIntervalSeconds { get; init; } = 0.65f;In the Source/Entities folder, create a new file named Enemy.cs and add the following code. The class holds the state of one enemy. Position, Velocity, Radius and Variant are used in this chapter. DirectionChangeTimer counts down to the next retarget. VisualRotation and VisualAngularVelocity spin the drawn shape. The last three properties belong to the Splitter's clones, and Chapter 14 uses them.
new-file Source/Entities/Enemy.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
namespace LastPerimeter.Entities;
public sealed class Enemy
{
public Vector2 Position { get; set; }
public Vector2 Velocity { get; set; }
public float Radius { get; set; } = 7f;
public float DirectionChangeTimer { get; set; }
public float VisualRotation { get; set; }
public float VisualAngularVelocity { get; set; } = 2.6f;
public EnemyVariant Variant { get; set; } = EnemyVariant.Wanderer;
public bool IsTemporaryClone { get; set; }
public float RemainingLifetimeSeconds { get; set; }
public float VariantTimer { get; set; }
}Building the enemy service
EnemySystem holds one thing: its Random. Each Enemy carries its own state, so one service moves every enemy. The first listing is the whole shell. The constants are written in full, because they are plain numbers. The constructor is in full too. Rotate, a small piece of geometry that turns a vector by an angle, is also in full and has no test of its own. Every other method throws, so the test project keeps compiling.
In the Source/Systems folder, create a new file named EnemySystem.cs and add the following code:
new-file Source/Systems/EnemySystem.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
namespace LastPerimeter.Systems;
public sealed class EnemySystem
{
public const float SplitterFirstSplitDelaySeconds = 6f;
private const float SplitterSplitIntervalSeconds = 8f;
private const float CloneLifetimeSeconds = 5f;
private const float CloneSpeedFactor = 0.9f;
private const float CloneRadiusFactor = 0.75f;
private static readonly Vector2 CloneSpawnOffset = new(12f, -12f);
private const float HunterSpeedMultiplier = 1.12f;
private const float SplitterSpeedMultiplier = 1.05f;
private const float HunterPursuitWeight = 0.7f;
private const float SplitterPursuitWeight = 0.5f;
private const float WandererPursuitWeight = 0.4f;
private const float RetargetConeDegrees = 35f;
private const float RecoverySearchStep = 1f;
private const float RecoverySearchLimit = 24f;
private const int RecoverySearchAngles = 16;
private readonly Random _random;
// Pass a seeded Random to make enemy movement repeatable (tests, seeded runs).
public EnemySystem(Random? random = null)
{
_random = random ?? new Random();
}
public bool Update(Enemy enemy, ArenaSystem arenaSystem, float deltaTime, float retargetIntervalSeconds, Vector2? pressureTarget = null, float speedMultiplier = 1f, bool frozen = false)
{
throw new NotImplementedException();
}
private void Retarget(Enemy enemy, float retargetIntervalSeconds, Vector2? pressureTarget)
{
throw new NotImplementedException();
}
private static void TryRecoverToFreeGround(Enemy enemy, ArenaSystem arenaSystem)
{
throw new NotImplementedException();
}
private static Vector2 Rotate(Vector2 vector, float angleRadians)
{
float cos = MathF.Cos(angleRadians);
float sin = MathF.Sin(angleRadians);
return new Vector2((vector.X * cos) - (vector.Y * sin), (vector.X * sin) + (vector.Y * cos));
}
private static bool CanOccupy(Vector2 position, ArenaSystem arenaSystem, float radius)
{
throw new NotImplementedException();
}
private static float GetVariantSpeedMultiplier(Enemy enemy)
{
throw new NotImplementedException();
}
}The key things to note are:
- The constants repeat Table 10-1.
RetargetConeDegreesis the 35 degree random turn, and the threeRecoveryconstants describe the ring search. - The
Splitterconstants andCloneSpawnOffsetare not used until Chapter 14. - The constructor accepts
nulland then makes its ownRandom, sonew EnemySystem()works in tests that do not care about randomness. - From the
LastPerimeterfolder, rundotnet build. The build should succeed.
You build Update in three steps. Each step has its tests first, then a fuller body of Update. The first step adds probes, bounce, speed and freezing. The second adds retargeting. The third adds recovery.
Moving, bouncing and freezing
EnemySystem.Update(enemy, arena, deltaTime, retargetIntervalSeconds, pressureTarget, speedMultiplier, frozen) : bool
- Takes: an enemy, the arena, the frame time, the base retarget interval, an optional player position to chase, a speed multiplier and a frozen flag.
- Gives:
truewhile the enemy is alive.falsefor a clone whose lifetime has run out.- Promises: the enemy moves at its variant's speed, bounces per axis, and stays on unclaimed ground. It retargets when its timer runs out and, in the third step, recovers from claimed ground first.
- Refuses: a frozen enemy does not move. Its drawn shape still spins.
- Requirements: ENM-02, ENM-03, ENM-06, ENM-10.
The stub is already in your file. You start with three tests: the variant speed, the frozen enemy and the bounce. In the Tests/Systems folder, create a new file named EnemySystemTests.cs and add the following code. It holds the first test and a helper that builds a small enemy. The enemy sits at (40, 40), moves at 10 pixels per second, and has a timer of 100 seconds, so it never retargets during a test. Both variants run for one second, so a Wanderer should travel exactly 10 pixels and a Hunter more.
new-file Tests/Systems/EnemySystemTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
using LastPerimeter.Systems;
using LastPerimeter.Tests.TestHelpers;
namespace LastPerimeter.Tests.Systems;
public sealed class EnemySystemTests
{
[Fact]
public void Update_AppliesVariantSpeedMultiplier_ToActualMovement()
{
ArenaSystem arena = new(TestConfigFactory.Create(width: 80, height: 80, margin: 0, tileSize: 4));
EnemySystem enemySystem = new();
Enemy wanderer = CreateEnemy(EnemyVariant.Wanderer);
Enemy hunter = CreateEnemy(EnemyVariant.Hunter);
enemySystem.Update(wanderer, arena, deltaTime: 1f, retargetIntervalSeconds: 100f);
enemySystem.Update(hunter, arena, deltaTime: 1f, retargetIntervalSeconds: 100f);
Assert.Equal(50f, wanderer.Position.X, precision: 2);
Assert.True(hunter.Position.X > wanderer.Position.X);
}
private static Enemy CreateEnemy(EnemyVariant variant)
{
return new Enemy
{
Position = new Vector2(40f, 40f),
Velocity = new Vector2(10f, 0f),
Radius = 2f,
DirectionChangeTimer = 100f,
Variant = variant,
};
}
}Open Tests/Systems/EnemySystemTests.cs. Add the following test to the EnemySystemTests class, below the Update_AppliesVariantSpeedMultiplier_ToActualMovement test. A frozen enemy must stay at (40, 40) and still report that it is alive.
add-member Tests/Systems/EnemySystemTests.cs after=Update_AppliesVariantSpeedMultiplier_ToActualMovement
csharp
[Fact]
public void Update_WhenFrozen_DoesNotMove()
{
ArenaSystem arena = new(TestConfigFactory.Create(width: 80, height: 80, margin: 0, tileSize: 4));
EnemySystem enemySystem = new();
Enemy enemy = CreateEnemy(EnemyVariant.Wanderer);
bool alive = enemySystem.Update(enemy, arena, deltaTime: 1f, retargetIntervalSeconds: 100f, frozen: true);
Assert.True(alive);
Assert.Equal(new Vector2(40f, 40f), enemy.Position);
}Add the following test below the CreateEnemy helper. The enemy is at (77, 40), moving fast to the right and a little downwards, and the arena ends at x = 80. The move along X leaves the arena, so only the X velocity should flip.
add-member Tests/Systems/EnemySystemTests.cs after=CreateEnemy
csharp
[Fact]
public void Update_BlockedOnX_ReflectsHorizontalVelocity()
{
ArenaSystem arena = new(TestConfigFactory.Create(width: 80, height: 80, margin: 0, tileSize: 4));
EnemySystem enemySystem = new(new Random(1));
Enemy enemy = CreateEnemy(EnemyVariant.Wanderer);
enemy.Position = new Vector2(77f, 40f);
enemy.Velocity = new Vector2(100f, 20f);
enemySystem.Update(enemy, arena, deltaTime: 0.1f, retargetIntervalSeconds: 100f);
Assert.True(enemy.Velocity.X < 0f);
Assert.True(enemy.Velocity.Y > 0f);
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 3 and Passed: 56. The 56 passes are tests from earlier chapters. The three failures hit the stub.
Now write the bodies. Open Source/Systems/EnemySystem.cs, find the Update method and replace the whole method with the following. This is the first of three versions of Update.
replace-method Source/Systems/EnemySystem.cs Update
csharp
public bool Update(Enemy enemy, ArenaSystem arenaSystem, float deltaTime, float retargetIntervalSeconds, Vector2? pressureTarget = null, float speedMultiplier = 1f, bool frozen = false)
{
if (enemy.IsTemporaryClone)
{
enemy.RemainingLifetimeSeconds -= deltaTime;
if (enemy.RemainingLifetimeSeconds <= 0f)
{
return false;
}
}
enemy.VisualRotation = (enemy.VisualRotation + (enemy.VisualAngularVelocity * deltaTime)) % MathHelper.TwoPi;
if (frozen)
{
return true;
}
float effectiveSpeedMultiplier = speedMultiplier * GetVariantSpeedMultiplier(enemy);
Vector2 candidate = enemy.Position + (enemy.Velocity * deltaTime * effectiveSpeedMultiplier);
bool moveX = CanOccupy(new Vector2(candidate.X, enemy.Position.Y), arenaSystem, enemy.Radius);
bool moveY = CanOccupy(new Vector2(enemy.Position.X, candidate.Y), arenaSystem, enemy.Radius);
if (!moveX)
{
enemy.Velocity = new Vector2(-enemy.Velocity.X, enemy.Velocity.Y);
enemy.DirectionChangeTimer = 0.05f;
}
if (!moveY)
{
enemy.Velocity = new Vector2(enemy.Velocity.X, -enemy.Velocity.Y);
enemy.DirectionChangeTimer = 0.05f;
}
Vector2 resolved = enemy.Position + (enemy.Velocity * deltaTime * effectiveSpeedMultiplier);
if (CanOccupy(resolved, arenaSystem, enemy.Radius))
{
enemy.Position = resolved;
return true;
}
enemy.DirectionChangeTimer = 0f;
return true;
}Find the CanOccupy method and replace the whole method with the following:
replace-method Source/Systems/EnemySystem.cs CanOccupy
csharp
private static bool CanOccupy(Vector2 position, ArenaSystem arenaSystem, float radius)
{
// Five probes: the centre and the four radius offsets. IsUnclaimedWorld
// already rejects points outside the arena. Direct calls avoid allocating
// an array and a lambda three times per enemy per frame.
return arenaSystem.IsUnclaimedWorld(position)
&& arenaSystem.IsUnclaimedWorld(position + new Vector2(radius, 0f))
&& arenaSystem.IsUnclaimedWorld(position + new Vector2(-radius, 0f))
&& arenaSystem.IsUnclaimedWorld(position + new Vector2(0f, radius))
&& arenaSystem.IsUnclaimedWorld(position + new Vector2(0f, -radius));
}Find the GetVariantSpeedMultiplier method and replace the whole method with the following:
replace-method Source/Systems/EnemySystem.cs GetVariantSpeedMultiplier
csharp
private static float GetVariantSpeedMultiplier(Enemy enemy)
{
return enemy.Variant switch
{
EnemyVariant.Hunter => HunterSpeedMultiplier,
EnemyVariant.Splitter => SplitterSpeedMultiplier,
_ => 1f,
};
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 59.
The key things to note are:
- A temporary clone counts its lifetime down first, and
Updatereturnsfalsewhen it reaches zero. No clone exists until Chapter 14, so no test covers this yet. VisualRotationadvances even when the enemy is frozen, so a frozen enemy still looks alive. The% MathHelper.TwoPikeeps the angle from growing without limit.- The frozen check comes before any movement, so a frozen enemy never retargets and never recovers.
CanOccupyuses&&to chain the five probes, so the first failed probe stops the rest. It makes direct calls and builds no array, because it runs several times per enemy per frame.moveXandmoveYtest the two axes from the current position, each with only one coordinate changed. That is what lets a diagonal mover keep its sliding motion.- The velocity flips first, and the new move is then tried with the flipped velocity. If that is also blocked, the enemy stays put and sets its timer to 0 so that it retargets on the next frame.
- The Hunter test only checks that the Hunter travels further, and the Wanderer test checks the exact distance of 10 pixels, which is
10 * 1 * 1.0and moves from x = 40 to x = 50.
Retargeting
Retargeting inside
EnemySystem.Update
- Takes: the enemy's timer, its variant and the optional pressure target.
- Gives: a new velocity of the same speed and a new timer.
- Promises: with a target, the new heading leans towards it by the variant's weight. The random turn is at most 35 degrees. A seeded
Randomgives the same result every time.- Refuses: with no target, the enemy keeps its heading and only turns randomly.
- Requirements: ENM-04, ENM-05, ENM-11.
Retarget is a private method, so a test drives it through Update with a timer of zero. Open Tests/Systems/EnemySystemTests.cs. Add the following test to the EnemySystemTests class, below the Update_WhenFrozen_DoesNotMove test. It builds two systems from the same seed and checks that two identical enemies end with the same velocity and timer.
add-member Tests/Systems/EnemySystemTests.cs after=Update_WhenFrozen_DoesNotMove
csharp
[Fact]
public void Update_WithSameSeed_RetargetsIdentically()
{
ArenaSystem arena = new(TestConfigFactory.Create(width: 80, height: 80, margin: 0, tileSize: 4));
EnemySystem first = new(new Random(42));
EnemySystem second = new(new Random(42));
Enemy firstEnemy = CreateEnemy(EnemyVariant.Hunter);
Enemy secondEnemy = CreateEnemy(EnemyVariant.Hunter);
firstEnemy.DirectionChangeTimer = 0f;
secondEnemy.DirectionChangeTimer = 0f;
first.Update(firstEnemy, arena, deltaTime: 0.1f, retargetIntervalSeconds: 0.5f, pressureTarget: new Vector2(10f, 10f));
second.Update(secondEnemy, arena, deltaTime: 0.1f, retargetIntervalSeconds: 0.5f, pressureTarget: new Vector2(10f, 10f));
Assert.Equal(firstEnemy.Velocity, secondEnemy.Velocity);
Assert.Equal(firstEnemy.DirectionChangeTimer, secondEnemy.DirectionChangeTimer);
}Add the following test below the Update_BlockedOnX_ReflectsHorizontalVelocity test. A Hunter at (40, 40) is travelling up, and the player is to its right. After one retarget, the Hunter must have a positive X velocity. With a weight of 0.7 the blend points about 23 degrees above the X axis, and the random turn of at most 35 degrees cannot flip it to the left.
add-member Tests/Systems/EnemySystemTests.cs after=Update_BlockedOnX_ReflectsHorizontalVelocity
csharp
[Fact]
public void Retarget_WithPressureTarget_TurnsTowardPlayer()
{
ArenaSystem arena = new(TestConfigFactory.Create(width: 80, height: 80, margin: 0, tileSize: 4));
EnemySystem enemySystem = new(new Random(7));
Enemy enemy = CreateEnemy(EnemyVariant.Hunter);
enemy.Position = new Vector2(40f, 40f);
enemy.Velocity = new Vector2(0f, -50f);
enemy.DirectionChangeTimer = 0f;
enemySystem.Update(enemy, arena, deltaTime: 0.01f, retargetIntervalSeconds: 100f, pressureTarget: new Vector2(70f, 40f));
Assert.True(enemy.Velocity.X > 0f);
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 60. The pursuit test fails, because nothing steers the enemy yet. The same-seed test passes for now, because two enemies that never retarget end up identical. It starts to prove something once retargeting exists.
Open Source/Systems/EnemySystem.cs, find the Update method and replace the whole method with the following. This is the second version. It adds the timer and the call to Retarget.
replace-method Source/Systems/EnemySystem.cs Update
csharp
public bool Update(Enemy enemy, ArenaSystem arenaSystem, float deltaTime, float retargetIntervalSeconds, Vector2? pressureTarget = null, float speedMultiplier = 1f, bool frozen = false)
{
if (enemy.IsTemporaryClone)
{
enemy.RemainingLifetimeSeconds -= deltaTime;
if (enemy.RemainingLifetimeSeconds <= 0f)
{
return false;
}
}
enemy.VisualRotation = (enemy.VisualRotation + (enemy.VisualAngularVelocity * deltaTime)) % MathHelper.TwoPi;
if (frozen)
{
return true;
}
enemy.DirectionChangeTimer -= deltaTime;
if (enemy.DirectionChangeTimer <= 0f)
{
Retarget(enemy, retargetIntervalSeconds, pressureTarget);
}
float effectiveSpeedMultiplier = speedMultiplier * GetVariantSpeedMultiplier(enemy);
Vector2 candidate = enemy.Position + (enemy.Velocity * deltaTime * effectiveSpeedMultiplier);
bool moveX = CanOccupy(new Vector2(candidate.X, enemy.Position.Y), arenaSystem, enemy.Radius);
bool moveY = CanOccupy(new Vector2(enemy.Position.X, candidate.Y), arenaSystem, enemy.Radius);
if (!moveX)
{
enemy.Velocity = new Vector2(-enemy.Velocity.X, enemy.Velocity.Y);
enemy.DirectionChangeTimer = 0.05f;
}
if (!moveY)
{
enemy.Velocity = new Vector2(enemy.Velocity.X, -enemy.Velocity.Y);
enemy.DirectionChangeTimer = 0.05f;
}
Vector2 resolved = enemy.Position + (enemy.Velocity * deltaTime * effectiveSpeedMultiplier);
if (CanOccupy(resolved, arenaSystem, enemy.Radius))
{
enemy.Position = resolved;
return true;
}
enemy.DirectionChangeTimer = 0f;
return true;
}The key change is in the middle of the method. The enemy's timer counts down, and Retarget runs when it reaches zero.
Find the Retarget method and replace the whole method with the following:
replace-method Source/Systems/EnemySystem.cs Retarget
csharp
private void Retarget(Enemy enemy, float retargetIntervalSeconds, Vector2? pressureTarget)
{
float speed = enemy.Velocity.Length();
if (speed <= float.Epsilon)
{
speed = 90f;
}
Vector2 baseDirection = enemy.Velocity.LengthSquared() <= float.Epsilon
? Vector2.Normalize(new Vector2(1f, 0.4f))
: Vector2.Normalize(enemy.Velocity);
Vector2 targetDirection = baseDirection;
if (pressureTarget is Vector2 target && Vector2.DistanceSquared(target, enemy.Position) > 4f)
{
targetDirection = Vector2.Normalize(target - enemy.Position);
}
float randomAngle = MathHelper.ToRadians((_random.NextSingle() * RetargetConeDegrees * 2f) - RetargetConeDegrees);
float targetWeight = enemy.Variant switch
{
EnemyVariant.Hunter => HunterPursuitWeight,
EnemyVariant.Splitter => SplitterPursuitWeight,
_ => WandererPursuitWeight,
};
Vector2 blended = Vector2.Normalize((baseDirection * (1f - targetWeight)) + (targetDirection * targetWeight));
Vector2 rotated = Rotate(blended, randomAngle);
if (rotated.LengthSquared() <= float.Epsilon)
{
rotated = baseDirection;
}
enemy.Velocity = Vector2.Normalize(rotated) * speed;
enemy.DirectionChangeTimer = retargetIntervalSeconds * (0.75f + (_random.NextSingle() * 0.5f));
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 61.
The key things to note are:
Retargetkeeps the speed. It reads the length of the old velocity, and the new velocity is a direction multiplied by that same speed. An enemy never speeds up by turning.- A target closer than 2 pixels is ignored, because the direction to a point that close is unreliable. The enemy keeps its own heading.
Vector2.Normalize((baseDirection * (1f - targetWeight)) + (targetDirection * targetWeight))is the blend of Figure 10-3. A weight of 0 gives the old heading and a weight of 1 gives the target heading.- The random turn is
(NextSingle() * 70) - 35degrees, which is a number between -35 and 35. - Two calls to
NextSinglehappen per retarget, one for the angle and one for the timer. A seeded test therefore repeats both.
Recovering from a capture
Recovery inside
EnemySystem.Update
- Takes: an enemy whose five probes are not all on unclaimed ground.
- Gives: the enemy, moved to the closest free position within 24 pixels.
- Promises: an enemy standing next to a fresh claim does not freeze. It moves again.
- Refuses: with no free position within 24 pixels, the enemy stays where it is.
- Requirements: ENM-02, ENM-09.
Open Tests/Systems/EnemySystemTests.cs. Add the following test to the EnemySystemTests class, below the Update_WithSameSeed_RetargetsIdentically test. It recreates the freeze. Columns 10 and 11 of the small arena are claimed, which covers x = 40 to 48. The enemy centre at x = 36 is free, but its right probe at x = 43 is on the claim. The test runs 3 seconds of frames and checks that the enemy moved and ended on free ground, with all five probes free.
add-member Tests/Systems/EnemySystemTests.cs after=Update_WithSameSeed_RetargetsIdentically
csharp
[Fact]
public void Update_EnemyBesideFreshCapture_RecoversAndKeepsMoving()
{
ArenaSystem arena = new(TestConfigFactory.Create(width: 80, height: 80, margin: 0, tileSize: 4));
ClaimColumns(arena, firstColumn: 10, lastColumn: 11);
EnemySystem enemySystem = new(new Random(7));
Enemy enemy = new()
{
Position = new Vector2(36f, 40f),
Velocity = new Vector2(60f, 0f),
Radius = 7f,
DirectionChangeTimer = 0.5f,
Variant = EnemyVariant.Wanderer,
};
Vector2 start = enemy.Position;
for (int i = 0; i < 180; i++)
{
enemySystem.Update(enemy, arena, deltaTime: 1f / 60f, retargetIntervalSeconds: 0.5f);
}
Assert.NotEqual(start, enemy.Position);
Assert.True(arena.IsUnclaimedWorld(enemy.Position));
Assert.True(arena.IsUnclaimedWorld(enemy.Position + new Vector2(enemy.Radius, 0f)));
Assert.True(arena.IsUnclaimedWorld(enemy.Position + new Vector2(-enemy.Radius, 0f)));
Assert.True(arena.IsUnclaimedWorld(enemy.Position + new Vector2(0f, enemy.Radius)));
Assert.True(arena.IsUnclaimedWorld(enemy.Position + new Vector2(0f, -enemy.Radius)));
}Add the following helper below the test. It claims a block of full-height columns, using the ApplyClaimResult operation from Chapter 03.
add-member Tests/Systems/EnemySystemTests.cs after=Update_EnemyBesideFreshCapture_RecoversAndKeepsMoving
csharp
private static void ClaimColumns(ArenaSystem arena, int firstColumn, int lastColumn)
{
Region captured = new();
for (int x = firstColumn; x <= lastColumn; x++)
{
for (int y = 0; y < 20; y++)
{
captured.Tiles.Add(new Point(x, y));
}
}
arena.ApplyClaimResult(new ClaimResult(captured, new Region(), Array.Empty<Point>()));
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 61. This is the freeze, reproduced in a test.
Open Source/Systems/EnemySystem.cs, find the Update method and replace the whole method with the following. This is the final version. It adds the recovery step before the timer.
replace-method Source/Systems/EnemySystem.cs Update
csharp
public bool Update(Enemy enemy, ArenaSystem arenaSystem, float deltaTime, float retargetIntervalSeconds, Vector2? pressureTarget = null, float speedMultiplier = 1f, bool frozen = false)
{
if (enemy.IsTemporaryClone)
{
enemy.RemainingLifetimeSeconds -= deltaTime;
if (enemy.RemainingLifetimeSeconds <= 0f)
{
return false;
}
}
enemy.VisualRotation = (enemy.VisualRotation + (enemy.VisualAngularVelocity * deltaTime)) % MathHelper.TwoPi;
if (frozen)
{
return true;
}
// A capture can claim tiles under the enemy's probes, and a splitter clone can
// spawn on claimed ground. Step to the nearest free spot first, or every
// move below would fail and the enemy would never move again.
if (!CanOccupy(enemy.Position, arenaSystem, enemy.Radius))
{
TryRecoverToFreeGround(enemy, arenaSystem);
}
enemy.DirectionChangeTimer -= deltaTime;
if (enemy.DirectionChangeTimer <= 0f)
{
Retarget(enemy, retargetIntervalSeconds, pressureTarget);
}
float effectiveSpeedMultiplier = speedMultiplier * GetVariantSpeedMultiplier(enemy);
Vector2 candidate = enemy.Position + (enemy.Velocity * deltaTime * effectiveSpeedMultiplier);
bool moveX = CanOccupy(new Vector2(candidate.X, enemy.Position.Y), arenaSystem, enemy.Radius);
bool moveY = CanOccupy(new Vector2(enemy.Position.X, candidate.Y), arenaSystem, enemy.Radius);
if (!moveX)
{
enemy.Velocity = new Vector2(-enemy.Velocity.X, enemy.Velocity.Y);
enemy.DirectionChangeTimer = 0.05f;
}
if (!moveY)
{
enemy.Velocity = new Vector2(enemy.Velocity.X, -enemy.Velocity.Y);
enemy.DirectionChangeTimer = 0.05f;
}
Vector2 resolved = enemy.Position + (enemy.Velocity * deltaTime * effectiveSpeedMultiplier);
if (CanOccupy(resolved, arenaSystem, enemy.Radius))
{
enemy.Position = resolved;
return true;
}
enemy.DirectionChangeTimer = 0f;
return true;
}Find the TryRecoverToFreeGround method and replace the whole method with the following:
replace-method Source/Systems/EnemySystem.cs TryRecoverToFreeGround
csharp
// Ring search outward in 1 px steps, 16 directions per ring, so the closest free
// position wins. If nothing is free within the limit the enemy is left where it
// is and the existing game logic (for example the claim rules) deals with it.
private static void TryRecoverToFreeGround(Enemy enemy, ArenaSystem arenaSystem)
{
for (float distance = RecoverySearchStep; distance <= RecoverySearchLimit; distance += RecoverySearchStep)
{
for (int i = 0; i < RecoverySearchAngles; i++)
{
float angle = MathHelper.TwoPi * i / RecoverySearchAngles;
Vector2 candidate = enemy.Position + new Vector2(MathF.Cos(angle) * distance, MathF.Sin(angle) * distance);
if (CanOccupy(candidate, arenaSystem, enemy.Radius))
{
enemy.Position = candidate;
return;
}
}
}
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 62.
The key things to note are:
- The outer loop grows the distance, and the inner loop tries 16 evenly spaced directions. The first free spot ends the search, so the enemy moves the smallest possible distance.
- Recovery runs before the retarget and the move, so everything after it sees an enemy that can stand where it is.
CanOccupyis the only judge of free ground, both for recovery and for the move. The two cannot disagree.- If nothing is free within the limit, the method returns without moving the enemy. This is rare, and the capture rules in Chapter 09 prefer to claim regions that hold no enemy.
Building the collision service
CollisionSystem has no state at all. Its two operations are one-line checks, so they share one stub, one test listing and one body listing each.
CollisionSystem.IsPlayerHitByEnemy(player, enemy, playerIsDrawing) : bool
- Takes: the player, an enemy and whether the player is drawing.
- Gives:
truewhen the two circles overlap.- Promises: the circles overlap when the squared distance is no greater than the squared sum of the radii.
- Refuses: it always gives
falsewhile the player is not drawing.- Requirements: COL-01.
CollisionSystem.IsTrailHitByEnemy(trail, enemy) : bool
- Takes: a trail, which may be
null, and an enemy.- Gives:
truewhen the enemy is within its radius plus 1 pixel of the trail.- Promises: the test runs against every segment of the trail.
- Refuses: a
nulltrail, or a trail that is not in progress, givesfalse.- Requirements: COL-02.
In the Source/Systems folder, create a new file named CollisionSystem.cs and add the following code:
new-file Source/Systems/CollisionSystem.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
namespace LastPerimeter.Systems;
public sealed class CollisionSystem
{
public bool IsPlayerHitByEnemy(Player player, Enemy enemy, bool playerIsDrawing)
{
throw new NotImplementedException();
}
public bool IsTrailHitByEnemy(Trail? trail, Enemy enemy)
{
throw new NotImplementedException();
}
}In the Tests/Systems folder, create a new file named CollisionSystemTests.cs and add the following code. The trail runs from (0, 0) to (20, 0), and the enemy at (10, 1) has a radius of 2, so the trail passes through it.
new-file Tests/Systems/CollisionSystemTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Entities;
using LastPerimeter.Systems;
namespace LastPerimeter.Tests.Systems;
public sealed class CollisionSystemTests
{
[Fact]
public void TrailCollision_IsDetected()
{
Trail trail = new();
trail.AddPoint(new Vector2(0, 0));
trail.AddPoint(new Vector2(20, 0));
Enemy enemy = new()
{
Position = new Vector2(10, 1),
Radius = 2f,
};
CollisionSystem collisionSystem = new();
Assert.True(collisionSystem.IsTrailHitByEnemy(trail, enemy));
}
}Open Tests/Systems/CollisionSystemTests.cs. Add the following test to the CollisionSystemTests class, below the TrailCollision_IsDetected test. The player and the enemy each have a radius of 6, and their centres are 5 pixels apart, so they overlap. The test checks both values of the drawing flag.
add-member Tests/Systems/CollisionSystemTests.cs after=TrailCollision_IsDetected
csharp
[Fact]
public void PlayerCollision_OnlyCountsWhileDrawing()
{
Player player = new()
{
Position = new Vector2(0, 0),
Radius = 6f,
};
Enemy enemy = new()
{
Position = new Vector2(5, 0),
Radius = 6f,
};
CollisionSystem collisionSystem = new();
Assert.False(collisionSystem.IsPlayerHitByEnemy(player, enemy, false));
Assert.True(collisionSystem.IsPlayerHitByEnemy(player, enemy, true));
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 2 and Passed: 62.
Open Source/Systems/CollisionSystem.cs. Find the IsPlayerHitByEnemy method and replace the whole method with the following:
replace-method Source/Systems/CollisionSystem.cs IsPlayerHitByEnemy
csharp
public bool IsPlayerHitByEnemy(Player player, Enemy enemy, bool playerIsDrawing)
{
if (!playerIsDrawing)
{
return false;
}
float combinedRadius = player.Radius + enemy.Radius;
return Vector2.DistanceSquared(player.Position, enemy.Position) <= combinedRadius * combinedRadius;
}Find the IsTrailHitByEnemy method and replace the whole method with the following:
replace-method Source/Systems/CollisionSystem.cs IsTrailHitByEnemy
csharp
public bool IsTrailHitByEnemy(Trail? trail, Enemy enemy)
{
return trail is not null && trail.State == TrailState.InProgress && trail.ContainsPoint(enemy.Position, enemy.Radius + 1f);
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 64.
The key things to note are:
- The drawing flag is checked first, so the wall stays safe before any arithmetic runs.
Vector2.DistanceSquaredand the squared sum of the radii give the circle test with no square root.trail is not null && trail.State == TrailState.InProgressmakes the trail test safe for a missing or finished trail. A completed trail is territory by then and cannot be hit.- The extra pixel in
enemy.Radius + 1fgives the player a small margin. A trail that grazes the very edge of the enemy still counts as a touch.
Wiring it into the game
The enemy service and the collision service now work in isolation. This section connects them to the simulation, in four parts. First the session gets a list of enemies, and the test helper learns to build them. Then the simulation takes a Random and creates its services. After that, it updates the enemies each tick and removes the enclosed ones. Last, it reacts when an enemy touches the trail.
The session and the test helper
Open Source/Data/GameSession.cs. Add the following property to the GameSession class, below the PlayableWallPath property:
add-member Source/Data/GameSession.cs after=PlayableWallPath
csharp
public List<Enemy> Enemies { get; init; } = [];Add the following property below the ClaimedAreaPercentage property. It holds the seconds that all enemies stay frozen. A later chapter sets it from a powerup, and the tests set it to keep enemies still.
add-member Source/Data/GameSession.cs after=ClaimedAreaPercentage
csharp
public float FreezeEnemiesRemaining { get; set; }Open Tests/TestHelpers/SimulationBuilder.cs. The Create method must pass a seeded Random to the simulation. It must also clear the one enemy that StartLevel will create, unless a test asks for enemies. This keeps every earlier scenario test free of enemies. In the Create method, find the signature line:
find Tests/TestHelpers/SimulationBuilder.cs
csharp
public static GameplaySimulation Create(int margin = 0)Replace it with:
csharp
public static GameplaySimulation Create(int seed = 1, bool withEnemies = false, int margin = 0)Find this line:
find Tests/TestHelpers/SimulationBuilder.cs
csharp
GameplaySimulation simulation = new(config, session);Replace it with:
csharp
GameplaySimulation simulation = new(config, session, new Random(seed));Find these lines:
find Tests/TestHelpers/SimulationBuilder.cs
csharp
simulation.StartLevel();
return simulation;Replace them with:
csharp
simulation.StartLevel();
if (!withEnemies)
{
session.Enemies.Clear();
}
return simulation;Add the following method at the end of the SimulationBuilder class. A frozen enemy does not move, so a scenario can put it at an exact position and rely on it staying there. The method returns the simulation, so calls can be chained.
add-member Tests/TestHelpers/SimulationBuilder.cs at=end
csharp
// Enemies do not move while frozen, which keeps a scenario exact.
public static GameplaySimulation WithFrozenEnemyAt(this GameplaySimulation simulation, float x, float y)
{
simulation.Session.Enemies.Add(new Enemy { Position = new Microsoft.Xna.Framework.Vector2(x, y), Velocity = new Microsoft.Xna.Framework.Vector2(10f, 0f), Radius = 2f });
simulation.Session.FreezeEnemiesRemaining = 1000f;
return simulation;
}The simulation and the scene
Open Source/Simulation/GameplaySimulation.cs. Add the following field to the GameplaySimulation class, below the _fuse field. It is the service that moves the enemies.
add-member Source/Simulation/GameplaySimulation.cs after=_fuse
csharp
private readonly EnemySystem _enemies;Add the following field below the _enemies field. It is the service that answers the two collision questions.
add-member Source/Simulation/GameplaySimulation.cs after=_enemies
csharp
private readonly CollisionSystem _collision = new();Add the following field below the _collision field. The simulation reuses this list and the next one every frame, so it does not allocate memory in the middle of play.
add-member Source/Simulation/GameplaySimulation.cs after=_collision
csharp
private readonly List<Vector2> _enemyPositions = [];Add the following field below the _enemyPositions field:
add-member Source/Simulation/GameplaySimulation.cs after=_enemyPositions
csharp
private readonly List<int> _eliminated = [];In the same file, the constructor must take a Random and pass it to a new EnemySystem. Find the constructor signature:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
public GameplaySimulation(GameConfig baseConfig, GameSession session)Replace it with:
csharp
public GameplaySimulation(GameConfig baseConfig, GameSession session, Random random)Find this line in the constructor:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
_baseConfig = baseConfig;Add the following line directly above it:
csharp
_enemies = new EnemySystem(random);Open Source/Scenes/GameplayScene.cs. The constructor must give the simulation a Random. The real game uses an unseeded one. Find this line in the constructor:
find Source/Scenes/GameplayScene.cs
csharp
_simulation = new GameplaySimulation(services.Config, session);Replace it with:
csharp
_simulation = new GameplaySimulation(services.Config, session, new Random());In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 64. Nothing has changed in behaviour yet. The run proves that the new constructor and the new builder did not disturb any earlier test.
Updating enemies and removing the enclosed
Enemies in
GameplaySimulation
- Takes: the enemies in the session, each tick, and the enemy positions at the moment a trail is completed.
- Gives: moving enemies, and removal of those that a capture encloses.
- Promises:
CaptureCompletedreports how many enemies the capture removed.- Refuses: an enemy outside every captured region stays.
- Requirements: ENM-12.
In the Tests/Simulation folder, create a new file named EnemyScenarioTests.cs and add the following code. The scenario puts one frozen enemy at (30, 20), inside the block that DrawRectangleFromTopWall encloses, and one at (60, 60), outside it. The capture must eliminate exactly the first. Chapter 09: The Capture Service made the solver able to report enclosed enemies. Here you prove that the simulation passes them in and removes them.
new-file Tests/Simulation/EnemyScenarioTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Simulation;
using LastPerimeter.Tests.TestHelpers;
namespace LastPerimeter.Tests.Simulation;
public sealed class EnemyScenarioTests
{
[Fact]
public void EnclosingCapture_RemovesEliminatedEnemies()
{
GameplaySimulation sim = SimulationBuilder.Create();
sim.WithFrozenEnemyAt(30, 20).WithFrozenEnemyAt(60, 60);
CaptureCompleted capture = ScriptedInput.DrawRectangleFromTopWall(sim).OfType<CaptureCompleted>().Single();
Assert.Equal(1, capture.EnemiesEliminated);
Assert.Single(sim.Session.Enemies);
Assert.Equal(new Vector2(60, 60), sim.Session.Enemies[0].Position);
}
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 64. The simulation does not yet pass enemy positions to the solver, so nothing is eliminated.
Open Source/Simulation/GameplaySimulation.cs. The StartLevel method must now clear the enemy list and add one Wanderer. Find this line in the method:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
_session.Player.Position = SelectStartNode(_session.PlayableWallPath);Add the following lines directly after it:
csharp
_session.Enemies.Clear();
_session.Enemies.Add(CreateWanderer());In the Tick method, two steps are new: step 1 counts the freeze timer down, and step 5 updates the enemies. The step numbers are explained in the order of one tick, and the missing numbers belong to later chapters. Find this comment line:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
// 3. The fuse must react to actual displacement, not input: holding a blockedReplace it with the following. The last line is the comment you found, unchanged:
csharp
// 1. Timers.
_session.FreezeEnemiesRemaining = Math.Max(0f, _session.FreezeEnemiesRemaining - deltaTime);
// 3. The fuse must react to actual displacement, not input: holding a blockedFind this comment line:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
// 6. Nothing to do with no input and no trail.Replace it with the following. The last line is the comment you found, unchanged:
csharp
// 5. Enemies.
UpdateEnemies(deltaTime);
// 6. Nothing to do with no input and no trail.Add the following method to the GameplaySimulation class, below the Tick method:
add-member Source/Simulation/GameplaySimulation.cs after=Tick
csharp
private void UpdateEnemies(float deltaTime)
{
bool frozen = _session.FreezeEnemiesRemaining > 0f;
Vector2? pressureTarget = _trails.HasActiveTrail ? _session.Player.Position : null;
for (int index = _session.Enemies.Count - 1; index >= 0; index--)
{
Enemy enemy = _session.Enemies[index];
bool alive = _enemies.Update(enemy, _arena, deltaTime, _baseConfig.EnemyRetargetIntervalSeconds, pressureTarget, speedMultiplier: 1f, frozen: frozen);
if (!alive)
{
_session.Enemies.RemoveAt(index);
}
}
}In the ResolveCapture method, two stages are new: stage 2 passes the enemy positions to the solver, and stage 9 removes the eliminated enemies. Make three edits. First, find the comment above the method:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
// Turns a completed trail into territory. Scoring arrives in chapter 12, enemy
// removal in chapter 10 and the level check in chapter 14.Replace it with:
csharp
// Turns a completed trail into territory. Scoring arrives in chapter 12 and the
// level check in chapter 14.Second, find these lines in stage 2:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
// 2. Ask the solver.
ClaimResult? claimResult = _claims.ProcessCompletedTrail(completedTrail);Replace them with:
csharp
// 2. Ask the solver, passing the enemy positions.
_enemyPositions.Clear();
for (int index = 0; index < _session.Enemies.Count; index++)
{
_enemyPositions.Add(_session.Enemies[index].Position);
}
ClaimResult? claimResult = _claims.ProcessCompletedTrail(completedTrail, _enemyPositions);Third, find these lines in stage 10:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
// 10. Report the capture. Points are zero until chapter 12.
int tiles = claimResult.CapturedRegion.TileCount + claimResult.TrailTiles.Count;
_events.Add(new CaptureCompleted(tiles, 0, completedTrail.IsSlowDraw, !snappedToPath, 0));Replace them with the following. Stage 9 is new, and the last line now reports the number of removed enemies:
csharp
// 9. Remove eliminated enemies, highest index first.
int eliminatedCount = RemoveEliminatedEnemies(claimResult.EliminatedEnemyIndexes);
// 10. Report the capture. Points are zero until chapter 12.
int tiles = claimResult.CapturedRegion.TileCount + claimResult.TrailTiles.Count;
_events.Add(new CaptureCompleted(tiles, 0, completedTrail.IsSlowDraw, !snappedToPath, eliminatedCount));Add the following method below the ResolveCapture method:
add-member Source/Simulation/GameplaySimulation.cs after=ResolveCapture
csharp
private int RemoveEliminatedEnemies(IReadOnlyList<int>? eliminatedIndexes)
{
if (eliminatedIndexes is null || eliminatedIndexes.Count == 0)
{
return 0;
}
_eliminated.Clear();
for (int index = 0; index < eliminatedIndexes.Count; index++)
{
_eliminated.Add(eliminatedIndexes[index]);
}
_eliminated.Sort();
int removed = 0;
for (int index = _eliminated.Count - 1; index >= 0; index--)
{
int enemyIndex = _eliminated[index];
if (enemyIndex >= 0 && enemyIndex < _session.Enemies.Count)
{
_session.Enemies.RemoveAt(enemyIndex);
removed++;
}
}
return removed;
}Add the following method below the RemoveEliminatedEnemies method:
add-member Source/Simulation/GameplaySimulation.cs after=RemoveEliminatedEnemies
csharp
// One Wanderer in the middle of the arena. Chapter 14 replaces this with the level roster.
private Enemy CreateWanderer()
{
Rectangle bounds = _arena.Bounds;
return new Enemy
{
Position = new Vector2(bounds.Center.X, bounds.Center.Y),
Velocity = Vector2.Normalize(new Vector2(1f, 0.7f)) * _baseConfig.EnemySpeed,
Variant = EnemyVariant.Wanderer,
};
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 65.
The key things to note are:
UpdateEnemieswalks the list backwards. Removing an item shifts the items after it, so a backwards walk never skips one.- The pressure target is the player's position only while a trail is active. This is the rule from "Pursuit as a blend".
RemoveEliminatedEnemiessorts the indexes and removes the highest first, for the same reason. The solver reports indexes into the list as it was when the trail completed.- The bounds check in
RemoveEliminatedEnemiesmakes a stale index harmless instead of a crash. CaptureCompletednow carries the number of removed enemies, where chapter 09 passed 0.CreateWandererputs the enemy at the arena centre, heading down and to the right. Chapter 14 replaces it with the level roster.
Cancelling the trail on contact
The last rule of this chapter is temporary. When an enemy touches the player or the trail, the simulation cancels the trail and puts the player back where the trail began. That is the same CancelTrail method that the fuse already uses from Chapter 08: The Fuse Service.
IMPORTANT
This rule is a placeholder. Chapter 11 deletes both calls to CancelTrail and sends them to LivesSystem instead. Two tests that you add or have already written will then change their bodies, and chapter 11 explains why.
Open Tests/Simulation/EnemyScenarioTests.cs. Add the following test to the EnemyScenarioTests class, below the EnclosingCapture_RemovesEliminatedEnemies test. The player draws right and then down to start a trail from (20, 0). A frozen enemy waits at (20, 8), right on the line the trail is about to follow. One more step down must cancel the trail and put the player back at (20, 0).
add-member Tests/Simulation/EnemyScenarioTests.cs after=EnclosingCapture_RemovesEliminatedEnemies
csharp
[Fact]
public void Tick_EnemyTouchingTrail_CancelsTheTrail()
{
GameplaySimulation sim = SimulationBuilder.Create();
ScriptedInput.Run(sim, ScriptedInput.Right, 4);
ScriptedInput.Run(sim, ScriptedInput.Down, 3);
sim.WithFrozenEnemyAt(20, 8);
List<GameEvent> events = ScriptedInput.Run(sim, ScriptedInput.Down, 1);
Assert.Empty(events.OfType<CaptureCompleted>());
Assert.Null(sim.Session.Player.CurrentTrail);
Assert.Equal(new Vector2(20, 0), sim.Session.Player.Position);
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 65.
Open Source/Simulation/GameplaySimulation.cs. The TickWhileDrawing method needs a new block, marked 8b, which checks the contact and cancels the trail. Find this line in the method:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
if (_trails.CanCompleteOnPath(intendedPosition, _session.PlayableWallPath))Replace it with the following. The last line is the line you found, unchanged:
csharp
// 8b. Enemy contact.
if (IsPlayerOrTrailHit(player, activeTrail))
{
CancelTrail(activeTrail);
return;
}
if (_trails.CanCompleteOnPath(intendedPosition, _session.PlayableWallPath))Add the following method below the TickWhileDrawing method:
add-member Source/Simulation/GameplaySimulation.cs after=TickWhileDrawing
csharp
private bool IsPlayerOrTrailHit(Player player, Trail activeTrail)
{
for (int index = 0; index < _session.Enemies.Count; index++)
{
Enemy enemy = _session.Enemies[index];
if (_collision.IsPlayerHitByEnemy(player, enemy, true) || _collision.IsTrailHitByEnemy(activeTrail, enemy))
{
return true;
}
}
return false;
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 66.
The key things to note are:
- Step 8b comes after the fuse check, so a fuse kill wins over an enemy touch in the same frame.
IsPlayerOrTrailHitpassestruefor the drawing flag, becauseTickWhileDrawingonly runs while a trail exists.- The helper asks both questions for every enemy and stops at the first hit, using
||and an earlyreturn. - The test puts a frozen enemy on the trail's path. A moving enemy would make the result depend on its heading, and the scenario would not be exact.
Drawing the enemies
In the Source/Rendering folder, create a new file named EnemyRenderer.cs and add the following code. An enemy is three lines that cross at its centre and spin, with a small circle in the middle. The variant changes the colour a little, so a Hunter looks redder and a Splitter looks more violet.
new-file Source/Rendering/EnemyRenderer.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Data;
using LastPerimeter.Entities;
namespace LastPerimeter.Rendering;
public sealed class EnemyRenderer
{
public void Draw(SpriteBatch spriteBatch, Texture2D pixel, Enemy enemy, Color color)
{
Color variantColor = enemy.Variant switch
{
EnemyVariant.Hunter => Color.Lerp(color, Color.Red, 0.35f),
EnemyVariant.Splitter => Color.Lerp(color, Color.Violet, 0.35f),
_ => color,
};
Color accent = Color.Lerp(variantColor, Color.Yellow, 0.45f);
float armLength = enemy.Radius * (enemy.Variant == EnemyVariant.Splitter ? 1.8f : 2.2f);
for (int index = 0; index < 3; index++)
{
float angle = enemy.VisualRotation + (index * MathHelper.TwoPi / 3f);
Vector2 axis = new(MathF.Cos(angle), MathF.Sin(angle));
Vector2 start = enemy.Position - (axis * armLength);
Vector2 end = enemy.Position + (axis * armLength);
PrimitiveDrawing.DrawLine(spriteBatch, pixel, start, end, index % 2 == 0 ? variantColor : accent, 2f);
}
PrimitiveDrawing.DrawFilledCircle(spriteBatch, pixel, enemy.Position, Math.Max(1f, enemy.Radius * 0.35f), accent);
}
}Open Source/Scenes/GameplayScene.cs. Add the following field to the GameplayScene class, below the _playerRenderer field:
add-member Source/Scenes/GameplayScene.cs after=_playerRenderer
csharp
private readonly EnemyRenderer _enemyRenderer = new();In the Draw method, the enemies are drawn after the fuse and before the player, so the player is always on top. Find this line:
find Source/Scenes/GameplayScene.cs
csharp
_playerRenderer.Draw(spriteBatch, _services.Pixel, session.Player, Color.Cyan);Replace it with the following. The last line is the line you found, unchanged:
csharp
for (int index = 0; index < session.Enemies.Count; index++)
{
_enemyRenderer.Draw(spriteBatch, _services.Pixel, session.Enemies[index], Color.OrangeRed);
}
_playerRenderer.Draw(spriteBatch, _services.Pixel, session.Player, Color.Cyan);The key change is the for loop that draws each enemy in orange-red.
Running the tests
In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 66. The 66 tests are the 56 from earlier chapters and the 10 new ones.
| Test | Proves |
|---|---|
Update_AppliesVariantSpeedMultiplier_ToActualMovement | ENM-06 |
Update_WhenFrozen_DoesNotMove | ENM-10 |
Update_BlockedOnX_ReflectsHorizontalVelocity | ENM-03 |
Update_WithSameSeed_RetargetsIdentically | ENM-04, ENM-11 |
Retarget_WithPressureTarget_TurnsTowardPlayer | ENM-05 |
Update_EnemyBesideFreshCapture_RecoversAndKeepsMoving | ENM-02, ENM-09 |
PlayerCollision_OnlyCountsWhileDrawing | COL-01 |
TrailCollision_IsDetected | COL-02 |
EnclosingCapture_RemovesEliminatedEnemies | ENM-12 |
Tick_EnemyTouchingTrail_CancelsTheTrail | COL-02 in the simulation. Chapter 11 rewrites its body. |
Running the game
From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen. An orange-red enemy with three spinning arms appears near the middle of the arena, and your cyan dot sits at the top-left corner.
Watch the enemy for a few seconds. It crosses the open space and turns away from the walls and from any claimed ground, as in Figure 10-1. Hold the Right arrow to move along the top wall. The enemy cannot hurt you here, even when it comes close.
Hold the Down arrow to leave the wall and start a trail. Within a few seconds, the enemy turns towards you. If it touches the trail or your dot, the trail vanishes and you are back at the point where you left the wall. This is the temporary rule.
Now draw a trail that returns to the wall and splits the arena in two. The solver claims the side that holds no enemy, as in Chapter 09, and the enemy keeps roaming the rest. With one enemy, one side is always empty, so you cannot yet see an enemy removed in the game. The scenario test proves that rule with two enemies, and the roster in Chapter 14 lets you watch it happen. Close the window with its close button when you have seen enough. The test counts prove the steering, the collision rules and the enemy removal. Only the window shows the enemy's motion and colour.
If you got lost
This section is optional. Use it only when your project no longer builds or the tests no longer match this chapter. It overwrites your Source and Tests folders with the chapter 10 snapshot, so any change of your own in those folders is lost. <course-repo> is the folder where you cloned the course repository.
WARNING
These commands overwrite your own changes in Source and Tests. Copy your project folder elsewhere first if you want to keep it.
In PowerShell, from the LastPerimeter folder, run the following. Replace <course-repo> with the real path first.
powershell
$snapshot = "<course-repo>/DOCUMENTATION/learning_plan_2/snapshots/10-Enemies-And-Collision"
Remove-Item -Recurse -Force Source, Tests
Copy-Item -Recurse "$snapshot/Source" Source
Copy-Item -Recurse "$snapshot/Tests" TestsIn bash, from the LastPerimeter folder, run the following. Replace <course-repo> with the real path first.
bash
snapshot="<course-repo>/DOCUMENTATION/learning_plan_2/snapshots/10-Enemies-And-Collision"
rm -rf Source Tests
cp -r "$snapshot/Source" Source
cp -r "$snapshot/Tests" TestsThen run dotnet test from the LastPerimeter folder and check for Passed: 66.
Common mistakes
- An enemy that sits still after a capture.
Updateis missing the recovery block, orTryRecoverToFreeGroundstill throws or returns at once. The enemy is on claimed ground and every move fails. - An enemy that sticks to a wall instead of sliding. The X and Y moves are tested from the same shifted position. Each test must change only its own coordinate.
- The Wanderer test reports a position other than 50. The variant multiplier is applied twice, or the speed in
CreateEnemydiffers from 10. The expected distance is10 * 1 * 1.0. Update_WithSameSeed_RetargetsIdenticallyfails. Something other than theRandompassed in feeds the retarget, such as a secondnew Random()or the clock.EnclosingCapture_RemovesEliminatedEnemiesreports 0 eliminated.ResolveCapturestill callsProcessCompletedTrailwithout the enemy positions.- The build says
GameplaySimulationhas no constructor that takes 2 arguments. A caller still uses the old form. CheckSimulationBuilderandGameplayScene, which must both pass aRandom. - A test run shows an enemy where an earlier scenario expects none.
SimulationBuilder.Createno longer clears the enemy thatStartLeveladds.
Conclusion
In this chapter, you accomplished the following:
- Learned why the three variants are one algorithm with two different numbers.
- Built
EnemySystem.Updatein three steps: probes, bounce and freezing, retargeting and recovery. - Understood the freeze bug and wrote the test that reproduces it.
- Built
CollisionSystemwith its two tests. - Wired enemies into the simulation, removed the enclosed ones, and cancelled the trail on contact as a temporary rule.
The tests now prove ENM-02 to ENM-06, ENM-09 to ENM-12, COL-01 and COL-02. In the next chapter, Chapter 11: Lives, Shields and Respawn, you replace the temporary rule with lives, shields and a fair respawn.
Test Your Knowledge
Why does the enemy test its X move and its Y move separately?
Answer
A diagonal mover that slides along a wall is blocked on one axis only. Testing the axes separately flips only the blocked axis, so the enemy keeps moving along the wall instead of stopping or reversing.
What separates a Hunter from a Wanderer?
Answer
Two numbers: the pursuit weight, 0.7 against 0.4, and the speed multiplier, 1.12 against 1.0. The code is the same.
Why is the player not hit when an enemy touches it on the wall?
Answer
The wall is safe space.
IsPlayerHitByEnemyreturnsfalsewhile the player is not drawing, and the simulation only checks contact in the drawing branch of the tick.An enemy has its centre on free ground but one probe on a fresh claim. Why would it never move without the recovery step?
Answer
Every move is tested with all five probes. The probe on the claim fails at the new position as well, so both axes are blocked, the velocity flips, and the flipped move fails too. The recovery step moves the enemy to free ground first.
Extensions
- Change the Hunter's pursuit weight to 1.0 and write a test that a Hunter with a target straight to its right always ends up with a positive X velocity after retargeting. What does the random turn do to the angle?
- Change
RecoverySearchLimitto 2 and run the tests. Which test fails, and what does it tell you about how far an enemy can be from free ground?

