Skip to content

Chapter 18: Runs and Upgrades ​

In Chapter 17: Menus and the Front End, you built the title screen, the main menu, the level select list and the options. Starting a run still happens inside GameplayScene.StartRun, and clearing a level goes straight to the next one. Nothing yet turns a string of levels into a run with a shape.

In this chapter, you turn the levels into a run. A run has a mode and a seed, starts from one factory, offers a draft of three upgrades after each level, and ends with a summary.

Figure 18-1: The upgrade screen that opens after a level is cleared
Figure 18-1: The upgrade screen that opens after a level is cleared. This is a drawn illustration, not a screenshot.

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

In this chapter, you will:

  • Learn the three layers of progression: within a level, within a run and across runs.
  • Build RunModifiers and GameSession.ApplyUpgrade, and see why the extra life is the odd one out.
  • Build RunUpgradeDraft, a repeatable draft of three distinct cards.
  • Build RunFactory, the one place a run is created, and route every menu through it.
  • Feed the modifiers into LevelServices.Create and the tick, so speed, fuse, score and grace all change.
  • Add the upgrade scene and the run summary scene.

Requirements in this chapter ​

IDShort name
RUN-01Run modes (Classic and Level Select here, Daily in Chapter 19)
RUN-02The draft offers three distinct upgrades
RUN-03The draft is repeatable for one seed and level
RUN-04The four modifier upgrades stack
RUN-05Extra Life adds a life and is recorded
RUN-09The run summary
MOV-06Run speed multiplier
FUS-02Cool Fuse adds to the fuse delay
LIV-07Safe Return adds to the grace time
SCO-03Double Down adds to the score multiplier
FE-08Level complete, then the draft, then the next level
FE-09Quit To Menu records the run

Three layers of progression ​

The game keeps three kinds of state, and each one has its own lifetime. Figure 18-2 shows them nested.

Figure 18-2: Three progression layers with three lifetimes
Figure 18-2: Three progression layers with three lifetimes

The innermost layer is the level. LevelServices holds the arena, the wall rebuild, the claim solver, the trail and the fuse, and StartLevel builds a new one for each level. Nothing in it survives a level, so nothing can leak from level 3 into level 4.

The middle layer is the run. GameSession holds the score, the lives, the upgrades the player has chosen and the seed. It lives from the first level until the player loses the last life or quits. The outer layer is the profile, which Chapter 16 saves to profile.json. It holds the high score and the unlocked levels, and it outlives every run.

This chapter builds the middle layer. The rule to hold on to is that each piece of state lives in the narrowest layer that needs it. An upgrade lasts for the run, so it belongs in GameSession. It must not be written to the profile, and it must not be stored in LevelServices, which is thrown away after each level.

The table below lists each piece of state, how long it lives, which operation resets it and which operation saves it. Only the profile is ever saved to disk. Everything else is rebuilt when the next level or run starts.

StateLives forReset bySaved by
Tile grid (ArenaSystem)One levelGameplaySimulation.StartLevel builds a new LevelServicesNever saved
Wall pathOne levelEnterLevel rebuilds it from the new arenaNever saved
TrailOne level, and also cleared on a deathEnterLevel, and LivesSystem when a life is lostNever saved
EnemiesOne levelEnterLevel clears the list and builds a new rosterNever saved
Powerups and their timersOne levelEnterLevel clears the list and the freeze and double points timersNever saved
Fuse and grace timersOne levelA new LevelServices and EnterLevelNever saved
Score, lives and shieldsOne runRunFactory.Create builds a new GameSessionNever saved. RecordRunFinished copies the score into the profile
Upgrades and the seedOne runRunFactory.CreateNever saved
Profile, settings and statisticsAcross runsOnly the player, through the options and the profile fileProfileTracker.SaveIfDirty, called between screens

Modifiers as data ​

Upgrades change numbers that earlier chapters already read. Quickstep raises the player speed that Tick uses. Cool Fuse lengthens the delay that FuseSystem waits. Double Down raises the multiplier that scoring uses. Safe Return lengthens the grace time after a respawn.

The design is to store those numbers in one small object, RunModifiers, with a neutral starting value for each. A multiplier starts at 1 and a bonus starts at 0, so a run with no upgrades behaves exactly as it did before this chapter. Picking an upgrade adds to one field. No rule needs rewriting, because each rule reads the number it always read, now multiplied or added to.

Picks stack. Two Quickstep cards give 1 plus 0.15 plus 0.15, which is 1.30. The upgrades add and do not multiply, so the order of the picks does not matter.

The odd one out ​

Four of the five upgrades are numbers. The fifth, Extra Life, is not. A life belongs to the player, and Player.Lives is already a number the lives system reads. Adding a life field to RunModifiers would give the game two places that count lives.

So RunModifiers.Apply does nothing for BonusLife, and a different method, GameSession.ApplyUpgrade, owns the whole rule. It applies the modifier, records the choice in ChosenUpgrades, and adds the life when the upgrade is Extra Life. Every caller uses ApplyUpgrade, so the rule is written once. A test proves both halves: Apply leaves the modifiers alone, and ApplyUpgrade adds the life.

Repeatable drafts ​

After each level the player picks one of three cards. The draft shuffles the five upgrades with a Random and takes the first three. If that Random were seeded by the clock, the offer would change every time the code ran, so a player who restarted the scene could re-roll for a better draft.

The draft therefore seeds its Random from the run seed and the level number. The same level of the same run always offers the same three cards. Different levels offer different cards, because the level number changes the seed. The seed is seed + (level * 31). The multiplier 31 is arbitrary. It only has to keep neighbouring levels from producing neighbouring seeds.

One factory ​

Before this chapter, GameplayScene.StartRun built the session by hand. The main menu and the level select both called it, and Chapter 19 adds a third way to start a run. If each way built its own session, a new mode would need the same lines copied again, and the copies would drift.

RunFactory.Create is the one place a run is built. It takes the mode, the starting level, the player settings, today's date and an optional seed. It gives back a ready GameplaySimulation. A new mode is then one extra branch in one method. The date parameter exists from this chapter and is unused until Chapter 19.

Two design choices live in the factory. A Classic run takes a fresh random seed, so its drafts differ from one run to the next. The seed is stored on the session, so a run can be replayed later. And the difficulty is copied from the settings into the session when the run starts. A change made in the options screen during a run therefore applies to the next run, which keeps a run fair from its first level to its last.

The flow of a run ​

Figure 18-3 shows how the scenes hand over during a run. You build the two new scenes and the changes to the existing ones in this chapter.

Figure 18-3: How the scenes hand over during a run. Both ways of ending a run record it on the profile.

Setting up the data ​

The run needs two enums and one small record. You add the enums to the file that already holds the others. The upgrade kind goes below PowerupType, because both lists describe things the player collects.

Open Source/Data/Enums.cs. Add the following enum below the PowerupType enum:

add-type Source/Data/Enums.cs after=PowerupType
csharp
public enum RunUpgradeKind
{
    FasterMovement,
    SlowerFuse,
    HigherScoring,
    SaferRespawn,
    BonusLife,
}

Add the following enum at the end of the same file, below the ThemePreset enum. RunMode is new in this chapter. It includes the DailyChallenge value now, so the enum never needs a second change when Chapter 19 starts to use it.

add-type Source/Data/Enums.cs
csharp
public enum RunMode
{
    Classic,
    DailyChallenge,
    LevelSelect,
}

In the Source/Data folder, create a new file named RunUpgradeChoice.cs and add the following code. A choice is one card in the draft: the kind, the name shown on screen and a one-line description. It is a record, so two choices with the same values are equal. New to records? See the C# primer.

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

public sealed record RunUpgradeChoice(RunUpgradeKind Upgrade, string Name, string Description);

Building the modifiers ​

RunModifiers holds the four numbers from the concept section above. It has one operation, Apply, which adds the effect of one upgrade.

RunModifiers.Apply(upgrade) : void

  • Takes: the kind of upgrade.
  • Gives: nothing. The modifiers change.
  • Promises: each upgrade adds its effect to one field, and repeated picks stack. Quickstep adds 0.15 to the speed multiplier. Cool Fuse adds 0.5 seconds to the fuse delay. Double Down adds 0.25 to the score multiplier. Safe Return adds 0.5 seconds to the grace time.
  • Refuses: nothing. BonusLife changes no field here, because GameSession.ApplyUpgrade owns the extra life.
  • Requirements: RUN-04, RUN-05.

In the Source/Data folder, create a new file named RunModifiers.cs and add the following code. The four properties are written in full, with their neutral values. Apply is a stub.

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

public sealed class RunModifiers
{
    public float MoveSpeedMultiplier { get; set; } = 1f;
    public float FuseDelayBonusSeconds { get; set; }
    public float ScoreMultiplier { get; set; } = 1f;
    public float RespawnGraceBonusSeconds { get; set; }

    // BonusLife changes the player, not a modifier. GameSession.ApplyUpgrade handles it.
    public void Apply(RunUpgradeKind upgrade)
    {
        throw new NotImplementedException();
    }
}

The tests for Apply live in the Tests/Systems folder, which exists from Chapter 03. In that folder, create a new file named RunModifiersTests.cs and add the following code. It starts with one test, which checks that a single Quickstep gives a speed multiplier of 1.15.

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

namespace LastPerimeter.Tests.Systems;

public sealed class RunModifiersTests
{
    [Fact]
    public void Apply_FasterMovement_IncreasesMoveSpeedMultiplier()
    {
        RunModifiers modifiers = new();

        modifiers.Apply(RunUpgradeKind.FasterMovement);

        Assert.Equal(1.15f, modifiers.MoveSpeedMultiplier, precision: 3);
    }
}

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

Open Tests/Systems/RunModifiersTests.cs. Add the following four tests to the RunModifiersTests class, below the Apply_FasterMovement_IncreasesMoveSpeedMultiplier test. They cover the other three number upgrades and the stacking promise.

add-member Tests/Systems/RunModifiersTests.cs after=Apply_FasterMovement_IncreasesMoveSpeedMultiplier
csharp
    [Fact]
    public void Apply_SlowerFuse_AddsFuseDelayBonus()
    {
        RunModifiers modifiers = new();

        modifiers.Apply(RunUpgradeKind.SlowerFuse);

        Assert.Equal(0.5f, modifiers.FuseDelayBonusSeconds, precision: 3);
    }

    [Fact]
    public void Apply_HigherScoring_IncreasesScoreMultiplier()
    {
        RunModifiers modifiers = new();

        modifiers.Apply(RunUpgradeKind.HigherScoring);

        Assert.Equal(1.25f, modifiers.ScoreMultiplier, precision: 3);
    }

    [Fact]
    public void Apply_SaferRespawn_AddsRespawnGraceBonus()
    {
        RunModifiers modifiers = new();

        modifiers.Apply(RunUpgradeKind.SaferRespawn);

        Assert.Equal(0.5f, modifiers.RespawnGraceBonusSeconds, precision: 3);
    }

    [Fact]
    public void Apply_StacksAcrossRepeatedPicks()
    {
        RunModifiers modifiers = new();

        modifiers.Apply(RunUpgradeKind.FasterMovement);
        modifiers.Apply(RunUpgradeKind.FasterMovement);
        modifiers.Apply(RunUpgradeKind.HigherScoring);

        Assert.Equal(1.3f, modifiers.MoveSpeedMultiplier, precision: 3);
        Assert.Equal(1.25f, modifiers.ScoreMultiplier, precision: 3);
    }

Add the following test below the Apply_StacksAcrossRepeatedPicks test. It checks the refusal on the card: applying BonusLife leaves all four numbers at their starting values.

add-member Tests/Systems/RunModifiersTests.cs after=Apply_StacksAcrossRepeatedPicks
csharp
    [Fact]
    public void Apply_BonusLife_LeavesModifierAggregateUnchanged()
    {
        RunModifiers modifiers = new();

        modifiers.Apply(RunUpgradeKind.BonusLife);

        Assert.Equal(1f, modifiers.MoveSpeedMultiplier, precision: 3);
        Assert.Equal(0f, modifiers.FuseDelayBonusSeconds, precision: 3);
        Assert.Equal(1f, modifiers.ScoreMultiplier, precision: 3);
        Assert.Equal(0f, modifiers.RespawnGraceBonusSeconds, precision: 3);
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 6 and Passed: 140. Every new test fails, because every new test calls the stub.

Open Source/Data/RunModifiers.cs, find the Apply method and replace the whole method with the following:

replace-method Source/Data/RunModifiers.cs Apply
csharp
    // BonusLife changes the player, not a modifier. GameSession.ApplyUpgrade handles it.
    public void Apply(RunUpgradeKind upgrade)
    {
        switch (upgrade)
        {
            case RunUpgradeKind.FasterMovement:
                MoveSpeedMultiplier += 0.15f;
                break;
            case RunUpgradeKind.SlowerFuse:
                FuseDelayBonusSeconds += 0.5f;
                break;
            case RunUpgradeKind.HigherScoring:
                ScoreMultiplier += 0.25f;
                break;
            case RunUpgradeKind.SaferRespawn:
                RespawnGraceBonusSeconds += 0.5f;
                break;
        }
    }

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

The key things to note are:

  • The switch has a case for each of the four number upgrades and no case for BonusLife. A switch statement with no match does nothing, and that is the refusal on the card.
  • Every case uses +=, so a second pick adds to the first. Two Quickstep picks give 1.30, which Apply_StacksAcrossRepeatedPicks checks.
  • The tests use precision: 3 because 0.15f is not exact in binary floating point. The comparison allows a difference smaller than 0.0005.
  • The comment above Apply names the odd one out, so the next reader does not mistake the missing case for a bug.

Building the upgrade draft ​

RunUpgradeDraft is a static class with one operation. It is a plain function of its two inputs, with no state, so it needs no constructor.

RunUpgradeDraft.CreateChoices(level, seed) : RunUpgradeChoice[]

  • Takes: the level just cleared and the run seed.
  • Gives: an array of three cards.
  • Promises: the three kinds are different. The same level and seed always give the same cards, in the same order.
  • Refuses: nothing. Any level and seed give a draft.
  • Requirements: RUN-02, RUN-03.

In the Source/Systems folder, create a new file named RunUpgradeDraft.cs and add the following code. It is the whole class, with the operation as a stub.

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

namespace LastPerimeter.Systems;

public static class RunUpgradeDraft
{
    // Three distinct cards. The same seed and level always give the same cards.
    public static RunUpgradeChoice[] CreateChoices(int level, int seed)
    {
        throw new NotImplementedException();
    }
}

In the Tests/Systems folder, create a new file named RunUpgradeDraftTests.cs and add the following code. The first test checks the three distinct cards. The second calls the draft twice with one level and one seed, and compares the kinds.

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

namespace LastPerimeter.Tests.Systems;

public sealed class RunUpgradeDraftTests
{
    [Fact]
    public void CreateUpgradeChoices_ReturnsThreeDistinctOptions()
    {
        RunUpgradeChoice[] upgrades = RunUpgradeDraft.CreateChoices(4, 12345);

        Assert.Equal(3, upgrades.Length);
        Assert.Equal(3, upgrades.Select(choice => choice.Upgrade).Distinct().Count());
    }

    [Fact]
    public void CreateChoices_WithSameSeed_IsRepeatable()
    {
        RunUpgradeChoice[] first = RunUpgradeDraft.CreateChoices(3, 777);
        RunUpgradeChoice[] second = RunUpgradeDraft.CreateChoices(3, 777);

        Assert.Equal(first.Select(choice => choice.Upgrade), second.Select(choice => choice.Upgrade));
    }
}

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

Open Source/Systems/RunUpgradeDraft.cs, find the CreateChoices method and replace the whole method with the following:

replace-method Source/Systems/RunUpgradeDraft.cs CreateChoices
csharp
    // Three distinct cards. The same seed and level always give the same cards.
    public static RunUpgradeChoice[] CreateChoices(int level, int seed)
    {
        Random random = new(seed + (level * 31));
        List<RunUpgradeChoice> allChoices =
        [
            new(RunUpgradeKind.FasterMovement, "QUICKSTEP", "+15% wall and draw speed"),
            new(RunUpgradeKind.SlowerFuse, "COOL FUSE", "+0.5s before the fuse ignites"),
            new(RunUpgradeKind.HigherScoring, "DOUBLE DOWN", "+25% scoring on all claims"),
            new(RunUpgradeKind.SaferRespawn, "SAFE RETURN", "+0.5s respawn grace"),
            new(RunUpgradeKind.BonusLife, "EXTRA LIFE", "Gain one additional life immediately"),
        ];

        return allChoices
            .OrderBy(_ => random.Next())
            .Take(3)
            .ToArray();
    }

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

The key things to note are:

  • The Random is built from seed + (level * 31). This is the line that makes the draft repeatable, and the line that makes each level differ.
  • OrderBy(_ => random.Next()) gives every card a random key and sorts by it. That is a shuffle, and Take(3) keeps the first three. A shuffle cannot return one card twice, so the three are distinct.
  • The cards are listed in a fixed order before the shuffle. The same seed gives the same keys in the same order, so the same cards come out.
  • CreateChoices reads no clock and no static Random. Everything it needs is in its two arguments. Chapter 19 builds on this habit.

Adding the run members to the session ​

GameSession needs to hold the modifiers, the chosen upgrades, the pending cards, the mode and the seed. It also needs the operation that applies an upgrade. The new members are required, so the compiler insists that every new session sets them. New to required? See the C# primer.

GameSession.ApplyUpgrade(upgrade) : void

  • Takes: the kind of upgrade.
  • Gives: nothing. The session changes.
  • Promises: the modifiers are updated through RunModifiers.Apply, the choice is appended to ChosenUpgrades, and BonusLife adds one to Player.Lives.
  • Refuses: nothing. Every kind of upgrade is accepted.
  • Requirements: RUN-05.

This change also tightens the class. The wall path, the capture history and the enemy list become required properties, like Player. The compiler then refuses to build a session that forgets one of them, so a half-built session cannot reach the simulation. The properties are also regrouped, so the members that a run adds sit together.

Open Source/Data/GameSession.cs. The change touches most of the file and moves properties, so replace the whole file with the following. The ApplyUpgrade method is a stub for now.

replace-file Source/Data/GameSession.cs
csharp
using LastPerimeter.Entities;

namespace LastPerimeter.Data;

public sealed class GameSession
{
    public required Player Player { get; init; }
    public required PlayableWallPath PlayableWallPath { get; set; }
    public required List<CapturedZone> CaptureHistory { get; init; }
    public required List<Enemy> Enemies { get; init; }
    public List<Powerup> Powerups { get; init; } = [];
    public RunModifiers RunModifiers { get; init; } = new();
    public List<RunUpgradeKind> ChosenUpgrades { get; init; } = [];
    public RunUpgradeChoice[] PendingUpgradeChoices { get; set; } = [];
    public LevelDefinition CurrentLevelDefinition { get; set; } = new(1, "LEVEL 1", 75f, 1f, [EnemyVariant.Wanderer]);
    public DifficultyPreset Difficulty { get; set; } = DifficultyPreset.Classic;
    public RunMode RunMode { get; set; } = RunMode.Classic;
    public float ClaimedAreaPercentage { get; set; }
    public int Score { get; set; }
    public int HighScore { get; set; }
    public int Level { get; set; } = 1;
    public float RespawnGraceRemaining { get; set; }
    public float FreezeEnemiesRemaining { get; set; }
    public float DoublePointsRemaining { get; set; }
    public int ShieldCharges { get; set; }
    public bool SlowDrawActive => Player.CurrentTrail?.IsSlowDraw == true;
    public int Seed { get; set; }

    // Everything a run upgrade does, in one place: the modifier, the record of
    // the choice, and the extra life, which belongs to the player rather than
    // to RunModifiers.
    public void ApplyUpgrade(RunUpgradeKind upgrade)
    {
        throw new NotImplementedException();
    }
}

The key changes are:

  • PlayableWallPath, CaptureHistory and Enemies are now required, with no default value. Player was already required.
  • RunModifiers, ChosenUpgrades, PendingUpgradeChoices, RunMode and Seed are new.
  • Score, HighScore and Level moved up beside the other run numbers, and the comment above the class is gone.
  • ApplyUpgrade has the shape of its card and a body that throws.

In a terminal, from the LastPerimeter folder, run dotnet build. The build fails on purpose. GameplayScene.StartRun creates a GameSession without the three new required properties, and the compiler reports an error for it.

This is the compiler doing its job. It found the one place that built a session by hand. You fix it in the next sections, by building the factory that every run will use. First, you add the two tests for ApplyUpgrade.

Open Tests/Systems/RunModifiersTests.cs. At the top of the file, add the following line below the other using lines. The tests need a Player and a PlayableWallPath, which live in LastPerimeter.Entities.

add-using Tests/Systems/RunModifiersTests.cs
csharp
using LastPerimeter.Entities;

Add the following test to the RunModifiersTests class, below the Apply_BonusLife_LeavesModifierAggregateUnchanged test. It applies Extra Life and checks both halves of the rule: the life and the record.

add-member Tests/Systems/RunModifiersTests.cs after=Apply_BonusLife_LeavesModifierAggregateUnchanged
csharp
    [Fact]
    public void ApplyUpgrade_BonusLife_AddsALifeAndRecordsTheChoice()
    {
        GameSession session = CreateSession();
        int livesBefore = session.Player.Lives;

        session.ApplyUpgrade(RunUpgradeKind.BonusLife);

        Assert.Equal(livesBefore + 1, session.Player.Lives);
        Assert.Equal([RunUpgradeKind.BonusLife], session.ChosenUpgrades);
    }

Add the following test below the ApplyUpgrade_BonusLife_AddsALifeAndRecordsTheChoice test. It checks that a number upgrade reaches the modifiers through the session.

add-member Tests/Systems/RunModifiersTests.cs after=ApplyUpgrade_BonusLife_AddsALifeAndRecordsTheChoice
csharp
    [Fact]
    public void ApplyUpgrade_HigherScoring_UpdatesRunModifiers()
    {
        GameSession session = CreateSession();

        session.ApplyUpgrade(RunUpgradeKind.HigherScoring);

        Assert.Equal(1.25f, session.RunModifiers.ScoreMultiplier, precision: 3);
    }

Add the following helper below the ApplyUpgrade_HigherScoring_UpdatesRunModifiers test. It builds the smallest session the compiler accepts, which is exactly what required demands.

add-member Tests/Systems/RunModifiersTests.cs after=ApplyUpgrade_HigherScoring_UpdatesRunModifiers
csharp
    private static GameSession CreateSession()
    {
        return new GameSession
        {
            Player = new Player(),
            PlayableWallPath = new PlayableWallPath([]),
            CaptureHistory = [],
            Enemies = [],
        };
    }

The test builder in Tests/TestHelpers/SimulationBuilder.cs already supplies the required properties. It should also record its seed on the session, because the session now has a Seed. Open that file, find the Create method and replace the whole method with the following:

replace-method Tests/TestHelpers/SimulationBuilder.cs Create
csharp
    public static GameplaySimulation Create(int seed = 1, bool withEnemies = false, int margin = 0, int level = 1)
    {
        GameConfig config = TestConfigFactory.Create(width: 80 + (margin * 2), height: 80 + (margin * 2), margin: margin, tileSize: 4);
        GameSession session = new()
        {
            Player = new Player(),
            PlayableWallPath = new PlayableWallPath([]),
            CaptureHistory = [],
            Enemies = [],
            Level = level,
            Seed = seed,
        };
        GameplaySimulation simulation = new(config, session, new Random(seed));
        if (!withEnemies)
        {
            session.Enemies.Clear();
        }

        return simulation;
    }

The key change is the new line Seed = seed, in the session initialiser. Tests that ask the session for its seed now see the number they passed in.

Building the run factory ​

RunFactory is the one place a run is created.

RunFactory.Create(mode, startingLevel, settings, todayUtc, seed, config) : GameplaySimulation

  • Takes: the run mode, the level to start at, the settings, today's date in UTC, an optional seed and an optional config.
  • Gives: a simulation with the first level already started.
  • Promises: the session has the mode, the level and the difficulty from the settings. The starting lives come from the difficulty. The seed is the one given, or a fresh random one, and it is stored on the session.
  • Refuses: nothing. The date is accepted and not used until Chapter 19.
  • Requirements: RUN-01, LIV-01.

In the Source/Simulation folder, create a new file named RunFactory.cs and add the following code. The signature is complete and the body is a stub. The optional config parameter lets the real game pass its layout, and lets a test use the defaults. The int? seed is a nullable value, which means it can hold a number or nothing. New to nullable types? See the C# primer.

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

namespace LastPerimeter.Simulation;

public static class RunFactory
{
    // Builds the session and the simulation, and starts the first level. The seed
    // is stored on the session so the run can be replayed. Chapter 19 adds the daily
    // seed and separate random streams.
    public static GameplaySimulation Create(RunMode mode, int startingLevel, GameSettings settings, DateOnly todayUtc, int? seed = null, GameConfig? config = null)
    {
        throw new NotImplementedException();
    }
}

The tests for the factory live in the Tests/Simulation folder, which exists from Chapter 05. In that folder, create a new file named RunFactoryTests.cs and add the following code. It starts a Hardcore run at level 4 from the level select, and checks that the session, the level, the lives, the seed and the first event all agree.

new-file Tests/Simulation/RunFactoryTests.cs
csharp
using LastPerimeter.Data;
using LastPerimeter.Simulation;

namespace LastPerimeter.Tests.Simulation;

public sealed class RunFactoryTests
{
    [Fact]
    public void StartRun_FromLevelSelect_StartsAtChosenLevel()
    {
        GameSettings settings = new() { Difficulty = DifficultyPreset.Hardcore };

        GameplaySimulation sim = RunFactory.Create(RunMode.LevelSelect, 4, settings, new DateOnly(2026, 12, 2), seed: 99);

        Assert.Equal(4, sim.Session.Level);
        Assert.Equal(4, sim.Level.Definition.Number);
        Assert.Equal(RunMode.LevelSelect, sim.Session.RunMode);
        Assert.Equal(2, sim.Session.Player.Lives);
        Assert.Equal(99, sim.Session.Seed);
        Assert.Contains(sim.Events, e => e is LevelStarted { Level: 4 });
    }
}

You cannot run the tests yet, because the build still fails in GameplayScene. The next section fixes it. Every place that starts a run calls the factory, and the scenes that end a run record it.

Starting and ending runs through the scenes ​

Four scenes need to change before the build is green again. The pause menu needs to know the gameplay scene, so that Quit To Menu can end the run. The gameplay scene builds its runs with the factory and records the end of a run. The two menus pass the mode they start.

First, a new scene. In the Source/Scenes folder, create a new file named RunSummaryScene.cs and add the following code. It is an overlay that shows one line of text, and Enter or Escape returns to the main menu.

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

namespace LastPerimeter.Scenes;

public sealed class RunSummaryScene : Scene
{
    private readonly GameServices _services;
    private readonly string _summary;

    public RunSummaryScene(GameServices services, string summary)
    {
        _services = services;
        _summary = summary;
    }

    public override bool IsOverlay => true;

    public override void Update(float deltaTime, InputState input)
    {
        if (input.IsConfirmPressed || input.IsCancelPressed)
        {
            Scenes.Change(new MainMenuScene(_services));
        }
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        _services.Menus.DrawCenteredOverlay(spriteBatch, _services.Pixel, "RUN SUMMARY", _summary, "PRESS ENTER FOR MENU");
    }
}

Open Source/Scenes/PauseScene.cs. Add the following field to the PauseScene class, below the _services field:

add-member Source/Scenes/PauseScene.cs after=_services
csharp
    private readonly GameplayScene _gameplay;

In the same file, find the PauseScene constructor and replace the whole constructor with the following:

replace-method Source/Scenes/PauseScene.cs PauseScene
csharp
    public PauseScene(GameServices services, GameplayScene gameplay)
    {
        _services = services;
        _gameplay = gameplay;
    }

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

replace-method Source/Scenes/PauseScene.cs Update
csharp
    public override void Update(float deltaTime, InputState input)
    {
        MenuInput result = _menu.HandleInput(input);
        if (result == MenuInput.Moved)
        {
            _services.Audio.PlayMenuSelect();
        }

        if (input.IsPausePressed)
        {
            Scenes.Pop();
            return;
        }

        if (result != MenuInput.Confirmed)
        {
            return;
        }

        _services.Audio.PlayMenuSelect();
        switch (MenuTables.Pause[_menu.SelectedIndex].Command)
        {
            case MenuCommand.Resume:
                Scenes.Pop();
                break;
            case MenuCommand.Options:
                Scenes.Push(new OptionsScene(_services, dimBackground: true));
                break;
            case MenuCommand.QuitToMenu:
                _gameplay.FinishRun();
                Scenes.Change(new MainMenuScene(_services));
                break;
        }
    }

The key change is the new line _gameplay.FinishRun(); in the QuitToMenu case. It records the run before the scene changes. You add FinishRun to GameplayScene next.

Open Source/Scenes/GameplayScene.cs. The scene needs five small changes. Two using lines are no longer needed, because StartRun no longer builds a session by hand.

Find this line near the top of the file:

find Source/Scenes/GameplayScene.cs
csharp
using LastPerimeter.Entities;

Delete it. Nothing in the file creates a Player any more.

Find this line, also near the top of the file:

find Source/Scenes/GameplayScene.cs
csharp
using LastPerimeter.Systems;

Delete it as well. Nothing in the file creates a LevelProgressionSystem any more.

Find the StartRun method and replace the whole method with the following. It takes a RunMode and asks RunFactory.Create for the simulation. The new last parameter, seed, is for the smoke run described after the next listing. A player never passes it.

replace-method Source/Scenes/GameplayScene.cs StartRun
csharp
    // Starts a run: records it on the profile and builds the simulation.
    public static GameplayScene StartRun(GameServices services, RunMode mode, int startingLevel, int? seed = null)
    {
        services.Profile.RecordRunStarted();
        GameplaySimulation simulation = RunFactory.Create(mode, startingLevel, services.Profile.Settings, DateOnly.FromDateTime(DateTime.UtcNow), seed: seed, config: services.Config);
        simulation.Session.HighScore = services.Profile.Profile.HighScore;
        return new GameplayScene(services, simulation);
    }

In the same file, find this line in the Update method:

find Source/Scenes/GameplayScene.cs
csharp
            Scenes.Push(new PauseScene(_services));

Replace it with the following line. The pause scene receives the gameplay scene, so that Quit To Menu can call FinishRun.

csharp
            Scenes.Push(new PauseScene(_services, this));

Add the following method to the GameplayScene class, below the BeginLevel method. It records the end of a run on the profile and returns the summary text.

add-member Source/Scenes/GameplayScene.cs after=BeginLevel
csharp
    // Records the end of the run on the profile and returns the summary text.
    public string FinishRun()
    {
        GameSession session = _simulation.Session;
        _services.Profile.RecordRunFinished(session.Score);
        return $"SCORE {session.Score}  HI {_services.Profile.Profile.HighScore}  LEVEL {session.Level}";
    }

Find these lines in the React method that takes one GameEvent:

find Source/Scenes/GameplayScene.cs
csharp
                _services.Profile.RecordRunFinished(_simulation.Session.Score);

                // Chapter 18 shows a run summary here instead.
                Scenes.Change(new MainMenuScene(_services));

Replace them with the following line. The RunLost case now pushes a summary scene instead of changing straight to the main menu.

csharp
                Scenes.Push(new RunSummaryScene(_services, FinishRun()));

The key changes are:

  • The using LastPerimeter.Entities; and using LastPerimeter.Systems; lines are gone, because StartRun no longer creates a Player or a LevelProgressionSystem.
  • StartRun takes a RunMode. It records the run on the profile, asks RunFactory.Create for the simulation and copies the profile's high score onto the session.
  • StartRun still reads DateTime.UtcNow for the factory's date. That is a clock read inside the game, and Chapter 19 replaces it with a clock that tests can control.
  • StartRun has a new optional seed parameter, which it passes to the factory. A real run leaves it empty and gets a fresh random seed. The smoke run, which starts the game with --smoke-test-seconds, passes a fixed seed so that its scripted capture meets the same enemies every time.
  • FinishRun is new. It records the final score on the profile and returns the summary text, SCORE n HI n LEVEL n.
  • The RunLost case now pushes a RunSummaryScene that shows the text from FinishRun. Before, it changed straight to the main menu.
  • The pause scene is created with this, so that Quit To Menu can call FinishRun.

Open Source/Scenes/MainMenuScene.cs. At the top of the file, add the following line below the using Microsoft.Xna.Framework.Graphics; line:

add-using Source/Scenes/MainMenuScene.cs after=Microsoft.Xna.Framework.Graphics
csharp
using LastPerimeter.Data;

In the same file, find the Update method and replace the whole method with the following. The only change is the call to StartRun, which now passes RunMode.Classic.

replace-method Source/Scenes/MainMenuScene.cs Update
csharp
    public override void Update(float deltaTime, InputState input)
    {
        MenuInput result = _menu.HandleInput(input);
        if (result == MenuInput.Moved)
        {
            _services.Audio.PlayMenuSelect();
        }

        if (result != MenuInput.Confirmed)
        {
            return;
        }

        _services.Audio.PlayMenuSelect();
        switch (MenuTables.Main[_menu.SelectedIndex].Command)
        {
            case MenuCommand.StartRun:
                Scenes.Change(GameplayScene.StartRun(_services, RunMode.Classic, 1));
                break;
            case MenuCommand.LevelSelect:
                Scenes.Push(new LevelSelectScene(_services));
                break;
            case MenuCommand.Tutorial:
                Scenes.Push(new TutorialScene(_services));
                break;
            case MenuCommand.Options:
                Scenes.Push(new OptionsScene(_services, dimBackground: false));
                break;
            case MenuCommand.Quit:
                _services.Quit();
                break;
        }
    }

Open Source/Scenes/LevelSelectScene.cs. At the top of the file, add the same line below the using Microsoft.Xna.Framework.Graphics; line:

add-using Source/Scenes/LevelSelectScene.cs after=Microsoft.Xna.Framework.Graphics
csharp
using LastPerimeter.Data;

Find the Update method and replace the whole method with the following. It passes RunMode.LevelSelect and the level the player picked.

replace-method Source/Scenes/LevelSelectScene.cs Update
csharp
    public override void Update(float deltaTime, InputState input)
    {
        switch (_menu.HandleInput(input))
        {
            case MenuInput.Cancelled:
                Scenes.Pop();
                break;
            case MenuInput.Confirmed:
                _services.Audio.PlayMenuSelect();
                Scenes.Change(GameplayScene.StartRun(_services, RunMode.LevelSelect, _menu.SelectedIndex + 1));
                break;
        }
    }

The smoke run starts a Classic run directly, so the host must call the new StartRun. Open Source/Game/LastPerimeterApp.cs and find this line in the LoadContent method:

find Source/Game/LastPerimeterApp.cs
csharp
            _smokeScene = GameplayScene.StartRun(_services.Value, 1, SmokeScript.Seed);

Replace it with the following line. The smoke run is the headless check that --smoke-test-seconds starts, and it now asks for a Classic run at level 1 with its fixed seed.

csharp
            _smokeScene = GameplayScene.StartRun(_services.Value, RunMode.Classic, 1, SmokeScript.Seed);

In a terminal, from the LastPerimeter folder, run dotnet test. The build works again. The summary line should report Failed: 3 and Passed: 148. The three failures are the factory test and the two ApplyUpgrade tests, which all hit stubs.

Open Source/Simulation/RunFactory.cs, find the Create method and replace the whole method with the following:

replace-method Source/Simulation/RunFactory.cs Create
csharp
    // Builds the session and the simulation, and starts the first level. The seed
    // is stored on the session so the run can be replayed. Chapter 19 adds the daily
    // seed and separate random streams.
    public static GameplaySimulation Create(RunMode mode, int startingLevel, GameSettings settings, DateOnly todayUtc, int? seed = null, GameConfig? config = null)
    {
        int runSeed = seed ?? Random.Shared.Next();

        GameSession session = new()
        {
            Player = new Player(),
            PlayableWallPath = new PlayableWallPath([]),
            CaptureHistory = [],
            Enemies = [],
            Difficulty = settings.Difficulty,
            RunMode = mode,
            Level = startingLevel,
            Seed = runSeed,
        };
        session.Player.Lives = new LevelProgressionSystem().GetStartingLives(settings.Difficulty);

        return new GameplaySimulation(config ?? new GameConfig(), session, new Random(runSeed));
    }

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

Open Source/Data/GameSession.cs, find the ApplyUpgrade method and replace the whole method with the following:

replace-method Source/Data/GameSession.cs ApplyUpgrade
csharp
    // Everything a run upgrade does, in one place: the modifier, the record of
    // the choice, and the extra life, which belongs to the player rather than
    // to RunModifiers.
    public void ApplyUpgrade(RunUpgradeKind upgrade)
    {
        RunModifiers.Apply(upgrade);
        ChosenUpgrades.Add(upgrade);
        if (upgrade == RunUpgradeKind.BonusLife)
        {
            Player.Lives++;
        }
    }

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

The key things to note are:

  • seed ?? Random.Shared.Next() gives a Classic run a fresh seed when the caller passes none. A test, or Chapter 19's daily run, passes a seed and gets the same run each time.
  • The session is built with every required property, so it compiles. The wall path starts as an empty path, and the simulation rebuilds it when it enters the level.
  • new GameplaySimulation(...) enters the first level in its constructor, which raises LevelStarted. That is why the test finds the event in sim.Events.
  • ApplyUpgrade calls RunModifiers.Apply and then handles the life itself. The if is the only place in the game where BonusLife has an effect.
  • The todayUtc parameter is not read in this chapter. Having the parameter from the start means Chapter 19 changes the factory's body and not its callers.

Applying the modifiers to a level ​

The modifiers exist, but nothing reads them yet. Two numbers reach the level through LevelServices.Create, and two reach the tick.

Open Source/Simulation/LevelServices.cs. Two small changes pass the modifiers into the level. Find this line in the Create method:

find Source/Simulation/LevelServices.cs
csharp
    public static LevelServices Create(GameConfig baseConfig, LevelDefinition definition)

Replace it with the following line. Create now takes the RunModifiers as a third parameter.

csharp
    public static LevelServices Create(GameConfig baseConfig, LevelDefinition definition, RunModifiers modifiers)

In the same method, find this line:

find Source/Simulation/LevelServices.cs
csharp
            WinClaimPercentage = definition.RequiredClaimPercentage,

Add the following two lines directly below it, inside the with expression:

csharp
            RespawnGraceSeconds = baseConfig.RespawnGraceSeconds + modifiers.RespawnGraceBonusSeconds,
            FuseTriggerDelaySeconds = baseConfig.FuseTriggerDelaySeconds + modifiers.FuseDelayBonusSeconds,

The key changes are:

  • Create takes the RunModifiers as a third parameter.
  • The two new lines in the with expression add the grace bonus and the fuse bonus to the base config. FuseSystem is then built from the new delay, so the fuse itself did not change. This is how Cool Fuse and Safe Return work.

Open Source/Simulation/GameplaySimulation.cs. Find this line above the StartLevel method:

find Source/Simulation/GameplaySimulation.cs
csharp
    // Builds a new LevelServices and resets the level state. Keeps score, lives and shields.

Replace it with the following two lines. Only the comment changes. It now says that upgrades survive from one level to the next.

csharp
    // Builds a new LevelServices and resets the level state. Keeps score, lives,
    // shields and upgrades.

Find this line in the BuildLevel method:

find Source/Simulation/GameplaySimulation.cs
csharp
        return LevelServices.Create(_baseConfig, definition);

Replace it with the following line. It passes the session's modifiers to LevelServices.Create.

csharp
        return LevelServices.Create(_baseConfig, definition, _session.RunModifiers);

In a terminal, from the LastPerimeter folder, run dotnet test. Nothing changed for a run with no upgrades, so the summary line should still report Failed: 0 and Passed: 151.

The speed is next. The player speed is PlayerSpeed times the run multiplier, and it is halved by slow draw. This is requirement MOV-06. The test moves one simulation for one frame at 1.5 times the speed, and another for one frame of slow draw, and checks the distances. A frame is 0.05 seconds in ScriptedInput, and the test arena has a base speed of 100 pixels per second, so one frame at the base speed is 5 pixels.

The old movement test needs a small tidy first. Tick_KeepsPlayerInsideArena compared the player with a Rectangle. It now asks the arena whether the position is inside, which means the file no longer needs its Microsoft.Xna.Framework line. Open Tests/Simulation/MovementScenarioTests.cs and make four edits.

Find this line at the top of the file:

find Tests/Simulation/MovementScenarioTests.cs
csharp
using Microsoft.Xna.Framework;

Delete it.

Find this line in the Tick_KeepsPlayerInsideArena test:

find Tests/Simulation/MovementScenarioTests.cs
csharp
        Rectangle bounds = TestConfigFactory.Create().ArenaBounds;

Delete it as well.

In the same test, find these lines:

find Tests/Simulation/MovementScenarioTests.cs
csharp
                Vector2 position = sim.Session.Player.Position;
                Assert.InRange(position.X, bounds.Left, bounds.Right);
                Assert.InRange(position.Y, bounds.Top, bounds.Bottom);

Replace them with the following line:

csharp
                Assert.True(sim.Level.Arena.IsWithinBounds(sim.Session.Player.Position));

Add the following test to the MovementScenarioTests class, below the last test in the file:

add-member Tests/Simulation/MovementScenarioTests.cs at=end
csharp
    [Fact]
    public void Tick_AppliesRunAndSlowDrawSpeedFactors()
    {
        GameplaySimulation fast = SimulationBuilder.Create();
        fast.Session.RunModifiers.MoveSpeedMultiplier = 1.5f;
        ScriptedInput.Run(fast, ScriptedInput.Right, 1);
        Assert.Equal(7.5f, fast.Session.Player.Position.X, precision: 2);

        GameplaySimulation slow = SimulationBuilder.Create();
        ScriptedInput.Run(slow, ScriptedInput.Right, 4);
        InputState slowDown = new() { IsMovingDown = true, IsSlowDrawHeld = true };
        ScriptedInput.Run(slow, slowDown, 1);
        Assert.Equal(5f, slow.Session.Player.Position.Y, precision: 2);
        ScriptedInput.Run(slow, slowDown, 1);
        Assert.Equal(7.5f, slow.Session.Player.Position.Y, precision: 2);
    }

The key changes are:

  • The using Microsoft.Xna.Framework; line is gone, together with the Rectangle and Vector2 locals that needed it.
  • Tick_KeepsPlayerInsideArena calls IsWithinBounds on the arena.
  • Tick_AppliesRunAndSlowDrawSpeedFactors is new. It checks a speed of 1.5 times the base speed, and then the halved speed of a slow draw.

Tick will also store the speed it used on the player, so add a property for it. Nothing in this chapter reads the property back. It records the speed the player moved at, so you can inspect it in a debugger, and the new test checks the distance moved instead. Open Source/Entities/Player.cs. Add the following property to the Player class, below the CurrentDirection property:

add-member Source/Entities/Player.cs after=CurrentDirection
csharp
    public float Speed { get; set; }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 151. The new test fails, because Tick does not read the multiplier yet.

Open Source/Simulation/GameplaySimulation.cs, and find this line in the Tick method, in step 4:

find Source/Simulation/GameplaySimulation.cs
csharp
        float currentSpeed = _baseConfig.PlayerSpeed * (_session.SlowDrawActive ? TrailSystem.SlowDrawSpeedFactor : 1f);

Replace it with the following two lines:

csharp
        float currentSpeed = _baseConfig.PlayerSpeed * _session.RunModifiers.MoveSpeedMultiplier * (_session.SlowDrawActive ? TrailSystem.SlowDrawSpeedFactor : 1f);
        player.Speed = currentSpeed;

The key changes are:

  • In step 4, currentSpeed is the base speed times RunModifiers.MoveSpeedMultiplier, times the slow draw factor when a trail is being drawn slowly.
  • The new line player.Speed = currentSpeed; stores the speed on the player. Nothing reads it yet, as the note above says.

In the same file, make two small changes in the EnterLevel method. Find this line:

find Source/Simulation/GameplaySimulation.cs
csharp
        _session.ClaimedAreaPercentage = _level.Arena.GetClaimedPercentage();

Add the following line directly below it. It clears any pending upgrade cards.

csharp
        _session.PendingUpgradeChoices = [];

Find this line in the same method:

find Source/Simulation/GameplaySimulation.cs
csharp
        player.IsInvulnerable = false;

Add the following line directly above it. It sets the player's speed at the start of each level.

csharp
        player.Speed = _baseConfig.PlayerSpeed * _session.RunModifiers.MoveSpeedMultiplier;

Find these two lines in the ResolveCapture method, in step 6:

find Source/Simulation/GameplaySimulation.cs
csharp
        // 6. Score the region and trail tiles, doubled while Double Points lasts.
        float totalScoreMultiplier = _session.DoublePointsRemaining > 0f ? 2f : 1f;

Replace them with the following. The score multiplier is now the run multiplier times the double points factor.

csharp
        // 6. Score the region and trail tiles with the run multiplier.
        float totalScoreMultiplier = _session.RunModifiers.ScoreMultiplier * (_session.DoublePointsRemaining > 0f ? 2f : 1f);

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

The key things to note are:

  • The speed lives in one expression in Tick. The wall movement and the trail drawing both receive currentSpeed, so one change reaches both.
  • The score multiplier multiplies. The run multiplier is 1.25 after one Double Down, and a double points powerup doubles that to 2.5. The two bonuses combine.
  • EnterLevel clears PendingUpgradeChoices, so the cards from one draft never carry over to the next level.
  • No test checks the fuse delay or the grace time with an upgrade. Each is one with line in LevelServices.Create. The Extensions below ask you to write the tests.

Adding the upgrade scene ​

After a level, the player presses Enter on LEVEL COMPLETE and sees the draft. In the Source/Scenes folder, create a new file named UpgradeScene.cs and add the following code:

new-file Source/Scenes/UpgradeScene.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Data;
using LastPerimeter.Game;
using LastPerimeter.Input;
using LastPerimeter.Scenes.Menus;
using LastPerimeter.Systems;

namespace LastPerimeter.Scenes;

public sealed class UpgradeScene : Scene
{
    private readonly GameServices _services;
    private readonly GameplayScene _gameplay;
    private readonly GameSession _session;
    private readonly string[] _options;
    private readonly string _subtitle;
    private readonly MenuList _menu;

    public UpgradeScene(GameServices services, GameplayScene gameplay)
    {
        _services = services;
        _gameplay = gameplay;
        _session = gameplay.Simulation.Session;
        _session.PendingUpgradeChoices = RunUpgradeDraft.CreateChoices(_session.Level, _session.Seed);
        _options = new string[_session.PendingUpgradeChoices.Length];
        for (int index = 0; index < _options.Length; index++)
        {
            RunUpgradeChoice choice = _session.PendingUpgradeChoices[index];
            _options[index] = $"{choice.Name} - {choice.Description}";
        }

        _subtitle = $"LEVEL {_session.Level} CLEARED";
        _menu = new MenuList(_options);
    }

    public override bool IsOverlay => true;

    public override void Update(float deltaTime, InputState input)
    {
        MenuInput result = _menu.HandleInput(input);
        if (result == MenuInput.Moved)
        {
            _services.Audio.PlayMenuSelect();
        }

        if (result == MenuInput.Cancelled)
        {
            _menu.Select(0);
        }

        if (result != MenuInput.Confirmed)
        {
            return;
        }

        RunUpgradeChoice choice = _session.PendingUpgradeChoices[_menu.SelectedIndex];
        _session.ApplyUpgrade(choice.Upgrade);
        _services.Audio.PlayPowerup();
        Scenes.Pop();
        _gameplay.BeginLevel(_session.Level + 1);
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        _services.Menus.DrawMenu(spriteBatch, _services.Pixel, "CHOOSE AN UPGRADE", _subtitle, _options, _menu.SelectedIndex, Color.Gold, overlay: true);
    }
}

The key things to note are:

  • The constructor creates the draft with RunUpgradeDraft.CreateChoices, from the session's level and seed, and stores it on the session. The scene shows one line for each card.
  • The scene reads Session.Seed. Chapter 19 changes it to a seed of its own for the draft.
  • Escape moves the cursor back to the first card and does not leave the scene. A player cannot skip the draft, because the next level must follow it.
  • On Enter, ApplyUpgrade records the choice. The scene then removes itself and asks the gameplay scene to begin the next level, which builds new LevelServices that include the new modifiers.
  • IsOverlay is true, so the cleared level stays visible behind the cards.

Now the level complete scene must open the draft. Open Source/Scenes/LevelCompleteScene.cs. Find the Update method and replace the whole method with the following. Enter used to start the next level. It now opens the draft.

replace-method Source/Scenes/LevelCompleteScene.cs Update
csharp
    public override void Update(float deltaTime, InputState input)
    {
        if (!input.IsConfirmPressed)
        {
            return;
        }

        Scenes.Pop();
        Scenes.Push(new UpgradeScene(_services, _gameplay));
    }

Find the Draw method and replace the whole method with the following. The prompt now says what Enter does.

replace-method Source/Scenes/LevelCompleteScene.cs Draw
csharp
    public override void Draw(SpriteBatch spriteBatch)
    {
        _services.Menus.DrawCenteredOverlay(spriteBatch, _services.Pixel, "LEVEL COMPLETE", _bonusLine, "PRESS ENTER FOR UPGRADES");
    }

Running the tests ​

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 152. The 152 tests are the 140 from earlier chapters and 12 new ones.

TestProves
CreateUpgradeChoices_ReturnsThreeDistinctOptionsRUN-02
CreateChoices_WithSameSeed_IsRepeatableRUN-03
Apply_FasterMovement_IncreasesMoveSpeedMultiplierRUN-04
Apply_SlowerFuse_AddsFuseDelayBonusRUN-04
Apply_HigherScoring_IncreasesScoreMultiplierRUN-04
Apply_SaferRespawn_AddsRespawnGraceBonusRUN-04
Apply_StacksAcrossRepeatedPicksRUN-04
Apply_BonusLife_LeavesModifierAggregateUnchangedRUN-05
ApplyUpgrade_BonusLife_AddsALifeAndRecordsTheChoiceRUN-05
ApplyUpgrade_HigherScoring_UpdatesRunModifiersRUN-05
StartRun_FromLevelSelect_StartsAtChosenLevelRUN-01
Tick_AppliesRunAndSlowDrawSpeedFactorsMOV-06

RUN-09, FE-08 and FE-09 are scene behaviour with no test of their own. You prove them in the next section. The fuse, grace and score bonuses (FUS-02, LIV-07 and SCO-03) have no test of their own either. Their base rules are tested in earlier chapters, and each bonus is one added term in LevelServices.Create or ResolveCapture.

Running the game ​

From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen, then Enter again on START RUN. Clearing a level takes a while at the real target. You need a window to see the cards and the faster movement, but the test counts already prove the draft, the modifiers and the factory.

TIP

To clear a level quickly, open Source/Systems/LevelProgressionSystem.cs and change 75f in CreateLevel to 10f. Run the game, and a few small captures clear the level. Change the value back before you go on.

Clear level 1. The LEVEL COMPLETE overlay appears with the bonus line and the prompt PRESS ENTER FOR UPGRADES. Press Enter. The CHOOSE AN UPGRADE overlay opens with three cards, as in Figure 18-1. Press Down to move the cursor, then press Enter on QUICKSTEP if it is offered. Level 2 starts, and the player moves visibly faster along the wall. If QUICKSTEP is not offered, pick any card. The draft for level 1 of one run is always the same, and a new Classic run shows a different draft.

Now lose every life. The RUN SUMMARY overlay shows SCORE n HI n LEVEL n, with your score, the best score and the level you reached. Press Enter, and the main menu opens.

Start a run again and score a little. Press Escape to pause, move to QUIT TO MENU and press Enter. The main menu opens. Quitting records the run, as FE-09 requires, so your score counts towards the high score. Start another run and lose it, and the HI value in the summary is at least the score you had when you quit.

Close the window with its close button when you finish. The next section is optional. It replaces your files with the chapter 18 snapshot.

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 18 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/18-Runs-And-Upgrades"
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/18-Runs-And-Upgrades"
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: 152.

Common mistakes ​

  • The build fails with "Required member 'GameSession.PlayableWallPath' must be set". A place that creates a GameSession still builds it by hand. Make that place call RunFactory.Create, or add the missing properties to its initialiser.
  • Quickstep changes nothing. Tick still uses _baseConfig.PlayerSpeed alone. Check that step 4 multiplies by _session.RunModifiers.MoveSpeedMultiplier.
  • Extra Life adds two lives. RunModifiers.Apply has a BonusLife case that also changes a number, or Player.Lives is raised in two places. The life belongs in ApplyUpgrade only.
  • The same three cards appear on every level. The Random in CreateChoices is seeded with the seed alone. Add the level term.
  • The draft changes when you reopen the scene. The Random is seeded from the clock or from Random.Shared. Seed it from the arguments.
  • Quit To Menu does not update the high score. PauseScene was not given the gameplay scene, or the QuitToMenu case never calls FinishRun.

Conclusion ​

In this chapter, you accomplished the following:

The tests now prove RUN-01 to RUN-05 and MOV-06, and the game proves RUN-09, FE-08 and FE-09. In the next chapter, Chapter 19: Seeds, the Clock and the Daily Challenge, you make a run a pure function of its seed and add the Daily Challenge.

Test Your Knowledge ​

  1. Why does RunModifiers.Apply(BonusLife) do nothing?

    Answer

    A life belongs to the player, and Player.Lives is already the number the game reads. GameSession.ApplyUpgrade handles it, so the whole rule is in one method and the game never counts lives in two places.

  2. Why is the draft seeded with the level as well as the run seed?

    Answer

    The level term makes each level offer a different draft. The seed and the level are fixed for a given point in a run, so the same level of the same run always offers the same cards.

  3. Which service had to change for Cool Fuse to work?

    Answer

    Only LevelServices.Create, which adds the bonus to the fuse delay it passes to FuseSystem. The fuse itself did not change, because it already took its delay as a number.

  4. What did the required properties on GameSession do to the old StartRun, and why is that useful?

    Answer

    The build failed, because StartRun built a session without the new required properties. The compiler found every hand-built session for you, and it will do the same for any later code that forgets one.

Extensions ​

  • Write a test for Cool Fuse. Call LevelServices.Create with a RunModifiers whose FuseDelayBonusSeconds is 0.5, and check that the Config of the result has a FuseTriggerDelaySeconds of 2.5.
  • Write the matching test for Safe Return, and one for Double Down that scores 100 tiles with a multiplier of 1.25.
  • Add a sixth upgrade to RunUpgradeKind. Which methods and tests must change, and which services stay as they are?