Skip to content

Chapter 14: Levels and Difficulty ​

In Chapter 13: Proving the Level, you wrote scenario tests that play one level through the simulation. The game still has exactly one level. The enemy is a single Wanderer, the arena is empty, and capturing most of it does nothing.

In this chapter, you turn one level into a sequence. Each level is data built from four formulas, and its services are built together so that no part of one level leaks into the next.

Figure 14-1: The chapter 14 level complete screen, shown after a capture reaches the target
Figure 14-1: The chapter 14 level complete screen, shown after a capture reaches the target. This is a drawn illustration, not a screenshot.

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

In this chapter, you will:

  • Describe a level as data with LevelDefinition, and build it from four formulas.
  • Apply a difficulty preset as one adjustment over the curve.
  • Build LevelServices, the group of per-level services that is created in one call.
  • Move enemy creation and the inset claim into the services that own them.
  • Add the Splitter and its temporary clones.
  • Clear a level with its two bonuses and start the next one.

Requirements in this chapter ​

IDShort name
LVL-01A level is cleared at its target
LVL-02 to LVL-04Enemy count, speed and target formulas
LVL-05The inset border from level 6
LVL-06The roster schedule
LVL-07Difficulty presets
LVL-08The level reset keeps the run
LIV-01Starting lives by difficulty
ARN-08The inset claim
ENM-01The roster's spawn positions
ENM-07, ENM-08The Splitter and its clones
ENM-09A clone on claimed ground recovers
SCO-05, SCO-06Level and threshold bonuses

Levels as data ​

A level is not a class. It is a record of six values. These are a number, a name, the percentage to claim, an enemy speed multiplier, a list of enemy variants and the number of pre-claimed border tiles. The list of variants is the level's roster, with one entry per enemy. A record is enough because every level behaves the same way. Only the numbers differ.

Keeping levels as data has a practical benefit. A test can ask for level 7 and read its numbers without running any game code. Nothing needs a window, a scene or a timer.

The curve ​

A difficulty curve says how hard each level is. Here, four formulas draw it, and each one is capped so that the game stays playable. For a level number n:

  • The enemy count is 1 + (n - 1) / 3, never more than 4. The division drops the fraction.
  • The enemy speed multiplier is 1 + (n - 1) x 0.1.
  • The claim target is 75 + (n - 1) percent, never more than 90.
  • The inset is (n - 4) / 2 tiles from level 5 onwards, never more than 3. The division drops the fraction, so the first visible inset is at level 6.

The roster has its own schedule. Slot 1 is always a Wanderer. Slot 2 becomes a Hunter from level 4. Slot 3 becomes a Splitter from level 7. Slot 4 becomes a Hunter from level 10. Any slot that has not met its level stays a Wanderer. Figure 14-2 plots all four formulas.

Figure 14-2: The four formulas for levels 1 to 12 on the Classic preset
Figure 14-2: The four formulas for levels 1 to 12 on the Classic preset

Difficulty as one adjustment ​

The player picks a difficulty preset: Chill, Classic or Hardcore. A preset does not change the formulas. It adjusts the numbers they produce. Chill lowers the target by 5, never below 70, and multiplies the speed by 0.9. Hardcore raises the target by 5, never above 90, and multiplies the speed by 1.15. Classic changes nothing.

Applying the adjustment once, after the curve, keeps the formulas easy to read. The preset also sets the starting lives: 4 on Chill, 3 on Classic and 2 on Hardcore. Lives belong to the run and not to a level, so they are a separate operation.

Insets ​

An inset claims a ring of tiles round the edge of the arena before the level starts. The playable space shrinks without any new rule. The claim goes through the same ApplyClaimResult that a capture uses, so the claimed percentage already counts the ring. Figure 14-3 shows an inset of 2.

Figure 14-3: An inset claims the outer rings of tiles, and the wall path is rebuilt round what remains
Figure 14-3: An inset claims the outer rings of tiles, and the wall path is rebuilt round what remains

All or nothing ​

Each level needs its own arena, wall builder, claim solver, trail service and fuse. In Chapter 13, the simulation holds five separate fields for these. Starting a new level means replacing all five. If one replacement is forgotten, the game keeps running with an arena from one level and a fuse from another. Nothing fails loudly, and the bug appears as strange behaviour many frames later.

LevelServices removes that risk. It is one record that holds every per-level service, and one method, Create, builds all of them. The simulation keeps a single reference and swaps it for a new one at the start of each level. A frame sees the old level or the new level, never a mixture. You build it later in this chapter, and it replaces the five fields.

The Splitter ​

The Splitter is the third kind of enemy. It moves like the others, but it carries a timer. The first time the timer reaches zero is after 6 seconds. It then spawns a clone, a smaller and slower temporary Hunter, and re-arms the timer for 8 seconds. A clone lives for 5 seconds and then expires. Figure 14-4 shows the first three splits.

A clone never splits, and neither does a frozen Splitter. The cadence is longer than the lifetime, so at most one clone per Splitter is alive at any moment. That is why the enemy count stays bounded without any extra limit.

Figure 14-4: A Splitter spawns a clone at 6 s, 14 s and 22 s, and each clone lives for 5 s
Figure 14-4: A Splitter spawns a clone at 6 s, 14 s and 22 s, and each clone lives for 5 s

Bonuses ​

Clearing a level adds two bonuses. The level bonus is 1,000 plus 500 times the level number, so level 3 gives 2,500. The threshold bonus is 1,000 for every whole percent above the target, so 78.6 percent on a 75 percent target gives 3,000. The fraction is dropped, and a result below the target gives nothing.

Adding the level data ​

You start with the two data types. A level needs a difficulty preset to build from, and a record to hold the result.

Open Source/Data/Enums.cs. Add the following enum to the end of the file, below the EnemyVariant enum:

add-type Source/Data/Enums.cs
csharp
public enum DifficultyPreset
{
    Chill,
    Classic,
    Hardcore,
}

In the Source/Data folder, create a new file named LevelDefinition.cs and add the following code. The last parameter has a default, so a level without an inset needs no value for it.

new-file Source/Data/LevelDefinition.cs
csharp
namespace LastPerimeter.Data;

public sealed record LevelDefinition(
    int Number,
    string Name,
    float RequiredClaimPercentage,
    float EnemySpeedMultiplier,
    IReadOnlyList<EnemyVariant> EnemyVariants,
    int PreclaimedInsetTiles = 0);

The key things to note are:

  • EnemyVariants is a read-only list, so a level cannot be changed once it is built.
  • PreclaimedInsetTiles is the only value with a default, which is 0.

Building the level progression service ​

LevelProgressionSystem turns a level number and a preset into a LevelDefinition. It has no state, so one instance serves the whole run. You build it in three rounds. The first round handles the four formulas, the second adds the starting lives, and the third adds the preset and the inset.

The first round needs only the shell of the service. In the Source/Systems folder, create a new file named LevelProgressionSystem.cs and add the following code. Both operations throw for now:

new-file Source/Systems/LevelProgressionSystem.cs
csharp
using LastPerimeter.Data;

namespace LastPerimeter.Systems;

public sealed class LevelProgressionSystem
{
    public int GetStartingLives(DifficultyPreset difficulty)
    {
        throw new NotImplementedException();
    }

    public LevelDefinition CreateLevel(int levelNumber, DifficultyPreset difficulty)
    {
        throw new NotImplementedException();
    }
}

Creating a level from the formulas ​

LevelProgressionSystem.CreateLevel(levelNumber, difficulty) : LevelDefinition

  • Takes: a level number from 1 upwards and a difficulty preset.
  • Gives: the definition of that level.
  • Promises: the enemy count, speed multiplier and target follow the curve. The roster follows the schedule. The inset starts at level 6. A preset adjusts the target and the speed.
  • Refuses: nothing. Every level number has a definition, and the caps keep the numbers sensible.
  • Requirements: LVL-02, LVL-03, LVL-04, LVL-05, LVL-06, LVL-07.

In the Tests/Systems folder, create a new file named LevelProgressionSystemTests.cs and add the following code. The test builds level 7 on Classic and checks the roster and the target. The target is 75 plus 6, which is 81.

new-file Tests/Systems/LevelProgressionSystemTests.cs
csharp
using LastPerimeter.Data;
using LastPerimeter.Systems;

namespace LastPerimeter.Tests.Systems;

public sealed class LevelProgressionSystemTests
{
    [Fact]
    public void CreateLevel_ScalesEnemyRosterAndGoal()
    {
        LevelProgressionSystem system = new();

        LevelDefinition definition = system.CreateLevel(7, DifficultyPreset.Classic);

        Assert.Equal(7, definition.Number);
        Assert.Equal(3, definition.EnemyVariants.Count);
        Assert.True(definition.RequiredClaimPercentage >= 81f);
        Assert.Contains(EnemyVariant.Splitter, definition.EnemyVariants);
    }
}

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 85. The 85 passes are the tests of earlier chapters, and the failure is the new test.

Open Source/Systems/LevelProgressionSystem.cs. Find the CreateLevel method and replace the whole method with the following. It applies the curve and the roster schedule, and leaves the preset and the inset for later:

replace-method Source/Systems/LevelProgressionSystem.cs CreateLevel
csharp
    public LevelDefinition CreateLevel(int levelNumber, DifficultyPreset difficulty)
    {
        int enemyCount = Math.Min(1 + ((levelNumber - 1) / 3), 4);
        float speedMultiplier = 1f + ((levelNumber - 1) * 0.1f);
        float requiredClaim = Math.Min(75f + (levelNumber - 1), 90f);

        List<EnemyVariant> variants = new();
        for (int index = 0; index < enemyCount; index++)
        {
            variants.Add(index switch
            {
                1 when levelNumber >= 4 => EnemyVariant.Hunter,
                2 when levelNumber >= 7 => EnemyVariant.Splitter,
                3 when levelNumber >= 10 => EnemyVariant.Hunter,
                _ => EnemyVariant.Wanderer,
            });
        }

        return new LevelDefinition(levelNumber, $"LEVEL {levelNumber}", requiredClaim, speedMultiplier, variants);
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 86.

The key things to note are:

  • Each formula is one line. The cap is a Math.Min, so a level number of 500 still gives 4 enemies and a target of 90.
  • Integer division drops the fraction, so (levelNumber - 1) / 3 is 0 for levels 1 to 3 and 1 for levels 4 to 6.
  • The roster uses a switch expression with when guards. New to switch expressions? See the C# primer. A slot gets its special variant only from the level that unlocks it. Every other case falls through to the Wanderer.

Starting lives ​

LevelProgressionSystem.GetStartingLives(difficulty) : int

  • Takes: a difficulty preset.
  • Gives: the number of lives a run starts with.
  • Promises: 4 on Chill, 3 on Classic and 2 on Hardcore.
  • Refuses: nothing.
  • Requirements: LIV-01.

The next test is a [Theory]. A normal test is marked [Fact] and runs once. A theory runs once for each [InlineData] row, with the row's values passed as the method's arguments. New to theories? See the C# primer. The test runner counts each row as its own test, so this theory adds 3 to the total, and a failure names the row that failed.

Open Tests/Systems/LevelProgressionSystemTests.cs. Add the following test to the LevelProgressionSystemTests class, below the CreateLevel_ScalesEnemyRosterAndGoal test:

add-member Tests/Systems/LevelProgressionSystemTests.cs after=CreateLevel_ScalesEnemyRosterAndGoal
csharp
    [Theory]
    [InlineData(DifficultyPreset.Chill, 4)]
    [InlineData(DifficultyPreset.Classic, 3)]
    [InlineData(DifficultyPreset.Hardcore, 2)]
    public void GetStartingLives_DependsOnDifficulty(DifficultyPreset difficulty, int expectedLives)
    {
        LevelProgressionSystem system = new();

        Assert.Equal(expectedLives, system.GetStartingLives(difficulty));
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 3 and Passed: 86. All three rows fail, because the stub throws.

Open Source/Systems/LevelProgressionSystem.cs. Find the GetStartingLives method and replace the whole method with the following:

replace-method Source/Systems/LevelProgressionSystem.cs GetStartingLives
csharp
    public int GetStartingLives(DifficultyPreset difficulty) => difficulty switch
    {
        DifficultyPreset.Chill => 4,
        DifficultyPreset.Hardcore => 2,
        _ => 3,
    };

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 89.

The key things to note are:

  • The switch expression names Chill and Hardcore and treats everything else as Classic. A new preset added later gets 3 lives until someone gives it a line.
  • The method body is the expression itself, so there is no return keyword.

Presets and insets ​

Two more tests finish the service. Open Tests/Systems/LevelProgressionSystemTests.cs. Add the following test to the LevelProgressionSystemTests class, above the GetStartingLives_DependsOnDifficulty test. It compares level 3 on Chill and Hardcore:

add-member Tests/Systems/LevelProgressionSystemTests.cs before=GetStartingLives_DependsOnDifficulty
csharp
    [Fact]
    public void CreateLevel_AppliesDifficultyPresetAdjustments()
    {
        LevelProgressionSystem system = new();

        LevelDefinition chill = system.CreateLevel(3, DifficultyPreset.Chill);
        LevelDefinition hardcore = system.CreateLevel(3, DifficultyPreset.Hardcore);

        Assert.True(chill.RequiredClaimPercentage < hardcore.RequiredClaimPercentage);
        Assert.True(chill.EnemySpeedMultiplier < hardcore.EnemySpeedMultiplier);
    }

Add the following test below the GetStartingLives_DependsOnDifficulty test. It checks that level 5 has no inset and level 6 has one tile:

add-member Tests/Systems/LevelProgressionSystemTests.cs after=GetStartingLives_DependsOnDifficulty
csharp
    [Fact]
    public void CreateLevel_AddsInsetFromLevelSix()
    {
        LevelProgressionSystem levels = new();

        Assert.Equal(0, levels.CreateLevel(5, DifficultyPreset.Classic).PreclaimedInsetTiles);
        Assert.Equal(1, levels.CreateLevel(6, DifficultyPreset.Classic).PreclaimedInsetTiles);
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 2 and Passed: 89. Both tests fail because the first-round body ignores the preset and never sets an inset.

Open Source/Systems/LevelProgressionSystem.cs. In the CreateLevel method, find this line:

find Source/Systems/LevelProgressionSystem.cs
csharp
        float requiredClaim = Math.Min(75f + (levelNumber - 1), 90f);

Add the following line directly below it:

csharp
        int insetTiles = levelNumber >= 5 ? Math.Min((levelNumber - 4) / 2, 3) : 0;

In the same method, find this line:

find Source/Systems/LevelProgressionSystem.cs
csharp
        return new LevelDefinition(levelNumber, $"LEVEL {levelNumber}", requiredClaim, speedMultiplier, variants);

Replace it with the following lines. The tuple block applies the preset, and the new last argument passes the inset:

csharp
        (requiredClaim, speedMultiplier) = difficulty switch
        {
            DifficultyPreset.Chill => (Math.Max(70f, requiredClaim - 5f), speedMultiplier * 0.9f),
            DifficultyPreset.Hardcore => (Math.Min(90f, requiredClaim + 5f), speedMultiplier * 1.15f),
            _ => (requiredClaim, speedMultiplier),
        };

        return new LevelDefinition(levelNumber, $"LEVEL {levelNumber}", requiredClaim, speedMultiplier, variants, insetTiles);

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 91.

The key changes are:

  • insetTiles is a new local. It is 0 below level 5, and otherwise (levelNumber - 4) / 2, capped at 3.
  • The tuple assignment (requiredClaim, speedMultiplier) = difficulty switch { ... } updates both numbers in one step, so the preset is applied once, after the curve. New to tuples? See the C# primer.
  • Math.Max(70f, ...) and Math.Min(90f, ...) keep Chill and Hardcore inside the same bounds as the curve.
  • The last argument of the LevelDefinition constructor is the inset.

Moving the inset claim into the arena ​

The inset needs a way to claim a ring. That belongs to ArenaSystem, because the arena owns the grid.

ArenaSystem.ApplyInsetClaim(insetTiles) : void

  • Takes: the number of rings to claim.
  • Gives: nothing. The arena changes.
  • Promises: every tile within insetTiles of an edge becomes claimed. Every other tile stays as it was.
  • Refuses: zero or a negative number does nothing.
  • Requirements: ARN-08.

The method builds a Region, so the file needs one more using. Open Source/Systems/ArenaSystem.cs. At the top of the file, add the following line below the other using lines:

add-using Source/Systems/ArenaSystem.cs
csharp
using LastPerimeter.Entities;

Add the following stub to the ArenaSystem class, below the GetClaimedPercentage method:

add-member Source/Systems/ArenaSystem.cs at=end
csharp
    // Claims the outer rings of tiles before a level starts. Zero or less does nothing.
    public void ApplyInsetClaim(int insetTiles)
    {
        throw new NotImplementedException();
    }

Open Tests/Systems/ArenaSystemTests.cs. Add the following test to the end of the ArenaSystemTests class. The test arena is 10 by 5 tiles, so a ring of 1 claims 50 minus the 8 by 3 tiles in the middle, which is 26:

add-member Tests/Systems/ArenaSystemTests.cs at=end
csharp
    [Fact]
    public void ApplyInsetClaim_ClaimsOnlyTheBorderRing()
    {
        ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));

        arena.ApplyInsetClaim(0);
        Assert.Equal(0, arena.ClaimedTileCount);

        arena.ApplyInsetClaim(1);

        Assert.Equal(50 - (8 * 3), arena.ClaimedTileCount);
        Assert.Equal(TileState.ClaimedByPlayer, arena.GetTileState(new Point(0, 0)));
        Assert.Equal(TileState.ClaimedByPlayer, arena.GetTileState(new Point(9, 4)));
        Assert.Equal(TileState.Unclaimed, arena.GetTileState(new Point(1, 1)));
        Assert.Equal(TileState.Unclaimed, arena.GetTileState(new Point(5, 2)));
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 1 and Passed: 91.

Open Source/Systems/ArenaSystem.cs. Find the ApplyInsetClaim method and replace the whole method with the following:

replace-method Source/Systems/ArenaSystem.cs ApplyInsetClaim
csharp
    // Claims the outer rings of tiles before a level starts. Zero or less does nothing.
    public void ApplyInsetClaim(int insetTiles)
    {
        if (insetTiles <= 0)
        {
            return;
        }

        Region captured = new();
        Region remaining = new();
        for (int x = 0; x < GridWidth; x++)
        {
            for (int y = 0; y < GridHeight; y++)
            {
                Point tile = new(x, y);
                if (x < insetTiles || y < insetTiles || x >= GridWidth - insetTiles || y >= GridHeight - insetTiles)
                {
                    captured.Tiles.Add(tile);
                }
                else
                {
                    remaining.Tiles.Add(tile);
                }
            }
        }

        ApplyClaimResult(new ClaimResult(captured, remaining, []));
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 92.

The key things to note are:

  • The method sorts every tile into the captured region or the remaining region, then calls ApplyClaimResult once. It reuses the claim code, so the count and the percentage stay right.
  • The condition x >= GridWidth - insetTiles is the mirror of x < insetTiles. Together the four comparisons describe a frame of tiles.
  • The trail list of the claim is empty, because an inset has no trail.

Building the roster and the Splitter ​

The simulation has so far created its one Wanderer by hand. EnemySystem takes that job over, and it also learns to spawn Splitter clones.

Creating the roster ​

EnemySystem.CreateRoster(levelDefinition, arenaBounds, enemySpeed) : IEnumerable<Enemy>

  • Takes: a level definition, the arena rectangle and the base enemy speed.
  • Gives: one enemy per roster slot.
  • Promises: the enemies spread across the arena from left to right, each inside the bounds. A Splitter starts its timer at 6 seconds.
  • Refuses: nothing. An empty roster gives no enemies.
  • Requirements: ENM-01.

Open Source/Systems/EnemySystem.cs. Add the following stub to the EnemySystem class, above the Update method:

add-member Source/Systems/EnemySystem.cs before=Update
csharp
    public IEnumerable<Enemy> CreateRoster(LevelDefinition levelDefinition, Rectangle arenaBounds, float enemySpeed)
    {
        throw new NotImplementedException();
    }

Open Tests/Systems/EnemySystemTests.cs. Add the following test to the end of the EnemySystemTests class. It builds a roster of three on an 80 by 200 arena and checks the spread and the Splitter timer:

add-member Tests/Systems/EnemySystemTests.cs at=end
csharp
    [Fact]
    public void CreateRoster_SpreadsEnemiesAcrossTheArena()
    {
        EnemySystem enemySystem = new();
        LevelDefinition level = new(7, "LEVEL 7", 75f, 1f, [EnemyVariant.Wanderer, EnemyVariant.Hunter, EnemyVariant.Splitter]);
        Rectangle bounds = new(0, 0, 80, 200);

        Enemy[] roster = enemySystem.CreateRoster(level, bounds, 90f).ToArray();

        Assert.Equal(3, roster.Length);
        Assert.Equal(3, roster.Select(enemy => enemy.Position.X).Distinct().Count());
        Assert.All(roster, enemy => Assert.True(bounds.Contains(enemy.Position)));
        Assert.Equal(EnemySystem.SplitterFirstSplitDelaySeconds, roster[2].VariantTimer);
        Assert.Equal(0f, roster[0].VariantTimer);
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 1 and Passed: 92.

Open Source/Systems/EnemySystem.cs. Find the CreateRoster method and replace the whole method with the following:

replace-method Source/Systems/EnemySystem.cs CreateRoster
csharp
    // One enemy per roster slot, spread across the arena. Splitters start their timer at 6 seconds.
    public IEnumerable<Enemy> CreateRoster(LevelDefinition levelDefinition, Rectangle arenaBounds, float enemySpeed)
    {
        int count = levelDefinition.EnemyVariants.Count;
        for (int index = 0; index < count; index++)
        {
            float horizontalFactor = (index + 1f) / (count + 1f);
            Vector2 position = new(
                arenaBounds.Left + (arenaBounds.Width * horizontalFactor),
                arenaBounds.Center.Y + ((index % 2 == 0 ? -1 : 1) * 40f));
            Vector2 velocity = Vector2.Normalize(new Vector2(index % 2 == 0 ? 1f : -1f, 0.7f + (index * 0.15f))) * enemySpeed;

            yield return new Enemy
            {
                Position = position,
                Velocity = velocity,
                Variant = levelDefinition.EnemyVariants[index],
                VariantTimer = levelDefinition.EnemyVariants[index] == EnemyVariant.Splitter ? SplitterFirstSplitDelaySeconds : 0f,
            };
        }
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 93.

The key things to note are:

  • The method is an iterator. Each yield return hands back one enemy, and the caller can add the whole sequence to a list.
  • The horizontal factor (index + 1) / (count + 1) spreads the enemies evenly. With three enemies they sit at a quarter, a half and three quarters of the width.
  • Even slots sit 40 pixels above the middle and odd slots 40 below. The alternating direction and the growing vertical part of the velocity give each enemy a different heading.
  • VariantTimer is 6 seconds for a Splitter and 0 for every other variant.

Spawning a Splitter clone ​

EnemySystem.TrySpawnSplitterClone(enemy, deltaTime, frozen) : Enemy?

  • Takes: an enemy, the frame time and whether enemies are frozen.
  • Gives: a new clone, or null.
  • Promises: a Splitter's timer counts down. At zero it produces a smaller, slower, temporary Hunter and re-arms the timer for 8 seconds.
  • Refuses: a clone, a non-Splitter or a frozen Splitter gives null and its timer is untouched.
  • Requirements: ENM-07, ENM-08.

Open Source/Systems/EnemySystem.cs. Add the following stub to the end of the EnemySystem class:

add-member Source/Systems/EnemySystem.cs at=end
csharp
    public Enemy? TrySpawnSplitterClone(Enemy enemy, float deltaTime, bool frozen = false)
    {
        throw new NotImplementedException();
    }

In the Tests/Systems folder, create a new file named EnemySplitterTests.cs and add the following code. The three tests cover the timer, the clone's shape and the three refusals. The CreateSplitter helper builds a Splitter whose timer is already at 6 seconds.

new-file Tests/Systems/EnemySplitterTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
using LastPerimeter.Systems;

namespace LastPerimeter.Tests.Systems;

public sealed class EnemySplitterTests
{
    [Fact]
    public void TrySpawnSplitterClone_WaitsForTheSplitTimer_ThenRearmsIt()
    {
        EnemySystem enemySystem = new();
        Enemy splitter = CreateSplitter();

        Enemy? early = enemySystem.TrySpawnSplitterClone(splitter, deltaTime: 1f);
        Enemy? clone = enemySystem.TrySpawnSplitterClone(splitter, deltaTime: EnemySystem.SplitterFirstSplitDelaySeconds);

        Assert.Null(early);
        Assert.NotNull(clone);
        Assert.True(splitter.VariantTimer > 0f);
    }

    [Fact]
    public void SpawnedClone_IsASmallerSlowerTemporaryHunter()
    {
        EnemySystem enemySystem = new();
        Enemy splitter = CreateSplitter();

        Enemy clone = enemySystem.TrySpawnSplitterClone(splitter, deltaTime: EnemySystem.SplitterFirstSplitDelaySeconds + 1f)!;

        Assert.True(clone.IsTemporaryClone);
        Assert.Equal(EnemyVariant.Hunter, clone.Variant);
        Assert.True(clone.RemainingLifetimeSeconds > 0f);
        Assert.True(clone.Radius < splitter.Radius);
        Assert.True(clone.Velocity.Length() < splitter.Velocity.Length());
    }

    [Fact]
    public void ClonesOtherVariantsAndFrozenSplitters_NeverSplit()
    {
        EnemySystem enemySystem = new();
        Enemy clone = CreateSplitter();
        clone.IsTemporaryClone = true;
        Enemy wanderer = new()
        {
            Position = new Vector2(100f, 100f),
            Velocity = new Vector2(60f, 30f),
            Variant = EnemyVariant.Wanderer,
        };
        Enemy frozenSplitter = CreateSplitter();

        Assert.Null(enemySystem.TrySpawnSplitterClone(clone, deltaTime: 100f));
        Assert.Null(enemySystem.TrySpawnSplitterClone(wanderer, deltaTime: 100f));
        Assert.Null(enemySystem.TrySpawnSplitterClone(frozenSplitter, deltaTime: 100f, frozen: true));
        Assert.Equal(EnemySystem.SplitterFirstSplitDelaySeconds, frozenSplitter.VariantTimer);
    }

    private static Enemy CreateSplitter()
    {
        return new Enemy
        {
            Position = new Vector2(100f, 100f),
            Velocity = new Vector2(60f, 30f),
            Variant = EnemyVariant.Splitter,
            VariantTimer = EnemySystem.SplitterFirstSplitDelaySeconds,
        };
    }
}

Two more tests go in EnemySystemTests.cs, because they exercise Update. Open Tests/Systems/EnemySystemTests.cs. Add the following test to the EnemySystemTests class, above the Update_WithSameSeed_RetargetsIdentically test. It gives a clone half a second to live and updates it for a full second:

add-member Tests/Systems/EnemySystemTests.cs before=Update_WithSameSeed_RetargetsIdentically
csharp
    [Fact]
    public void Update_TemporaryClone_ExpiresWhenLifetimeRunsOut()
    {
        ArenaSystem arena = new(TestConfigFactory.Create(width: 80, height: 80, margin: 0, tileSize: 4));
        EnemySystem enemySystem = new();
        Enemy clone = CreateEnemy(EnemyVariant.Hunter);
        clone.IsTemporaryClone = true;
        clone.RemainingLifetimeSeconds = 0.5f;

        bool alive = enemySystem.Update(clone, arena, deltaTime: 1f, retargetIntervalSeconds: 100f);

        Assert.False(alive);
    }

Add the following test below the Update_EnemyBesideFreshCapture_RecoversAndKeepsMoving test. It spawns a clone, claims the ground under it, and checks that the next update moves it to free ground:

add-member Tests/Systems/EnemySystemTests.cs after=Update_EnemyBesideFreshCapture_RecoversAndKeepsMoving
csharp
    [Fact]
    public void Update_SplitterCloneOnClaimedGround_RecoversToFreeGround()
    {
        ArenaSystem arena = new(TestConfigFactory.Create(width: 80, height: 80, margin: 0, tileSize: 4));
        EnemySystem enemySystem = new(new Random(3));
        Enemy splitter = new()
        {
            Position = new Vector2(30f, 40f),
            Velocity = new Vector2(40f, 0f),
            Radius = 8f,
            DirectionChangeTimer = 100f,
            Variant = EnemyVariant.Splitter,
            VariantTimer = 0f,
        };

        Enemy? clone = enemySystem.TrySpawnSplitterClone(splitter, deltaTime: 0.1f);
        Assert.NotNull(clone);
        ClaimColumns(arena, firstColumn: 10, lastColumn: 19);
        Assert.False(arena.IsUnclaimedWorld(clone.Position));

        bool alive = enemySystem.Update(clone, arena, deltaTime: 1f / 60f, retargetIntervalSeconds: 100f);

        Assert.True(alive);
        Assert.True(arena.IsUnclaimedWorld(clone.Position));
        Assert.True(arena.IsUnclaimedWorld(clone.Position + new Vector2(clone.Radius, 0f)));
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 4 and Passed: 94. The three splitter tests and the recovery test fail on the stub. The expiry test already passes, because the lifetime countdown has been part of Update since Chapter 10.

Open Source/Systems/EnemySystem.cs. Find the TrySpawnSplitterClone method and replace the whole method with the following:

replace-method Source/Systems/EnemySystem.cs TrySpawnSplitterClone
csharp
    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,
        };
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 98.

The key things to note are:

  • The refusals come first. A frozen Splitter returns before the timer moves, so a freeze really pauses the split.
  • The timer is a VariantTimer that counts down. Re-arming it to 8 seconds after each split gives the cadence in Figure 14-4.
  • The clone appears 12 pixels right and 12 pixels up from its parent. Its velocity is the parent's velocity turned a quarter circle, at 0.9 of the speed.
  • The clone is a Hunter with IsTemporaryClone set and a 5 second lifetime. The constants for these numbers have been in the file since Chapter 10.
  • A clone can appear on ground that has just been claimed. The recovery test proves that Update moves it to free ground, which is ENM-09.

Adding the bonuses ​

Two small operations calculate what a cleared level is worth. They have no state, so each one is a single expression.

ScoringSystem.CalculateThresholdBonus(claimedPercentage, requiredPercentage) : int

  • Takes: the claimed percentage and the target.
  • Gives: 1,000 points for each whole percent above the target.
  • Promises: the fraction is dropped, so 82 on 75 gives 7,000.
  • Refuses: a result below the target gives 0, never a negative number.
  • Requirements: SCO-06.

ScoringSystem.CalculateLevelBonus(levelNumber) : int takes a level number and gives 1,000 plus 500 times the level. Requirements: SCO-05.

Open Source/Systems/ScoringSystem.cs. Add the following constant to the ScoringSystem class, below the PointsPerTile constant:

add-member Source/Systems/ScoringSystem.cs after=PointsPerTile
csharp
    private const int PointsPerOvershootPercent = 1000;

Add the following stubs to the end of the ScoringSystem class:

add-member Source/Systems/ScoringSystem.cs at=end
csharp
    public int CalculateThresholdBonus(float claimedPercentage, float requiredPercentage)
    {
        throw new NotImplementedException();
    }

    public int CalculateLevelBonus(int levelNumber)
    {
        throw new NotImplementedException();
    }

Open Tests/Systems/ScoringSystemTests.cs. Add the following tests to the end of the ScoringSystemTests class. One checks 82 percent against a 75 percent target and 74.5 against 75. The other checks levels 1 and 5:

add-member Tests/Systems/ScoringSystemTests.cs at=end
csharp
    [Fact]
    public void CalculateThresholdBonus_AwardsPointsPerPercentAboveTarget()
    {
        ScoringSystem scoringSystem = new();

        Assert.Equal(7000, scoringSystem.CalculateThresholdBonus(82f, 75f));
        Assert.Equal(0, scoringSystem.CalculateThresholdBonus(74.5f, 75f));
    }

    [Fact]
    public void CalculateLevelBonus_GrowsWithLevel()
    {
        ScoringSystem scoring = new();

        Assert.Equal(1500, scoring.CalculateLevelBonus(1));
        Assert.Equal(3500, scoring.CalculateLevelBonus(5));
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 2 and Passed: 98.

Open Source/Systems/ScoringSystem.cs. Find the CalculateThresholdBonus method and replace the whole method with the following:

replace-method Source/Systems/ScoringSystem.cs CalculateThresholdBonus
csharp
    public int CalculateThresholdBonus(float claimedPercentage, float requiredPercentage)
    {
        int overshootPercent = (int)MathF.Floor(claimedPercentage - requiredPercentage);
        return Math.Max(0, overshootPercent) * PointsPerOvershootPercent;
    }

Find the CalculateLevelBonus method and replace the whole method with the following:

replace-method Source/Systems/ScoringSystem.cs CalculateLevelBonus
csharp
    public int CalculateLevelBonus(int levelNumber)
    {
        return 1000 + (levelNumber * 500);
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 100.

The key things to note are:

  • MathF.Floor drops the fraction of the overshoot, and Math.Max(0, ...) turns a miss into 0.
  • The two bonuses are separate, so a test can check each without the other.

Teaching the simulation about levels ​

The services are ready. Now the simulation has to use them. This part changes several files, so it has green checkpoints and one red stretch. The project builds and the tests pass after the new events and state, after LevelServices, and again after the last test is updated. The red stretch starts when you replace LivesSystem and ends when the tests are updated. Do not run dotnet test inside it, except where a step tells you to. Follow the steps in order.

New events, a new state and new session members ​

Clearing a level needs a way to say so. Three small additions give it one. In the Source/Simulation folder, open SimulationState.cs. Find this line in the SimulationState enum:

find Source/Simulation/SimulationState.cs
csharp
    Running,

Add the following line directly below it:

csharp
    LevelCleared,

Open Source/Simulation/GameEvent.cs. Add the following record below the GameEvent record. It announces a new level:

add-type Source/Simulation/GameEvent.cs after=GameEvent
csharp
public sealed record LevelStarted(int Level) : GameEvent;

Add the following record to the end of the same file. It carries the bonus of a cleared level:

add-type Source/Simulation/GameEvent.cs
csharp
public sealed record LevelCleared(int Bonus) : GameEvent;

Open Source/Data/GameSession.cs. Add the following property to the GameSession class, below the CaptureHistory property. The session now remembers the definition of the current level:

add-member Source/Data/GameSession.cs after=CaptureHistory
csharp
    public LevelDefinition CurrentLevelDefinition { get; set; } = new(1, "LEVEL 1", 75f, 1f, [EnemyVariant.Wanderer]);

Add the following property below the CurrentLevelDefinition property. It holds the difficulty preset, which is Classic until a later chapter lets the player choose:

add-member Source/Data/GameSession.cs after=CurrentLevelDefinition
csharp
    public DifficultyPreset Difficulty { get; set; } = DifficultyPreset.Classic;

The status line must read the new events. Open Tests/Scenes/StatusTextTests.cs. In the StatusText_MapsEveryEventToALine test, find this line:

find Tests/Scenes/StatusTextTests.cs
csharp
        Assert.Equal("DRAW TO CAPTURE", StatusText.For(new TrailStarted(false)));

Add the following line directly above it:

csharp
        Assert.Equal("LEVEL 3", StatusText.For(new LevelStarted(3)));

In the same test, find this line:

find Tests/Scenes/StatusTextTests.cs
csharp
        Assert.Equal(string.Empty, StatusText.For(new RunLost()));

Add the following line directly below it:

csharp
        Assert.Equal("BONUS 1500", StatusText.For(new LevelCleared(1500)));

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 1 and Passed: 99.

Open Source/Scenes/StatusText.cs. In the For method, find this line:

find Source/Scenes/StatusText.cs
csharp
            TrailStarted trail => trail.SlowDraw ? "SLOW DRAW 2X" : "DRAW TO CAPTURE",

Add the following line directly above it:

csharp
            LevelStarted started => $"LEVEL {started.Level}",

In the same method, find this line:

find Source/Scenes/StatusText.cs
csharp
            RunLost => string.Empty,

Add the following line directly below it:

csharp
            LevelCleared cleared => $"BONUS {cleared.Bonus}",

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 100.

Building LevelServices ​

In the Source/Simulation folder, create a new file named LevelServices.cs and add the following code. The record lists the seven things a level owns. Create is the only place that builds them:

new-file Source/Simulation/LevelServices.cs
csharp
using LastPerimeter.Data;
using LastPerimeter.Systems;

namespace LastPerimeter.Simulation;

// Everything that belongs to one level. The simulation swaps the whole object at
// the start of each level, so the services in it always belong together.
public sealed record LevelServices(
    GameConfig Config,
    LevelDefinition Definition,
    ArenaSystem Arena,
    WallSystemV2 Walls,
    AreaClaimingSystem Claims,
    TrailSystem Trails,
    FuseSystem Fuse)
{
    public static LevelServices Create(GameConfig baseConfig, LevelDefinition definition)
    {
        GameConfig config = baseConfig with
        {
            EnemySpeed = baseConfig.EnemySpeed * definition.EnemySpeedMultiplier,
            WinClaimPercentage = definition.RequiredClaimPercentage,
        };

        ArenaSystem arena = new(config);
        arena.ApplyInsetClaim(definition.PreclaimedInsetTiles);

        return new LevelServices(
            config,
            definition,
            arena,
            new WallSystemV2(),
            new AreaClaimingSystem(arena),
            new TrailSystem(config.MinimumTrailLength),
            new FuseSystem(config.FuseWarningDelaySeconds, config.FuseTriggerDelaySeconds, config.FuseBurnSpeed));
    }
}

LevelServices.Create(baseConfig, definition) : LevelServices

  • Takes: the base configuration and a level definition.
  • Gives: a complete set of per-level services.
  • Promises: every service in the set is built in this one call, from the same configuration copy. The arena already carries the level's inset.
  • Refuses: nothing. The constructor of a record has no way to leave a member out.
  • Requirements: LVL-08.

The key things to note are:

  • baseConfig with { ... } copies the configuration and changes two values. The enemy speed is scaled by the level's multiplier, and the win percentage comes from the level's target. The base configuration is never changed. New to with? See the C# primer.
  • The arena is built first, and the inset is applied before the solver, the trail service and the fuse are built. The solver holds a reference to the arena, so it must get the same one.
  • The record has no setters. A caller cannot replace the arena of a level that is running.
  • Nothing tests Create on its own. The scenario tests at the end of this chapter prove it, because every one of them builds a level through it.

In a terminal, from the LastPerimeter folder, run dotnet test. This is a checkpoint. LevelServices is new and nothing uses it yet, so the build succeeds. The summary line should report Failed: 0 and Passed: 100.

Clearing the level ​

The first scenario test of this part describes the payoff. A capture that reaches the target must clear the level. Open Tests/Simulation/LevelScenarioTests.cs. Add the following test to the end of the LevelScenarioTests class. A frozen enemy keeps the scenario exact, and the 80 by 80 arena makes one rectangle enough:

add-member Tests/Simulation/LevelScenarioTests.cs at=end
csharp
    [Fact]
    public void CaptureReachingTarget_ClearsTheLevel()
    {
        GameplaySimulation sim = SimulationBuilder.Create();
        sim.WithFrozenEnemyAt(3, 40);
        ScriptedInput.Run(sim, ScriptedInput.Right, 4);

        List<GameEvent> events = ScriptedInput.Run(sim, ScriptedInput.Down, 16);

        LevelCleared cleared = Assert.Single(events.OfType<LevelCleared>());
        Assert.Equal(SimulationState.LevelCleared, sim.State);
        Assert.True(cleared.Bonus >= 1500);
        Assert.True(sim.Session.Score >= cleared.Bonus);
        Assert.Empty(ScriptedInput.Run(sim, ScriptedInput.Right, 3));
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 1 and Passed: 100. The simulation does not know about levels yet, so no LevelCleared event arrives.

Handing the level services to the lives service ​

LivesSystem currently takes the trail service, the fuse and the grace time as separate parameters. Each is now a part of LevelServices, so the four operations take the one object instead. This step starts the red stretch. The simulation and the tests still call the old signatures, so the project does not build until the scene and the tests are updated. Open Source/Systems/LivesSystem.cs and replace the whole file with the following. Four methods, the using lines and the class comment change, so the whole file is shown:

replace-file Source/Systems/LivesSystem.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
using LastPerimeter.Simulation;

namespace LastPerimeter.Systems;

public enum HitOutcome
{
    Blocked,
    LifeLost,
    RunOver,
}

// Hits, shields and respawn. Stateless: it changes the session and the level
// services it is given.
public sealed class LivesSystem
{
    private const float ScorePerConnectedSegment = 500f;

    public HitOutcome ResolveHit(GameSession session, LevelServices level)
    {
        if (TryBlockWithShield(session, level))
        {
            return HitOutcome.Blocked;
        }

        if (LoseLife(session, level) <= 0)
        {
            return HitOutcome.RunOver;
        }

        Respawn(session, level);
        return HitOutcome.LifeLost;
    }

    public bool TryBlockWithShield(GameSession session, LevelServices level)
    {
        if (session.ShieldCharges <= 0)
        {
            return false;
        }

        session.ShieldCharges--;
        level.Trails.Cancel();
        level.Fuse.Reset();
        session.Player.CurrentTrail = null;
        session.Player.Position = session.PlayableWallPath.Snap(session.Player.Position);
        session.RespawnGraceRemaining = level.Config.RespawnGraceSeconds;
        return true;
    }

    public int LoseLife(GameSession session, LevelServices level)
    {
        session.Player.Lives = Math.Max(0, session.Player.Lives - 1);
        session.Player.CurrentTrail = null;
        level.Trails.Cancel();
        level.Fuse.Reset();
        return session.Player.Lives;
    }

    // The node with the highest score wins: squared distance to the nearest enemy
    // plus a bonus per connected segment. Ties go to the first node.
    public Vector2 SelectRespawnNode(PlayableWallPath path, IReadOnlyList<Enemy> enemies)
    {
        Vector2 best = Vector2.Zero;
        float bestScore = float.NegativeInfinity;
        IReadOnlyList<Vector2> nodes = path.Nodes;
        for (int index = 0; index < nodes.Count; index++)
        {
            Vector2 node = nodes[index];
            float nearest = 0f;
            if (enemies.Count > 0)
            {
                nearest = float.MaxValue;
                for (int enemyIndex = 0; enemyIndex < enemies.Count; enemyIndex++)
                {
                    nearest = Math.Min(nearest, Vector2.DistanceSquared(node, enemies[enemyIndex].Position));
                }
            }

            float score = nearest + (path.GetConnectedSegmentCount(node) * ScorePerConnectedSegment);
            if (score > bestScore)
            {
                bestScore = score;
                best = node;
            }
        }

        return best;
    }

    public void Respawn(GameSession session, LevelServices level)
    {
        session.Player.Position = SelectRespawnNode(session.PlayableWallPath, session.Enemies);
        session.RespawnGraceRemaining = level.Config.RespawnGraceSeconds;
    }
}

The key changes are:

  • using LastPerimeter.Simulation; is new, because LevelServices lives there.
  • ResolveHit, TryBlockWithShield, LoseLife and Respawn each take a LevelServices in place of the trail, fuse and grace seconds.
  • The grace time now comes from level.Config.RespawnGraceSeconds.

Replacing the per-level fields ​

Here is the payoff. In Chapter 13, GameplaySimulation holds five fields for the services of one level. Read them, but do not type them. Each one is replaced by a field on LevelServices:

csharp
    private readonly WallSystemV2 _walls = new();
    private readonly TrailSystem _trails;
    private readonly FuseSystem _fuse;
    private ArenaSystem _arena;
    private AreaClaimingSystem _claims;

After this step, the simulation has one field. It is not readonly, because each new level swaps it:

csharp
    private LevelServices _level;

Every use of _trails, _fuse, _arena and _claims becomes _level.Trails, _level.Fuse, _level.Arena and _level.Claims. That touches almost every method of the class. The constructor, StartLevel, Tick, UpdateEnemies, the three tick helpers, ResolveHit and ResolveCapture all change. Two new methods, BuildLevel and EnterLevel, and a new Events property join them, and CreateWanderer is removed. A method-by-method edit would repeat the same rename many times. Open Source/Simulation/GameplaySimulation.cs and replace the whole file with the following. The numbered comments in Tick and its helpers follow the table in Chapter 05: Scenes and the Gameplay Simulation, so each number keeps its meaning. Stage 11 of ResolveCapture is new:

replace-file Source/Simulation/GameplaySimulation.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
using LastPerimeter.Input;
using LastPerimeter.Systems;

namespace LastPerimeter.Simulation;

// The headless heart of the game. It owns the session and the services that
// the rules need. It reports what happened as events. It never plays a sound,
// writes the profile, builds text or touches the screen.
public sealed class GameplaySimulation
{
    private const float MovedThresholdSquared = 0.0001f;

    private readonly GameConfig _baseConfig;
    private readonly GameSession _session;
    private readonly MovementSystem _movement = new();
    private readonly EnemySystem _enemies;
    private readonly CollisionSystem _collision = new();
    private readonly ScoringSystem _scoring = new();
    private readonly LivesSystem _lives = new();
    private readonly LevelProgressionSystem _levels = new();
    private readonly List<GameEvent> _events = [];
    private readonly List<Vector2> _enemyPositions = [];
    private readonly List<Enemy> _spawnedClones = [];
    private readonly List<int> _eliminated = [];
    private LevelServices _level;
    private Vector2 _lastPlayerPosition;
    private bool _fuseWarned;

    public GameplaySimulation(GameConfig baseConfig, GameSession session, Random random)
    {
        _baseConfig = baseConfig;
        _session = session;
        _enemies = new EnemySystem(random);
        _level = BuildLevel(session.Level);
        EnterLevel();
    }

    public SimulationState State { get; private set; }
    public GameSession Session => _session;
    public LevelServices Level => _level;

    // The events raised by the latest StartLevel or Tick call.
    public IReadOnlyList<GameEvent> Events => _events;

    // Builds a new LevelServices and resets the level state. Keeps score, lives and shields.
    public IReadOnlyList<GameEvent> StartLevel(int levelNumber)
    {
        _level = BuildLevel(levelNumber);
        EnterLevel();
        return _events;
    }

    // One frame of rules. Returns the reused list of events raised in this frame.
    public IReadOnlyList<GameEvent> Tick(float deltaTime, InputState input)
    {
        _events.Clear();
        if (State != SimulationState.Running)
        {
            return _events;
        }

        Player player = _session.Player;

        // 1. Timers.
        player.IsInvulnerable = _session.RespawnGraceRemaining > 0f;
        _session.RespawnGraceRemaining = Math.Max(0f, _session.RespawnGraceRemaining - deltaTime);
        _session.FreezeEnemiesRemaining = Math.Max(0f, _session.FreezeEnemiesRemaining - deltaTime);

        // 3. The fuse must react to actual displacement, not input: holding a blocked
        // direction leaves the player stationary and the fuse must keep burning.
        bool playerMovedLastFrame = Vector2.DistanceSquared(player.Position, _lastPlayerPosition) > MovedThresholdSquared;
        _lastPlayerPosition = player.Position;

        // 4. Intent: which way does the player want to go?
        Direction direction = _movement.DetermineDirection(input);

        // 5. Enemies.
        UpdateEnemies(deltaTime);

        // 6. Nothing to do with no input and no trail.
        Trail? activeTrail = _level.Trails.ActiveTrail;
        if (direction == Direction.None && activeTrail is null)
        {
            return _events;
        }

        // 7. Where the player would like to be after this frame.
        float speed = _baseConfig.PlayerSpeed * (_session.SlowDrawActive ? TrailSystem.SlowDrawSpeedFactor : 1f);
        Vector2 intendedPosition = _movement.CalculateNextPosition(player.Position, direction, speed, deltaTime);

        if (activeTrail is not null)
        {
            TickWhileDrawing(activeTrail, direction, intendedPosition, playerMovedLastFrame, deltaTime, input);
        }
        else
        {
            TickOnWall(direction, intendedPosition, speed, deltaTime, input);
        }

        return _events;
    }

    private void UpdateEnemies(float deltaTime)
    {
        bool frozen = _session.FreezeEnemiesRemaining > 0f;
        Vector2? pressureTarget = _level.Trails.HasActiveTrail ? _session.Player.Position : null;
        _spawnedClones.Clear();
        for (int index = _session.Enemies.Count - 1; index >= 0; index--)
        {
            Enemy enemy = _session.Enemies[index];
            bool alive = _enemies.Update(enemy, _level.Arena, deltaTime, _level.Config.EnemyRetargetIntervalSeconds, pressureTarget, speedMultiplier: 1f, frozen: frozen);
            if (!alive)
            {
                _session.Enemies.RemoveAt(index);
                continue;
            }

            Enemy? clone = _enemies.TrySpawnSplitterClone(enemy, deltaTime, frozen);
            if (clone is not null)
            {
                _spawnedClones.Add(clone);
            }
        }

        _session.Enemies.AddRange(_spawnedClones);
    }

    private void TickWhileDrawing(Trail activeTrail, Direction direction, Vector2 intendedPosition, bool playerMovedLastFrame, float deltaTime, InputState input)
    {
        Player player = _session.Player;

        // 8a. Fuse.
        bool killedByFuse = _level.Fuse.Update(activeTrail, playerMovedLastFrame, deltaTime);
        if (_level.Fuse.IsWarning && !_fuseWarned)
        {
            _events.Add(new FuseWarning());
            _fuseWarned = true;
        }
        if (killedByFuse)
        {
            ResolveHit();
            return;
        }

        // 8b. Enemy contact.
        if (!player.IsInvulnerable && IsPlayerOrTrailHit(player, activeTrail))
        {
            ResolveHit();
            return;
        }

        if (_level.Trails.CanCompleteOnPath(intendedPosition, _session.PlayableWallPath))
        {
            // 8c. Reconnect to the wall.
            ResolveCapture(_session.PlayableWallPath.Snap(intendedPosition), snappedToPath: true);
        }
        else if (_level.Trails.TryGetSelfIntersection(intendedPosition, out Vector2 loopIntersection))
        {
            // 8d. Cross the own trail.
            ResolveCapture(loopIntersection, snappedToPath: false);
        }
        else if (_level.Trails.CanAdvance(intendedPosition, _level.Arena, direction, player.CurrentDirection))
        {
            // 8e. Advance the trail.
            player.Position = intendedPosition;
            _level.Trails.AppendPoint(player.Position);
            bool wasSlowDraw = _session.SlowDrawActive;
            _level.Trails.UpdateSlowDraw(input.IsSlowDrawHeld);
            if (wasSlowDraw && !_session.SlowDrawActive)
            {
                _events.Add(new SlowDrawLost());
            }

            player.CurrentTrail = _level.Trails.ActiveTrail;

            // Only record the heading when the move was accepted. Recording a
            // blocked reversal would defeat the no-backtrack check next frame.
            player.CurrentDirection = direction;
        }
    }

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

    private void TickOnWall(Direction direction, Vector2 intendedPosition, float speed, float deltaTime, InputState input)
    {
        Player player = _session.Player;

        // 9a. Put out the fuse.
        _level.Fuse.Reset();
        _fuseWarned = false;

        // 9b. Move along the wall.
        if (_movement.TryMoveAlongPath(_session.PlayableWallPath, player.Position, direction, speed, deltaTime, out Vector2 nextOnPath))
        {
            player.Position = nextOnPath;
            player.CurrentDirection = direction;
            return;
        }

        // 9c. Otherwise try to start a trail into open space.
        if (_session.RespawnGraceRemaining <= 0f
            && _session.PlayableWallPath.Contains(player.Position)
            && _level.Arena.IsUnclaimedWorld(intendedPosition)
            && _level.Trails.TryStart(_session.PlayableWallPath.Snap(player.Position), intendedPosition, input.IsSlowDrawHeld))
        {
            player.Position = intendedPosition;
            player.CurrentTrail = _level.Trails.ActiveTrail;
            player.CurrentDirection = direction;
            _events.Add(new TrailStarted(_session.SlowDrawActive));
        }
    }

    private void ResolveHit()
    {
        HitOutcome outcome = _lives.ResolveHit(_session, _level);
        _fuseWarned = false;
        switch (outcome)
        {
            case HitOutcome.Blocked:
                _events.Add(new ShieldBlocked());
                break;
            case HitOutcome.LifeLost:
                _events.Add(new LifeLost(_session.Player.Lives));
                break;
            case HitOutcome.RunOver:
                _events.Add(new LifeLost(_session.Player.Lives));
                _events.Add(new RunLost());
                State = SimulationState.RunLost;
                break;
        }
    }

    // Turns a completed trail into territory, then clears the level when the target is reached.
    private void ResolveCapture(Vector2 endPoint, bool snappedToPath)
    {
        Player player = _session.Player;

        // 1. Complete the trail and put out the fuse.
        Trail completedTrail = _level.Trails.Complete(endPoint);
        player.Position = endPoint;
        player.CurrentTrail = null;
        _level.Fuse.Reset();
        _fuseWarned = false;

        // 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 = _level.Claims.ProcessCompletedTrail(completedTrail, _enemyPositions);

        // 3. Nothing enclosed. A loop endpoint can sit mid-arena, so return the
        // player to the wall anchor where the trail began.
        if (claimResult is null)
        {
            if (!snappedToPath)
            {
                player.Position = completedTrail.Points[0];
            }

            _events.Add(new CaptureRejected());
            return;
        }

        // 4 and 5. Apply the result and update the percentage.
        _level.Arena.ApplyClaimResult(claimResult, completedTrail.IsSlowDraw);
        _session.ClaimedAreaPercentage = _level.Arena.GetClaimedPercentage();

        // 6. Score the region and trail tiles.
        int tiles = claimResult.CapturedRegion.TileCount + claimResult.TrailTiles.Count;
        int points = _scoring.ScoreClaim(tiles, completedTrail.IsSlowDraw);
        _session.Score += points;

        // 7. History.
        _session.CaptureHistory.Add(new CapturedZone(_session.CaptureHistory.Count + 1, claimResult.CapturedRegion.Tiles, completedTrail.IsSlowDraw));

        // 8. Rebuild the wall path and snap the player onto it.
        _session.PlayableWallPath = _level.Walls.RebuildPlayablePath(_level.Arena);
        player.Position = _session.PlayableWallPath.Snap(player.Position);

        // 9. Remove eliminated enemies, highest index first.
        int eliminatedCount = RemoveEliminatedEnemies(claimResult.EliminatedEnemyIndexes);

        // 10. Report the capture.
        _events.Add(new CaptureCompleted(tiles, points, completedTrail.IsSlowDraw, !snappedToPath, eliminatedCount));

        // 11. Clear the level when the target is reached.
        if (_session.ClaimedAreaPercentage >= _level.Config.WinClaimPercentage)
        {
            int bonus = _scoring.CalculateLevelBonus(_session.Level) + _scoring.CalculateThresholdBonus(_session.ClaimedAreaPercentage, _level.Config.WinClaimPercentage);
            _session.Score += bonus;
            State = SimulationState.LevelCleared;
            _events.Add(new LevelCleared(bonus));
        }
    }

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

    private LevelServices BuildLevel(int levelNumber)
    {
        LevelDefinition definition = _levels.CreateLevel(levelNumber, _session.Difficulty);
        _session.Level = levelNumber;
        _session.CurrentLevelDefinition = definition;
        return LevelServices.Create(_baseConfig, definition);
    }

    private void EnterLevel()
    {
        Player player = _session.Player;
        PlayableWallPath path = _level.Walls.RebuildPlayablePath(_level.Arena);
        _session.PlayableWallPath = path;
        _session.CaptureHistory.Clear();
        _session.ClaimedAreaPercentage = _level.Arena.GetClaimedPercentage();
        _session.FreezeEnemiesRemaining = 0f;
        _fuseWarned = false;

        player.Position = SelectStartNode(path);
        player.CurrentDirection = Direction.None;
        player.CurrentTrail = null;
        player.IsInvulnerable = false;
        _session.RespawnGraceRemaining = 0f;
        _session.Enemies.Clear();
        _session.Enemies.AddRange(_enemies.CreateRoster(_level.Definition, _level.Arena.Bounds, _level.Config.EnemySpeed));

        State = SimulationState.Running;
        _events.Clear();
        _events.Add(new LevelStarted(_session.Level));
    }

    // The top-left node: the lowest X, then the lowest Y.
    private static Vector2 SelectStartNode(PlayableWallPath path)
    {
        IReadOnlyList<Vector2> nodes = path.Nodes;
        Vector2 start = nodes[0];
        for (int index = 1; index < nodes.Count; index++)
        {
            Vector2 node = nodes[index];
            if (node.X < start.X || (node.X == start.X && node.Y < start.Y))
            {
                start = node;
            }
        }

        return start;
    }
}

The key changes are:

  • The five per-level fields are gone. _level replaces them, and a Level property exposes it to the scene and the tests. The Config, Trails, Arena and Fuse properties are gone too.
  • Two new fields join the run-long services: _levels for the progression service, and _spawnedClones for the clones that one frame creates.
  • BuildLevel asks _levels for a definition, records it on the session, and returns LevelServices.Create(...). It is the only place a level is built.
  • EnterLevel resets the session for the new level: the wall path, the capture history, the timers, the player and the enemies. It places the roster from CreateRoster, and raises LevelStarted.
  • The constructor calls BuildLevel and EnterLevel for the first level, so a new simulation is ready to run. The host no longer calls StartLevel first.
  • StartLevel(int levelNumber) swaps in a new LevelServices and calls EnterLevel. Score, lives and shields live on the session, so they carry over. The arena, the trail and the fuse live in LevelServices, so they start fresh.
  • Tick now returns at once unless the state is Running. A cleared level stops the rules, and the next level starts them again.
  • UpdateEnemies collects clones in _spawnedClones, then adds them after the loop. Adding to a list while a loop walks it backwards would be a bug.
  • ResolveCapture has a new stage 11. When the claimed percentage reaches the target, it adds the two bonuses to the score, sets the state to LevelCleared and raises LevelCleared.

The project no longer builds, and that is expected. In a terminal, from the LastPerimeter folder, run dotnet build. The build reports errors in GameplayScene.cs and in several test files. Each error names a member that moved into LevelServices. Fix the scene first, then the tests.

Updating the scene ​

The scene must build its renderer from the level's arena, and it must react to the new event. The smoke seed and the capture count from Chapter 13 stay, so the smoke run keeps working. It also needs a second constructor, so the level complete scene can hand it a simulation that already exists. Open Source/Scenes/GameplayScene.cs. At the top of the file, add the following line below the other using lines:

add-using Source/Scenes/GameplayScene.cs
csharp
using LastPerimeter.Systems;

Find the GameplayScene constructor and replace the whole constructor with the following two constructors. The first starts a new run, and it passes the optional smoke seed on to CreateSimulation. The second wraps a simulation that already exists:

replace-method Source/Scenes/GameplayScene.cs GameplayScene
csharp
    public GameplayScene(GameServices services, int? seed = null)
        : this(services, CreateSimulation(services, seed))
    {
    }

    public GameplayScene(GameServices services, GameplaySimulation simulation)
    {
        _services = services;
        _simulation = simulation;
        _hudRenderer = new HudRenderer(services.Text);
        _claimedArea = new ClaimedAreaRenderer(simulation.Level.Arena, services.GraphicsDevice, services.Pixel, Color.RoyalBlue, Color.Orange);
        for (int index = 0; index < simulation.Events.Count; index++)
        {
            React(simulation.Events[index]);
        }
    }

Find the Enter method and replace the whole method with the following. The claimed-area renderer is now created in the constructor, so Enter only updates the window title:

replace-method Source/Scenes/GameplayScene.cs Enter
csharp
    public override void Enter()
    {
        UpdateWindowTitle();
    }

The fuse and the configuration now come from _simulation.Level. In the Draw method of Source/Scenes/GameplayScene.cs, find these lines:

find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
        if (_simulation.Fuse.IsActive)
        {
            PrimitiveDrawing.DrawFilledCircle(spriteBatch, _services.Pixel, _simulation.Fuse.Position, 4f, Color.Red);

Replace them with these lines:

csharp
        if (_simulation.Level.Fuse.IsActive)
        {
            PrimitiveDrawing.DrawFilledCircle(spriteBatch, _services.Pixel, _simulation.Level.Fuse.Position, 4f, Color.Red);

In the same method, find this line:

find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
        _hudRenderer.Draw(spriteBatch, _services.Pixel, session, _services.Config, _status, _simulation.Fuse.IsWarning || _simulation.Fuse.IsActive, _simulation.Fuse.IsActive);

Replace it with this line:

csharp
        _hudRenderer.Draw(spriteBatch, _services.Pixel, session, _simulation.Level.Config, _status, _simulation.Level.Fuse.IsWarning || _simulation.Level.Fuse.IsActive, _simulation.Level.Fuse.IsActive);

In the React method, find these lines. The new LevelCleared case replaces the gameplay scene with the level complete scene:

find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
            case LifeLost:
                _services.Audio.PlayDeath();
                break;

Add these lines directly below them:

csharp
            case LevelCleared cleared:
                Scenes.Change(new LevelCompleteScene(_services, _simulation, cleared.Bonus));
                break;

Add the following method to the GameplayScene class, below the React method. It starts a new run. The starting lives come from the difficulty, and the optional seed is the one the smoke run passes. Chapter 18 moves this into a factory:

add-member Source/Scenes/GameplayScene.cs after=React
csharp
    // A new run. The starting lives come from the difficulty. Chapter 18 moves this into RunFactory.
    private static GameplaySimulation CreateSimulation(GameServices services, int? seed)
    {
        GameSession session = new() { Player = new Player() };
        session.Player.Lives = new LevelProgressionSystem().GetStartingLives(session.Difficulty);
        return new GameplaySimulation(services.Config, session, seed is null ? new Random() : new Random(seed.Value));
    }

The scene replaces itself with Change and does not push the new scene on top. Chapter 17 adds a scene stack, and until then a level change swaps one scene for another.

In the Source/Scenes folder, create a new file named LevelCompleteScene.cs and add the following code. It shows the bonus. When the player presses Enter, it starts the next level and returns to a gameplay scene that wraps the same simulation:

new-file Source/Scenes/LevelCompleteScene.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Game;
using LastPerimeter.Input;
using LastPerimeter.Simulation;

namespace LastPerimeter.Scenes;

// Shows the level bonus. Enter starts the next level and keeps the run. Chapter 18
// inserts the upgrade draft between the two.
public sealed class LevelCompleteScene : Scene
{
    private readonly GameServices _services;
    private readonly GameplaySimulation _simulation;
    private readonly string _bonusLine;

    public LevelCompleteScene(GameServices services, GameplaySimulation simulation, int bonus)
    {
        _services = services;
        _simulation = simulation;
        _bonusLine = $"BONUS {bonus}";
    }

    public override void Update(float deltaTime, InputState input)
    {
        if (!input.IsConfirmPressed)
        {
            return;
        }

        _simulation.StartLevel(_simulation.Session.Level + 1);
        Scenes.Change(new GameplayScene(_services, _simulation));
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        DrawCentered(spriteBatch, "LEVEL COMPLETE", 160, 4, Color.White);
        DrawCentered(spriteBatch, _bonusLine, 240, 2, Color.Gold);
        DrawCentered(spriteBatch, "PRESS ENTER FOR THE NEXT LEVEL", 300, 2, Color.LightGray);
    }

    private void DrawCentered(SpriteBatch spriteBatch, string text, int y, int scale, Color color)
    {
        Vector2 size = _services.Text.MeasureString(text, scale);
        _services.Text.DrawString(spriteBatch, _services.Pixel, text, new Vector2((_services.Config.ScreenWidth - size.X) / 2f, y), color, scale);
    }
}

The game project is complete now. In a terminal, from the LastPerimeter folder, run dotnet build Platforms/DesktopVK. This builds the game and not the tests, and it succeeds with no errors. This is a checkpoint. Do not run dotnet test yet, because the test project still refers to the old members.

Updating the tests ​

The test helper builds simulations, so it changes first. The simulation now enters its first level in its constructor, so the helper no longer calls StartLevel. Create also takes a level number.

Open Tests/TestHelpers/SimulationBuilder.cs. In the comment above the SimulationBuilder class, find this line:

find Tests/TestHelpers/SimulationBuilder.cs
csharp
// Builds a small arena (80 by 80, 4 pixel tiles) with a player on the top-left node of the wall.

Replace it with this line:

csharp
// Builds a small arena (80 by 80, 4 pixel tiles) with a player at the top-left node.

In the Create method, find this line:

find Tests/TestHelpers/SimulationBuilder.cs type=SimulationBuilder
csharp
    public static GameplaySimulation Create(int seed = 1, bool withEnemies = false, int margin = 0)

Replace it with this line:

csharp
    public static GameplaySimulation Create(int seed = 1, bool withEnemies = false, int margin = 0, int level = 1)

In the same Create method, find these lines:

find Tests/TestHelpers/SimulationBuilder.cs type=SimulationBuilder
csharp
        GameSession session = new() { Player = new Player() };
        GameplaySimulation simulation = new(config, session, new Random(seed));
        simulation.StartLevel();

Replace them with these lines:

csharp
        GameSession session = new()
        {
            Player = new Player(),
            PlayableWallPath = new PlayableWallPath([]),
            CaptureHistory = [],
            Enemies = [],
            Level = level,
        };
        GameplaySimulation simulation = new(config, session, new Random(seed));

Every other test change is the same edit. A test that read sim.Arena, sim.Fuse, sim.Trails or sim.Config now reads it through sim.Level. A test that checked Player.CurrentTrail for null now asks the trail service, because the service is the source of truth for whether a trail is active. Seventeen test methods change. Each step below names the file and the method, and shows only the changed lines.

Open Tests/Simulation/CaptureScenarioTests.cs. In the Tick_ClosingATrail_ClaimsTheSmallerSide method, find these lines:

find Tests/Simulation/CaptureScenarioTests.cs type=CaptureScenarioTests
csharp
        Assert.True(sim.Arena.IsClaimedWorld(new Vector2(30, 20)));
        Assert.False(sim.Arena.IsClaimedWorld(new Vector2(60, 60)));

Replace them with these lines:

csharp
        Assert.True(sim.Level.Arena.IsClaimedWorld(new Vector2(30, 20)));
        Assert.False(sim.Level.Arena.IsClaimedWorld(new Vector2(60, 60)));

In the RejectedLoop_ReturnsPlayerToAnchor method, find this line:

find Tests/Simulation/CaptureScenarioTests.cs type=CaptureScenarioTests
csharp
        Assert.Null(sim.Session.Player.CurrentTrail);

Replace it with this line:

csharp
        Assert.False(sim.Level.Trails.HasActiveTrail);

Open Tests/Simulation/EnemyScenarioTests.cs. In the Tick_EnemyTouchingTrail_CancelsTheTrail method, find this line:

find Tests/Simulation/EnemyScenarioTests.cs type=EnemyScenarioTests
csharp
        Assert.Null(sim.Session.Player.CurrentTrail);

Replace it with this line:

csharp
        Assert.False(sim.Level.Trails.HasActiveTrail);

Open Tests/Simulation/FuseScenarioTests.cs. In the Tick_HoldingBlockedDirection_LetsFuseBurn method, find this line:

find Tests/Simulation/FuseScenarioTests.cs type=FuseScenarioTests
csharp
        Assert.True(sim.Fuse.IsActive);

Replace it with this line:

csharp
        Assert.True(sim.Level.Fuse.IsActive);

In the Tick_FuseReachingPlayer_CancelsTheTrail method, find these lines:

find Tests/Simulation/FuseScenarioTests.cs type=FuseScenarioTests
csharp
        Assert.Null(sim.Session.Player.CurrentTrail);
        Assert.False(sim.Fuse.IsActive);

Replace them with these lines:

csharp
        Assert.False(sim.Level.Trails.HasActiveTrail);
        Assert.Null(sim.Session.Player.CurrentTrail);
        Assert.False(sim.Level.Fuse.IsActive);

Open Tests/Simulation/GraceScenarioTests.cs. In the Tick_DoesNotStartTrailDuringGrace method, find this line:

find Tests/Simulation/GraceScenarioTests.cs type=GraceScenarioTests
csharp
        Assert.Null(sim.Session.Player.CurrentTrail);

Replace it with this line:

csharp
        Assert.False(sim.Level.Trails.HasActiveTrail);

Open Tests/Simulation/LevelScenarioTests.cs. In the Scenario_StopMidTrail_FuseCostsALife method, find this line:

find Tests/Simulation/LevelScenarioTests.cs type=LevelScenarioTests
csharp
        Assert.Null(sim.Session.Player.CurrentTrail);

Replace it with this line:

csharp
        Assert.False(sim.Level.Trails.HasActiveTrail);

In the Scenario_TwoCapturesInARow_KeepWallConsistent method, find this line:

find Tests/Simulation/LevelScenarioTests.cs type=LevelScenarioTests
csharp
        Assert.All(path.Nodes, node => Assert.True(sim.Arena.IsWithinBounds(node)));

Replace it with this line:

csharp
        Assert.All(path.Nodes, node => Assert.True(sim.Level.Arena.IsWithinBounds(node)));

In the Scenario_LoopCapture_ClaimsInsideOfLoop method, find these lines:

find Tests/Simulation/LevelScenarioTests.cs type=LevelScenarioTests
csharp
        Assert.True(sim.Arena.IsClaimedWorld(new Vector2(30, 30)));
        Assert.False(sim.Arena.IsClaimedWorld(new Vector2(30, 10)));

Replace them with these lines:

csharp
        Assert.True(sim.Level.Arena.IsClaimedWorld(new Vector2(30, 30)));
        Assert.False(sim.Level.Arena.IsClaimedWorld(new Vector2(30, 10)));

Open Tests/Simulation/LevelStartScenarioTests.cs. In the StartLevel_PlacesPlayerOnTopLeftNode method, find this line:

find Tests/Simulation/LevelStartScenarioTests.cs type=LevelStartScenarioTests
csharp
        sim.StartLevel();

Replace it with this line. StartLevel now takes a level number:

csharp
        sim.StartLevel(2);

Open Tests/Simulation/TrailScenarioTests.cs. In the Tick_DrawingOutAndBackToWall_CompletesTheTrail method, find this line:

find Tests/Simulation/TrailScenarioTests.cs type=TrailScenarioTests
csharp
        Assert.Contains(events, e => e is TrailStarted { SlowDraw: false });

Add this line directly below it:

csharp
        Assert.False(sim.Level.Trails.HasActiveTrail);

Open Tests/Systems/LivesSystemTests.cs. In the DrawingSimulation method, find these lines:

find Tests/Systems/LivesSystemTests.cs type=LivesSystemTests
csharp
        ScriptedInput.Run(sim, ScriptedInput.Down, 3);
        Assert.NotNull(sim.Session.Player.CurrentTrail);

Replace them with these lines:

csharp
        ScriptedInput.Run(sim, ScriptedInput.Down, 3);
        Assert.True(sim.Level.Trails.HasActiveTrail);

In the TryBlockWithShield_SpendsOneChargeInsteadOfALife method, find these lines:

find Tests/Systems/LivesSystemTests.cs type=LivesSystemTests
csharp
        Assert.False(lives.TryBlockWithShield(sim.Session, sim.Trails, sim.Fuse, sim.Config.RespawnGraceSeconds));
        Assert.Equal(0f, sim.Session.RespawnGraceRemaining);
        Assert.NotNull(sim.Session.Player.CurrentTrail);

        sim.Session.ShieldCharges = 2;
        Assert.True(lives.TryBlockWithShield(sim.Session, sim.Trails, sim.Fuse, sim.Config.RespawnGraceSeconds));

Replace them with these lines:

csharp
        Assert.False(lives.TryBlockWithShield(sim.Session, sim.Level));
        Assert.Equal(0f, sim.Session.RespawnGraceRemaining);
        Assert.True(sim.Level.Trails.HasActiveTrail);

        sim.Session.ShieldCharges = 2;
        Assert.True(lives.TryBlockWithShield(sim.Session, sim.Level));

In the ShieldBlock_ReturnsPlayerToWallWithGrace method, find these lines:

find Tests/Systems/LivesSystemTests.cs type=LivesSystemTests
csharp
        HitOutcome outcome = new LivesSystem().ResolveHit(sim.Session, sim.Trails, sim.Fuse, sim.Config.RespawnGraceSeconds);

        Assert.Equal(HitOutcome.Blocked, outcome);
        Assert.True(sim.Session.PlayableWallPath.Contains(sim.Session.Player.Position));
        Assert.Equal(sim.Config.RespawnGraceSeconds, sim.Session.RespawnGraceRemaining);

Replace them with these lines:

csharp
        HitOutcome outcome = new LivesSystem().ResolveHit(sim.Session, sim.Level);

        Assert.Equal(HitOutcome.Blocked, outcome);
        Assert.True(sim.Session.PlayableWallPath.Contains(sim.Session.Player.Position));
        Assert.Equal(sim.Level.Config.RespawnGraceSeconds, sim.Session.RespawnGraceRemaining);

In the LoseLife_CancelsTrailAndFuse method, find these lines:

find Tests/Systems/LivesSystemTests.cs type=LivesSystemTests
csharp
        Assert.True(sim.Fuse.IsWarning || sim.Fuse.IsActive);

        int left = new LivesSystem().LoseLife(sim.Session, sim.Trails, sim.Fuse);

        Assert.Equal(2, left);
        Assert.Null(sim.Session.Player.CurrentTrail);
        Assert.False(sim.Fuse.IsActive);
        Assert.False(sim.Fuse.IsWarning);

Replace them with these lines:

csharp
        Assert.True(sim.Level.Fuse.IsWarning || sim.Level.Fuse.IsActive);

        int left = new LivesSystem().LoseLife(sim.Session, sim.Level);

        Assert.Equal(2, left);
        Assert.False(sim.Level.Trails.HasActiveTrail);
        Assert.False(sim.Level.Fuse.IsActive);
        Assert.False(sim.Level.Fuse.IsWarning);

In the LoseLife_OnLastLife_EndsTheRun method, find these lines:

find Tests/Systems/LivesSystemTests.cs type=LivesSystemTests
csharp
        HitOutcome outcome = lives.ResolveHit(sim.Session, sim.Trails, sim.Fuse, sim.Config.RespawnGraceSeconds);

        Assert.Equal(HitOutcome.RunOver, outcome);
        Assert.Equal(0, sim.Session.Player.Lives);
        Assert.Equal(0, lives.LoseLife(sim.Session, sim.Trails, sim.Fuse));

Replace them with these lines:

csharp
        HitOutcome outcome = lives.ResolveHit(sim.Session, sim.Level);

        Assert.Equal(HitOutcome.RunOver, outcome);
        Assert.Equal(0, sim.Session.Player.Lives);
        Assert.Equal(0, lives.LoseLife(sim.Session, sim.Level));

In the Respawn_StartsGraceFromConfig method, find these lines:

find Tests/Systems/LivesSystemTests.cs type=LivesSystemTests
csharp
        new LivesSystem().Respawn(sim.Session, sim.Config.RespawnGraceSeconds);

        Assert.True(sim.Config.RespawnGraceSeconds > 0f);
        Assert.Equal(sim.Config.RespawnGraceSeconds, sim.Session.RespawnGraceRemaining);

Replace them with these lines:

csharp
        new LivesSystem().Respawn(sim.Session, sim.Level);

        Assert.True(sim.Level.Config.RespawnGraceSeconds > 0f);
        Assert.Equal(sim.Level.Config.RespawnGraceSeconds, sim.Session.RespawnGraceRemaining);

In a terminal, from the LastPerimeter folder, run dotnet test. The build now succeeds. The summary line should report Failed: 0 and Passed: 101. The scenario test from earlier, CaptureReachingTarget_ClearsTheLevel, passes at last.

The last test checks the reset. Open Tests/Simulation/LevelScenarioTests.cs. Add the following test to the end of the LevelScenarioTests class. It draws a capture, sets the shields and lives, starts level 2 and checks what stayed and what reset:

add-member Tests/Simulation/LevelScenarioTests.cs at=end
csharp
    [Fact]
    public void StartLevel_ResetsTheArenaButKeepsTheRun()
    {
        GameplaySimulation sim = SimulationBuilder.Create();
        ScriptedInput.DrawRectangleFromTopWall(sim);
        sim.Session.ShieldCharges = 2;
        sim.Session.Player.Lives = 2;
        int score = sim.Session.Score;

        IReadOnlyList<GameEvent> events = sim.StartLevel(2);

        Assert.Equal(0, sim.Level.Arena.ClaimedTileCount);
        Assert.Empty(sim.Session.CaptureHistory);
        Assert.Equal(2, sim.Session.Level);
        Assert.Equal(score, sim.Session.Score);
        Assert.Equal(2, sim.Session.Player.Lives);
        Assert.Equal(2, sim.Session.ShieldCharges);
        Assert.Equal(SimulationState.Running, sim.State);
        Assert.Contains(events, e => e is LevelStarted { Level: 2 });
    }

This test passes the first time, because StartLevel and EnterLevel already behave this way. It is a regression test. It pins the rule down so that a later chapter cannot break it without a failure.

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 102.

Running the tests ​

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 102. The 102 are the 85 from earlier chapters and 17 new results. Fourteen of the new results are single tests, and 3 are the rows of one theory.

TestProves
CreateLevel_ScalesEnemyRosterAndGoalLVL-02, LVL-03, LVL-04, LVL-06
CreateLevel_AppliesDifficultyPresetAdjustmentsLVL-07
CreateLevel_AddsInsetFromLevelSixLVL-05
GetStartingLives_DependsOnDifficulty (3 rows)LIV-01
ApplyInsetClaim_ClaimsOnlyTheBorderRingARN-08
CreateRoster_SpreadsEnemiesAcrossTheArenaENM-01
TrySpawnSplitterClone_WaitsForTheSplitTimer_ThenRearmsItENM-07
SpawnedClone_IsASmallerSlowerTemporaryHunterENM-07
ClonesOtherVariantsAndFrozenSplitters_NeverSplitENM-08
Update_TemporaryClone_ExpiresWhenLifetimeRunsOutENM-08
Update_SplitterCloneOnClaimedGround_RecoversToFreeGroundENM-09
CalculateThresholdBonus_AwardsPointsPerPercentAboveTargetSCO-06
CalculateLevelBonus_GrowsWithLevelSCO-05
CaptureReachingTarget_ClearsTheLevelLVL-01
StartLevel_ResetsTheArenaButKeepsTheRunLVL-08

Running the game ​

From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen. The arena is empty and one Wanderer moves in it. The status line reads LEVEL 1. Walk the wall with the arrow keys, draw rectangles and capture 75 percent of the arena. The screen changes to LEVEL COMPLETE with a BONUS line, as in Figure 14-1. Press Enter. Level 2 starts with your score kept and the arena empty again.

The LEVEL COMPLETE screen, the colours and the movement need a window. The test counts and the exit code of the smoke run below confirm the rules without one.

The smoke run from Chapter 13: Proving the Level still works. From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK -- --smoke-test-seconds 3, and then check the exit code as you did in Chapter 13. It must be 0. The script plays level 1 through the new LevelServices, so a 0 shows that a capture still completes after this chapter's rewiring.

Reaching 75 percent by hand takes a while. The next tip lets you see level 6 and its inset in a minute.

TIP

Open Source/Systems/LevelProgressionSystem.cs and change 75f in the requiredClaim line of CreateLevel to 5f. Every level then needs only a few percent. Run the game and clear levels with one capture each. At level 6 you can see the claimed ring round the arena. At level 7 a third enemy appears, and after 6 seconds it spawns a clone. Change 5f back to 75f and run dotnet test before you go on.

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 14 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/14-Levels-And-Difficulty"
Remove-Item -Recurse -Force Source, Tests
Copy-Item -Recurse "$snapshot/Source" Source
Copy-Item -Recurse "$snapshot/Tests" Tests

In 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/14-Levels-And-Difficulty"
rm -rf Source Tests
cp -r "$snapshot/Source" Source
cp -r "$snapshot/Tests" Tests

Then run dotnet test from the LastPerimeter folder and check for Passed: 102.

Common mistakes ​

  • The build reports sim.Arena or sim.Fuse not found in a test. You skipped one of the 17 test methods. The error names the file and the line. Make the edit that this chapter shows for that method.
  • A NotImplementedException in the final test run. A stub is still in LevelProgressionSystem.cs, ArenaSystem.cs, EnemySystem.cs or ScoringSystem.cs. Search the file for throw new NotImplementedException(); and replace that method.
  • CreateLevel_AddsInsetFromLevelSix fails with 0 at level 6. You kept the first-round CreateLevel body. Replace it with the final listing.
  • Level 1 is cleared by a tiny capture. You left the 5f from the tip in CreateLevel. Change it back to 75f.
  • The window shows LEVEL COMPLETE, but pressing Enter does nothing. LevelCompleteScene reads input.IsConfirmPressed. Check that you typed it exactly, and that the scene calls Scenes.Change.

Conclusion ​

In this chapter, you accomplished the following:

The tests now prove LVL-01 to LVL-08, LIV-01, ARN-08, ENM-01, ENM-07, ENM-08, ENM-09, SCO-05 and SCO-06. In the next chapter, Chapter 15: Powerups, you add pickups on the wall that change one piece of state each.

Test Your Knowledge ​

  1. At which level does the Splitter first appear, and in which roster slot?

    Answer

    At level 7, in the third slot. The schedule gives slot 3 a Splitter from level 7. Before that, slot 3 is a Wanderer, or the slot does not exist yet.

  2. What could go wrong if the simulation kept the arena, the claim solver and the fuse as separate fields, and why does LevelServices avoid it?

    Answer

    A new level might replace the arena and forget the solver. The solver would then claim tiles on the old arena, and nothing would fail at once. LevelServices.Create builds every part in one call, and the simulation swaps the whole object, so a frame never sees a mixture.

  3. A player claims 81.2 percent on level 2, where the target is 76 percent. What is the total bonus?

    Answer

    The level bonus is 1,000 + 500 x 2, which is 2,000. The overshoot is 5.2, which drops to 5 whole percent, and that gives 5,000. The total is 7,000.

  4. GetStartingLives_DependsOnDifficulty has three [InlineData] rows. How many tests does the runner report, and what does that tell you when one fails?

    Answer

    It reports three tests, one for each row. A failure names the row, so you can see which preset returned the wrong number of lives.

Extensions ​

  • Add a fourth preset to DifficultyPreset. What does GetStartingLives return for it, and which test would you add first?
  • Change the Splitter's first delay to 3 seconds in EnemySystem. Which tests fail, and why does the spawn test in EnemySplitterTests use the constant and not the number 6?