Skip to content

Chapter 07 - Enemies, Collision, and Fairness ​

Where this chapter fits: the arena gets a threat. An enemy bounces through unclaimed space and homes toward you while you draw. If it touches you or your trail while you draw, you lose a life. The fuse now kills, and a capture that traps an enemy eliminates it. The game is now winnable and losable. The later sections cover the enemy variants (Wanderer, Hunter, Splitter), which share this one movement algorithm. The chapter 07 game still shows a single Wanderer, and the variants first appear in play in chapter 10.

Time: [TODO Simon: time estimate for chapter 07]

Chapter 07: the player draws a trail from the left wall while the spinning enemy roams the interior

The chapter 07 build: an enemy (three rotating arms) roams the unclaimed field. While the trail is active the enemy homes toward the player.

Prerequisites ​

Chapters 01-06. Enemies live in unclaimed space, threaten trails and are eliminated by captures. All three of those systems must already work.

Learning objectives ​

By the end of this chapter you should be able to:

  1. implement blended enemy movement (current heading, periodic retargeting, random variation, pressure homing) and axis-separated bouncing,
  2. describe enemy variants as parameter sets (homing weight, speed multiplier) layered over one shared movement system, and verify the speed multiplier with a test,
  3. implement circle-circle collision with squared distances and the safe-on-wall rule,
  4. implement trail collision as point-to-segment distance with tolerance,
  5. implement a timed split-and-expire behaviour (Splitter clones) without leaking entities, and prove the population is bounded,
  6. argue fairness trade-offs for each variant using the collision rules,
  7. wire up lives, death, respawn grace, and the fairest spawn point, and pass the chapter's 38 tests.

Code anchors ​

  • Source/Systems/EnemySystem.cs (movement, the variant homing weights in Retarget, GetVariantSpeedMultiplier, clone lifetime handling in Update, TrySpawnSplitterClone)
  • Source/Systems/CollisionSystem.cs
  • Source/Data/Enums.cs (EnemyVariant: Wanderer, Hunter, Splitter)
  • Source/Entities/Enemy.cs (Variant, VariantTimer, IsTemporaryClone, RemainingLifetimeSeconds), Source/Entities/Trail.cs (ContainsPoint)
  • Source/Rendering/EnemyRenderer.cs (per-variant tint)
  • Source/Game/LastPerimeterApp.cs (chapter 07 staged version: HandlePlayerDeath, the update flow)
  • Tests/Systems/CollisionSystemTests.cs, Tests/Systems/EnemySystemTests.cs, Tests/Systems/EnemySplitterTests.cs

Enemy movement model ​

EnemySystem.Update blends four ingredients: the current movement direction, periodic retargeting, random angular variation, and pressure toward the player while drawing. This is a good compromise between pure randomness, which feels irrelevant, and perfect pursuit, which feels unfair.

Retarget blends the current heading with the direction to the player using a per-variant weight, then jitters the result by up to 35 degrees

Every EnemyRetargetIntervalSeconds (0.65 s, randomised by 0.75x to 1.25x) the enemy picks a new heading:

csharp
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 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));
}

pressureTarget is the player's position only while a trail is active; the app passes null when the player is on the wall, so targetDirection falls back to baseDirection and the enemy wanders. That is the fairness promise expressed in the movement code before collision is even considered.

Staying inside unclaimed space ​

CanOccupy tests five probe points: the centre and the four radius offsets; a blocked axis reflects that velocity component

Between retargets the enemy moves with its velocity, but it must never enter claimed territory or leave the arena. Update tests the X move and the Y move separately with a five-point footprint. It reflects whichever axis is blocked, so an enemy slides along a wall it hits instead of sticking to it. Before any of that, Update checks whether the enemy is already standing on claimed ground. A capture can claim tiles under the enemy's probes, and a Splitter clone can spawn on claimed ground. Without a recovery step every move would fail and the enemy would never move again. So Update first steps the enemy to the nearest free spot:

csharp
// 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;
// ... retarget when the timer runs out ...

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;
}

// ... a blocked move resets the direction timer and Update returns true

CanOccupy is a separate private method of EnemySystem, below Update:

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));
}

The EnemySystem constructor takes an optional Random, which chapter 14 uses to seed enemy movement. The EnemySystem.cs you copy also contains the Splitter clone code, which this chapter explains later. CanOccupy is the grid from chapter 02 doing its O(1) job five times per axis test. After a capture an enemy can find itself with claimed tiles on more than one side. If every candidate fails it simply stays put and retargets, which is a known weakness this design accepts.

TryRecoverToFreeGround is a ring search. It tries 16 directions at each distance, growing the distance by 1 px up to 24 px, so the closest free position wins. If nothing is free within the limit the enemy stays where it is:

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;
            }
        }
    }
}

Two tests cover it. Update_EnemyBesideFreshCapture_RecoversAndKeepsMoving and Update_SplitterCloneOnClaimedGround_RecoversToFreeGround both start with the enemy on claimed ground and check that it ends on free ground.

Collision: the code is small, the rules are the point ​

Two collision tests: circle against circle with squared distances, and a point projected onto each trail segment with a tolerance

CollisionSystem is the shortest system in the project, and that is deliberate. Both predicates are one rule plus one distance test:

csharp
public sealed class CollisionSystem
{
    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;
    }

    public bool IsTrailHitByEnemy(Trail? trail, Enemy enemy)
    {
        return trail is not null && trail.State == TrailState.InProgress && trail.ContainsPoint(enemy.Position, enemy.Radius + 1f);
    }
}

Read the first guard carefully: the player on the wall is safe by definition. IsPlayerHitByEnemy returns false outright unless the player is drawing. That is the safe-on-wall rule expressed as code, and it is a fairness decision before it is a maths decision.

Maths: distance-based collision ​

Player-enemy contact uses distanceSquared(player, enemy) <= (playerRadius + enemyRadius)^2. This is a classic optimisation because it avoids a square root. With radius 6 for the player and 7 for the enemy, contact is a centre distance of 13 px or less.

Trail collision ​

Trail collision checks whether the enemy lies within tolerance of any trail segment. Trail.ContainsPoint projects the point onto each segment, clamps the projection to the segment, and compares squared distances:

csharp
private static float DistanceSquaredToSegment(Vector2 point, Vector2 start, Vector2 end)
{
    Vector2 segment = end - start;
    float segmentLengthSquared = segment.LengthSquared();
    if (segmentLengthSquared <= float.Epsilon)
    {
        return Vector2.DistanceSquared(point, start);
    }

    float projection = Vector2.Dot(point - start, segment) / segmentLengthSquared;
    projection = MathHelper.Clamp(projection, 0f, 1f);

    Vector2 snapped = start + (segment * projection);
    return Vector2.DistanceSquared(point, snapped);
}

This is the same projection idea as PathSegment.Snap in chapter 04, generalised to any orientation with a dot product. The tolerance is enemy.Radius + 1 pixels.

Death and respawn ​

The chapter 07 app upgrades the fuse and collision outcomes from chapter 05's "cancel the trail" to a real death:

csharp
private void HandlePlayerDeath()
{
    _gameSession.Player.Lives = Math.Max(0, _gameSession.Player.Lives - 1);
    _gameSession.Player.CurrentTrail = null;
    _trailSystem.Cancel();
    _fuseSystem.Reset();

    if (_gameSession.Player.Lives <= 0)
    {
        _gameSession.Status = GameStatus.GameOver;
        return;
    }

    Vector2 spawn = _gameSession.PlayableWallPath.Nodes
        .OrderByDescending(node => _gameSession.Enemies.Count == 0 ? 0f : _gameSession.Enemies.Min(enemy => Vector2.DistanceSquared(node, enemy.Position)))
        .First();
    _gameSession.Player.Position = spawn;
    _gameSession.RespawnGraceRemaining = _config.RespawnGraceSeconds;
}

Two fairness details are worth noting. The respawn point is the wall node farthest from the nearest enemy. RespawnGraceRemaining (1.2 s) blocks starting a new trail until the grace period expires, so the player cannot be pressured into instantly dying again. The final game adds a small bonus for well-connected nodes to the same ordering, and chapter 11's shield can intercept the death.

Fairness rules ​

Treat collision as a rules problem as well as a maths problem:

  • when is the player safe on the wall (always),
  • when is the player vulnerable while drawing (to contact and to trail touches),
  • when does a completed capture take priority (the capture is resolved on the frame the trail reconnects, and enemies are checked first on that frame; see "Questions to think about"),
  • what happens during respawn grace (no trail can start, so no vulnerability exists).

These design decisions have a direct impact on the implementation.

Enemy variants: one algorithm, three parameter sets ​

An enemy roster is more than a list of sprites: it is a set of readable pressures with different promises to the player. Think about enemy design in terms of capabilities: roam in open space, pressure the player while drawing, split temporarily, speed up, deny regions. This helps you build combinable behaviour rather than one-off monsters.

There is exactly one movement algorithm, the one in "Enemy movement model" above. The variants (Wanderer, Hunter, Splitter) differ only in two numbers: how strongly they steer toward the player while a trail is active, and how fast they move. The homing weight is the targetWeight switch in the Retarget listing. The speed multiplier is folded into the real displacement every frame (effectiveSpeedMultiplier in the Update listing), so a Hunter genuinely covers more ground:

csharp
private const float HunterSpeedMultiplier = 1.12f;
private const float SplitterSpeedMultiplier = 1.05f;

private static float GetVariantSpeedMultiplier(Enemy enemy)
{
    return enemy.Variant switch
    {
        EnemyVariant.Hunter => HunterSpeedMultiplier,
        EnemyVariant.Splitter => SplitterSpeedMultiplier,
        _ => 1f,
    };
}
VariantHoming weightSpeedTint (EnemyRenderer)Signature
Wanderer0.41.00xpalette Enemy colourthe baseline threat
Hunter0.71.12x35% toward redcuts toward you while you draw
Splitter0.51.05x35% toward violet, shorter armsemits a temporary Hunter clone

pressureTarget is only non-null while the player has an active trail, so on the wall every variant goes back to wandering. That preserves the fairness promise: the wall is safe, drawing is dangerous.

Update_AppliesVariantSpeedMultiplier_ToActualMovement in EnemySystemTests exists because an earlier version applied the multiplier in name only. It is a good example of a test written against the effect, not the code path.

NOTE

The chapter 07 game spawns one Wanderer, so you will not see a Hunter or a Splitter on screen yet. The variant code is already in the EnemySystem.cs you copy in this chapter, and its tests prove it. Chapter 10 puts the variants into play through level data.

The Splitter: temporary multiplication ​

Timeline of a Splitter: a clone at 6 s that lives 5 s, then one every 8 s; at most one clone is alive at a time

The Splitter's timing and the clone's shape are enemy rules, so they live in EnemySystem as named constants and one method. TrySpawnSplitterClone ticks the parent's VariantTimer, re-arms it, and returns the clone (or null). The clone's speed is derived from the parent's actual velocity:

csharp
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);

public Enemy? TrySpawnSplitterClone(Enemy enemy, float deltaTime, bool frozen = false)
{
    if (frozen || enemy.Variant != EnemyVariant.Splitter || enemy.IsTemporaryClone)
    {
        return null;
    }

    enemy.VariantTimer -= deltaTime;
    if (enemy.VariantTimer > 0f)
    {
        return null;
    }

    enemy.VariantTimer = SplitterSplitIntervalSeconds;
    return new Enemy
    {
        Position = enemy.Position + CloneSpawnOffset,
        Velocity = Vector2.Normalize(new Vector2(-enemy.Velocity.Y, enemy.Velocity.X)) * (enemy.Velocity.Length() * CloneSpeedFactor),
        Radius = enemy.Radius * CloneRadiusFactor,
        Variant = EnemyVariant.Hunter,
        IsTemporaryClone = true,
        RemainingLifetimeSeconds = CloneLifetimeSeconds,
    };
}

The method only returns the clone. Adding it to the game is the app's job, and the chapter 07 app never calls TrySpawnSplitterClone. Chapter 10's UpdateEnemies is its first caller. The other half is in EnemySystem.Update, which counts a clone's RemainingLifetimeSeconds down and returns false when it expires:

csharp
if (enemy.IsTemporaryClone)
{
    enemy.RemainingLifetimeSeconds -= deltaTime;
    if (enemy.RemainingLifetimeSeconds <= 0f)
    {
        return false;
    }
}

Three design rules are encoded here: clones cannot themselves split (the enemy.IsTemporaryClone guard), clones are smaller and slightly slower so they read as lesser threats, and clones expire. A Splitter's first split comes 6 s after it spawns, because chapter 10's CreateEnemies sets VariantTimer = EnemySystem.SplitterFirstSplitDelaySeconds. Splits then repeat every 8 s, while each clone lives 5 s, so at most one clone per Splitter exists at any moment. The population is bounded by construction, not by tuning luck. A clone that spawns on claimed ground is moved to free ground by EnemySystem.Update, using the recovery step in "Staying inside unclaimed space".

Update_TemporaryClone_ExpiresWhenLifetimeRunsOut in EnemySystemTests pins the expiry. EnemySplitterTests pins the timer, the clone's shape and the never-split rules (TrySpawnSplitterClone_WaitsForTheSplitTimer_ThenRearmsIt, SpawnedClone_IsASmallerSlowerTemporaryHunter, ClonesOtherVariantsAndFrozenSplitters_NeverSplit).

Encounter design rules ​

Encounters are scheduled by data, not scattered if (level == 7) checks. LevelProgressionSystem.CreateLevel in chapter 10 introduces one new pressure at a time: slot 1 becomes a Hunter at level 4, slot 2 a Splitter at level 7, and slot 3 a second Hunter at level 10. The chapter 10 app also shows the roster in the status line (LEVEL 7: WANDERER / HUNTER / SPLITTER), so a player can read the encounter before it starts. You should still control encounters by:

  • limiting simultaneous new mechanics,
  • pairing fast enemies with simpler arenas,
  • pairing complex arenas (pre-claimed insets) with fewer enemies,
  • using spawn timing and position as difficulty levers (chapter 10's CreateEnemies spreads spawns across the arena width),
  • protecting readability first.

Build it step by step ​

This chapter is copy-along. Step 1 copies the chapter's files from the snapshot, and the steps after it walk through what changed and why.

Step 1 - Copy the chapter files ​

From your LastPerimeter folder, copy the Source and Tests folders from this chapter's snapshot over your own. The command creates any folders you do not have yet and overwrites the files that changed. Replace <course-repo> with the path to your copy of the course repository (the course index explains how to get it).

In PowerShell:

powershell
Copy-Item -Recurse -Force "<course-repo>/DOCUMENTATION/LastPerimeter-Source/07-Enemies-Collision-And-Fairness/Source", "<course-repo>/DOCUMENTATION/LastPerimeter-Source/07-Enemies-Collision-And-Fairness/Tests" .

In bash:

bash
cp -R "<course-repo>/DOCUMENTATION/LastPerimeter-Source/07-Enemies-Collision-And-Fairness/Source" "<course-repo>/DOCUMENTATION/LastPerimeter-Source/07-Enemies-Collision-And-Fairness/Tests" .

That copy brings in these files. The listings in this chapter show the parts worth studying, not every line.

New files:

  • Source/Rendering/EnemyRenderer.cs
  • Source/Systems/CollisionSystem.cs
  • Source/Systems/EnemySystem.cs
  • Tests/Systems/CollisionSystemTests.cs
  • Tests/Systems/EnemySplitterTests.cs
  • Tests/Systems/EnemySystemTests.cs

Replaced files:

  • Source/Game/LastPerimeterApp.cs

EnemyRenderer draws three rotating arms and a core, tinted per variant. EnemySystem.cs already contains the variant weights, the speed multipliers and TrySpawnSplitterClone, although the chapter 07 app spawns one Wanderer and never calls TrySpawnSplitterClone.

NOTE

Every step after this one describes code that is already in the files you just copied. Open the file each step names and read along. You type nothing unless a step says so.

Step 2 - Spawn the first enemy ​

Open Source/Game/LastPerimeterApp.cs. Initialize now constructs the two systems and spawns one enemy at the arena centre, heading down-right:

csharp
Enemies =
[
    new Enemy
    {
        Position = new Vector2(_arenaSystem.Bounds.Center.X, _arenaSystem.Bounds.Center.Y),
        Velocity = Vector2.Normalize(new Vector2(1f, 0.7f)) * _config.EnemySpeed,
    },
],

Step 3 - Move the enemies before the player ​

Open Source/Game/LastPerimeterApp.cs and find Update. It now ticks the respawn grace and moves the enemies before the player logic. The pressure target is the player only while drawing:

csharp
_gameSession.RespawnGraceRemaining = Math.Max(0f, _gameSession.RespawnGraceRemaining - deltaTime);

Vector2? pressureTarget = _trailSystem.HasActiveTrail ? _gameSession.Player.Position : null;
foreach (Enemy enemy in _gameSession.Enemies)
{
    _enemySystem.Update(enemy, _arenaSystem, deltaTime, _config.EnemyRetargetIntervalSeconds, pressureTarget);
}

Step 4 - Turn the fuse and collisions into a death ​

Open Source/Game/LastPerimeterApp.cs and stay in Update. Inside the active-trail branch, the fuse result and the collision check now call HandlePlayerDeath before any movement is considered:

csharp
if (_fuseSystem.Update(_trailSystem.ActiveTrail, playerMoved, deltaTime))
{
    HandlePlayerDeath();
    base.Update(gameTime);
    return;
}

if (_gameSession.Enemies.Any(enemy => _collisionSystem.IsPlayerHitByEnemy(_gameSession.Player, enemy, true) || _collisionSystem.IsTrailHitByEnemy(_trailSystem.ActiveTrail, enemy)))
{
    HandlePlayerDeath();
    base.Update(gameTime);
    return;
}

Step 5 - Give the solver the enemies ​

Open Source/Game/LastPerimeterApp.cs and stay in Update. The app now passes enemy positions into the solver so region selection can see them. It removes eliminated enemies after the claim is applied, highest index first, so the indexes stay valid:

csharp
claimResult = _areaClaimingSystem.ProcessCompletedTrail(completedTrail, _gameSession.Enemies.Select(enemy => enemy.Position).ToList());
// ... after ApplyClaimResult, the rebuild, and MarkDirty:
if (claimResult.EliminatedEnemyIndexes is not null)
{
    foreach (int eliminatedIndex in claimResult.EliminatedEnemyIndexes.OrderByDescending(index => index))
    {
        if (eliminatedIndex >= 0 && eliminatedIndex < _gameSession.Enemies.Count)
        {
            _gameSession.Enemies.RemoveAt(eliminatedIndex);
        }
    }
}

if (_gameSession.ClaimedAreaPercentage >= _config.WinClaimPercentage)
{
    _gameSession.Status = GameStatus.LevelComplete;
}

Step 6 - Block trail starts during grace ​

Open Source/Game/LastPerimeterApp.cs and find the trail-start condition in Update. It now begins with _gameSession.RespawnGraceRemaining <= 0f &&, which blocks trail starts during grace.

Step 7 - Draw the enemies ​

Open Source/Game/LastPerimeterApp.cs and find Draw. It now draws enemies after the trail and before the player. The chapter app also writes lives and the claimed percentage into the window title (Window.Title), the cheapest possible HUD until chapter 08.

Step 8 - Read the Splitter tests ​

Open Tests/Systems/EnemySplitterTests.cs. Its three tests pin the split timer, the clone's shape and the never-split rules. They call EnemySystem.TrySpawnSplitterClone directly, which is how this chapter proves behaviour that the chapter 07 game does not yet show on screen.

Step 9 - Build, test, run ​

Run these commands from your LastPerimeter folder:

bash
dotnet build
dotnet test
dotnet run --project Platforms/DesktopVK

dotnet test reports 38 passing tests, including the new CollisionSystemTests, EnemySystemTests and EnemySplitterTests.

The last command opens the game window. Press Escape to close it.

Chapter snapshot ​

The matching buildable project is DOCUMENTATION/LastPerimeter-Source/07-Enemies-Collision-And-Fairness; build and test it standalone with dotnet build and dotnet test. This chapter stages CollisionSystemTests, EnemySystemTests and EnemySplitterTests, bringing the suite to 38 passing tests. The chapter app also wires in lives, death, respawn grace, and enemy elimination by capture. It still spawns one Wanderer. The variant and Splitter code in EnemySystem.cs is exercised only by the tests until chapter 10.

Checkpoint ​

Chapter 07 after a capture: the enemy-free left region is claimed while the enemy keeps roaming the remaining space

  1. In your LastPerimeter folder, run dotnet test. 38 tests pass, including Update_AppliesVariantSpeedMultiplier_ToActualMovement and PlayerCollision_OnlyCountsWhileDrawing. If your count differs, run the same command in <course-repo>/DOCUMENTATION/LastPerimeter-Source/07-Enemies-Collision-And-Fairness/ and compare.
  2. Run dotnet test --filter EnemySplitterTests. The summary reports 3 passed. These tests are the proof of the Splitter rules in this chapter, because the game does not spawn a Splitter until chapter 10.
  3. Run the game with dotnet run --project Platforms/DesktopVK. One Wanderer bounces through the unclaimed interior, and the window title shows your lives and claimed percentage.
  4. Stand still on the wall while the enemy passes. Nothing happens, because of the safe-on-wall rule. Then press the arrow key that points into the arena (the Controls table in chapter 03 lists every input) and draw a trail into its path. The lives count in the window title drops by one and you respawn on the wall far from the enemy.
  5. Draw a trail from wall to wall that pens the enemy into a small pocket. The other, enemy-free side is claimed even though it is larger, because the enemy-free rule outranks the smallest-region rule. With a single enemy, elimination-by-capture can never trigger in play. ProcessCompletedTrail_CapturesSmallestRegionAndEliminatesContainedEnemy_WhenEachSideContainsAnEnemy exercises the both-sides-occupied fallback, and the app wiring that removes eliminated enemies is ready for the multi-enemy levels of chapter 10.

What you should have now ​

You now have:

  • enemy movement in unclaimed space, with directional retargeting,
  • three enemy variants (Wanderer, Hunter, Splitter) as parameters over that one movement algorithm, each with its own homing weight and speed multiplier,
  • Splitter clones that spawn on a timer, expire after 5 s and never split, so the enemy count is bounded,
  • EnemySplitterTests, which proves the Splitter rules before any Splitter appears in play (chapter 10),
  • player collision,
  • trail collision,
  • death handling and respawn logic.

Common mistakes ​

  • letting enemies home toward the player on the wall (breaks the safe-on-wall promise),
  • testing collision after moving the player instead of before,
  • removing eliminated enemies in ascending index order (later indexes shift),
  • forgetting to cancel the trail and reset the fuse on death,
  • respawning at a fixed point next to the enemy,
  • letting clones split (unbounded population),
  • giving a variant its own movement code instead of its own parameters.

Questions to think about ​

Ask yourself: Should a player die if an enemy touches them on the exact frame the trail reconnects? In this build the collision check runs before the completion check, so the answer is yes. The question is a useful way to think about fairness, consistency and update order.

The variants raise more questions:

  • Which enemies can kill on contact while the player is on the wall? (In this codebase: none. CollisionSystem only matters off the wall or against an active trail.)
  • Which enemies should only matter while drawing? (All homing behaviour is trail-gated.)
  • Can Splitter clones plus a Hunter combine into unavoidable deaths near a freshly claimed corner?
  • When does a "hard" encounter become illegible?

These are encounter-design questions as well as collision questions.

Extensions ​

Try to prototype:

  1. enemies that alter capture rules,
  2. enemies that mutate arena geometry,
  3. enemies that coordinate in packs,
  4. boss encounters that temporarily change win conditions,
  5. a path-bound patroller that walks PlayableWallPath nodes, like the edge patrollers of the 1981 original: the one classic threat this roster intentionally omits, and the first enemy that would make the wall unsafe,
  6. a fourth variant of your own: extend EnemyVariant and the two switch expressions with a new weight and multiplier,
  7. a longer encounter schedule, once you have finished chapter 10: extend the roster ladder in LevelProgressionSystem.CreateLevel,
  8. more tests for collision and enemy-selection edge cases in EnemySystemTests.