Skip to content

Chapter 13 - Roguelite Runs, Between-Level Choices, and Persistent Abilities ​

Where this chapter fits: clearing a level now offers a choice. Three upgrade cards are drawn deterministically, the pick accumulates into a run-scoped RunModifiers object, and SetupLevel is the single place where those modifiers touch the live systems.

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

The upgrade draft after clearing level 1: CHOOSE AN UPGRADE with three cards, DOUBLE DOWN highlighted

The between-level draft in the chapter 13 build, drawn as an overlay above the frozen arena. To reach this screen with a scripted capture the claim goal was temporarily lowered to 3% in a scratch copy of the snapshot; the overlay itself is unchanged.

Prerequisites ​

Chapters 10-12 (level progression, powerups, the front-end state machine, and profile persistence).

Learning objectives ​

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

  1. separate in-level state, run state, and meta progression into distinct owned objects with distinct lifetimes,
  2. implement an upgrade draft with a deterministic, seed-driven shuffle (PowerupSystem.CreateUpgradeChoices),
  3. accumulate picked upgrades into a RunModifiers aggregate and apply it at well-defined points in level setup,
  4. trace exactly which state resets at level start and which carries across the run,
  5. reason about runaway stacking using additive caps and per-pick increments.

Code anchors ​

  • Source/Data/RunModifiers.cs (the run-state aggregate and Apply), Tests/Systems/RunModifiersTests.cs
  • Source/Data/RunUpgradeChoice.cs (one offered card: Upgrade, Name, Description)
  • Source/Data/Enums.cs (RunUpgradeKind: FasterMovement, SlowerFuse, HigherScoring, SaferRespawn, BonusLife; GameStatus.UpgradeSelect)
  • Source/Systems/PowerupSystem.cs (CreateUpgradeChoices(level, seed))
  • Source/Data/GameSession.cs (the full version: RunModifiers, ChosenUpgrades, PendingUpgradeChoices, ApplyUpgrade)
  • Source/Game/LastPerimeterApp.cs (chapter 13 staged version: UpdateLevelComplete, UpdateUpgradeSelect, DrawUpgradeSelect, the modifier hooks in SetupLevel)
  • Source/Data/PlayerProfile.cs (the meta-progression layer)

The key lesson ​

Roguelite structure works when the run layer amplifies the core mechanic instead of replacing it.

Three progression layers to separate ​

Three nested boxes: meta progression in PlayerProfile, run state in GameSession, in-level state rebuilt by SetupLevel, each with its lifetime and reset rule

This codebase keeps the three layers as three different objects with three different lifetimes:

  1. in-level state: rebuilt by SetupLevel every level (ArenaSystem, trail, fuse, powerups, enemies),
  2. run state: lives on GameSession, created once per StartRun (Score, Lives, RunModifiers, ChosenUpgrades),
  3. meta progression: lives on PlayerProfile, kept by ProfileTracker and persisted by ProfileStorage across runs (HighScore, HighestUnlockedLevel, Statistics).

If those layers blur together, balancing becomes nearly impossible. Here the type system enforces the boundary.

The between-level draft ​

When a level is cleared, UpdateLevelComplete generates three offers and switches to GameStatus.UpgradeSelect. The offers come from PowerupSystem.CreateUpgradeChoices:

csharp
public RunUpgradeChoice[] CreateUpgradeChoices(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();
}

The shuffle is deterministic: new Random(seed + (level * 31)) means the same seed and level always offer the same three cards. The caller chooses the seed. The chapter 13 app passes the level number itself (CreateUpgradeChoices(_gameSession.Level, _gameSession.Level)), so every Classic run sees the same cards after each level. Chapter 14 substitutes the daily-challenge seed, which is what makes shared daily runs fair. Each archetype is represented once: mobility, pacing, scoring, survival, and a rare immediate resource.

The LEVEL COMPLETE overlay that precedes the draft: BONUS 1500, PRESS ENTER FOR UPGRADES

Accumulating picks ​

A confirmed pick flows through UpdateUpgradeSelect into GameSession.ApplyUpgrade, which calls RunModifiers.Apply:

csharp
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)
    {
        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;
        }
    }
}
csharp
private void UpdateUpgradeSelect(InputState input)
{
    HandleVerticalMenu(input, _gameSession.PendingUpgradeChoices.Length, ref _upgradeMenuIndex);

    if (input.IsCancelPressed)
    {
        _upgradeMenuIndex = 0;
    }

    if (!input.IsConfirmPressed)
    {
        return;
    }

    RunUpgradeChoice choice = _gameSession.PendingUpgradeChoices[_upgradeMenuIndex];
    _gameSession.ApplyUpgrade(choice.Upgrade);

    _audioCuePlayer?.PlayPowerup();
    SetupLevel(_gameSession.Level + 1);
}

The app hands the pick to the session and then calls SetupLevel. Everything an upgrade does lives in one GameSession method:

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

ChosenUpgrades is the history, kept for the run summary and balancing. BonusLife is the one upgrade RunModifiers.Apply deliberately ignores. It is an instant resource, not a modifier, so the aggregate stays untouched (Apply_BonusLife_LeavesModifierAggregateUnchanged in RunModifiersTests). The other four never patch live systems directly. They only change the aggregate.

Where modifiers actually take effect ​

SetupLevel is the single choke point where run state touches in-level systems:

csharp
_activeConfig = _baseConfig with
{
    EnemySpeed = _baseConfig.EnemySpeed * levelDefinition.EnemySpeedMultiplier,
    WinClaimPercentage = levelDefinition.RequiredClaimPercentage,
    RespawnGraceSeconds = _baseConfig.RespawnGraceSeconds + _gameSession.RunModifiers.RespawnGraceBonusSeconds,
    FuseTriggerDelaySeconds = _baseConfig.FuseTriggerDelaySeconds + _gameSession.RunModifiers.FuseDelayBonusSeconds,
};
// ...
_gameSession.Player.Speed = _baseConfig.PlayerSpeed * _gameSession.RunModifiers.MoveSpeedMultiplier;

ScoreMultiplier joins in at claim time (totalScoreMultiplier = RunModifiers.ScoreMultiplier * (DoublePointsRemaining > 0f ? 2f : 1f) in CompleteTrailClaim). The per-frame speed in UpdateGameplay multiplies MoveSpeedMultiplier in as well. Because everything derives from _baseConfig fresh each level, upgrades compose cleanly and a new run starts from a clean slate. The reset rule is structural, not a checklist.

The risk of runaway stacking ​

Every upgrade here is additive (+0.15x speed, +0.25x score, +0.5 s) with no caps, a deliberate simplicity for teaching. Think about caps, trade-offs, rarity, mutually exclusive branches, and reset rules at run end. Then decide which the current model needs first.

TIP

Try stacking QUICKSTEPs. The base speed of 150 px per second is a 2.5 px step at 60 frames per second. Chapter 04 showed that corners work while the step is no more than twice the 2 px tolerance band, which is 4 px per frame. Four QUICKSTEPs (1.6x) give exactly 4.0 px, the limit. The fifth (1.75x, 4.4 px) goes past it, so the player can stop more than 2 px short of a corner and the turn is refused. That is the containment check's hidden assumption showing through.

Build it step by step ​

This chapter is copy-along. Step 1 copies the chapter's files from the snapshot, and the steps after it walk through what changed and why. The listings show the parts worth studying, not every line.

Step 1 - Copy the chapter files ​

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

In PowerShell:

powershell
Copy-Item -Recurse -Force "<course-repo>/DOCUMENTATION/LastPerimeter-Source/13-Roguelite-Runs-Between-Level-Choices-And-Persistent-Abilities/Source", "<course-repo>/DOCUMENTATION/LastPerimeter-Source/13-Roguelite-Runs-Between-Level-Choices-And-Persistent-Abilities/Tests" .

In bash:

bash
cp -R "<course-repo>/DOCUMENTATION/LastPerimeter-Source/13-Roguelite-Runs-Between-Level-Choices-And-Persistent-Abilities/Source" "<course-repo>/DOCUMENTATION/LastPerimeter-Source/13-Roguelite-Runs-Between-Level-Choices-And-Persistent-Abilities/Tests" .

That copy brings in these files:

New files:

  • Source/Data/RunModifiers.cs
  • Tests/Systems/RunModifiersTests.cs

Replaced files (you already have these, so overwrite them):

  • Source/Data/GameSession.cs
  • Source/Game/LastPerimeterApp.cs

NOTE

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

Step 2 - The full GameSession ​

Open Source/Data/GameSession.cs. This is the full version, which replaces the staged one. It adds RunModifiers, ChosenUpgrades, PendingUpgradeChoices, ApplyUpgrade, DailyChallengeActive and DailyChallengeSeed.

Step 3 - The upgrade menu: UpdateUpgradeSelect and DrawUpgradeSelect ​

Open Source/Game/LastPerimeterApp.cs. It gains _upgradeMenuIndex, the UpgradeSelect case in both switches, UpdateUpgradeSelect (which calls _gameSession.ApplyUpgrade(choice.Upgrade)), and DrawUpgradeSelect. The draw method is a DrawMenu overlay whose rows are "{Name} - {Description}".

Step 4 - The draft handoff: UpdateLevelComplete ​

Open Source/Game/LastPerimeterApp.cs. UpdateLevelComplete now creates the choices and switches to UpgradeSelect instead of calling SetupLevel directly. The overlay footer changes to PRESS ENTER FOR UPGRADES.

Step 5 - Applying the modifiers: SetupLevel ​

Open Source/Game/LastPerimeterApp.cs. The modifiers are applied in SetupLevel (the with expression shown earlier and the player speed), in the per-frame speed calculation, and in the claim score. SetupLevel also clears PendingUpgradeChoices, so a stale draft can never be shown twice.

Step 6 - Build, test, run ​

Run these commands from your LastPerimeter folder:

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

dotnet test reports 73 passing tests. On Windows you can also run dotnet run --project Platforms/WindowsDX12.

Chapter snapshot ​

The buildable project lives at DOCUMENTATION/LastPerimeter-Source/13-Roguelite-Runs-Between-Level-Choices-And-Persistent-Abilities. Versus chapter 12 it adds RunModifiers.cs, RunModifiersTests.cs, and the full GameSession.cs (replacing the staged version with the run-modifier and upgrade-state fields). GameSession.cs also gains ApplyUpgrade. Its staged app adds the between-level flow: LevelComplete -> UpgradeSelect -> pick -> SetupLevel(level + 1).

bash
cd DOCUMENTATION/LastPerimeter-Source/13-Roguelite-Runs-Between-Level-Choices-And-Persistent-Abilities
dotnet build
dotnet test

RunModifiersTests arrives with nine facts. Six cover the modifiers: one per additive upgrade, stacking across repeated picks, and BonusLife leaving the aggregate unchanged. Three cover the session: ApplyUpgrade_BonusLife_AddsALifeAndRecordsTheChoice, ApplyUpgrade_HigherScoring_UpdatesRunModifiers and DailyChallengeActive_FollowsRunMode. This takes the suite from 64 to 73 tests, the final count for the course. The draft's shape is covered by PowerupSystemTests.CreateUpgradeChoices_ReturnsThreeDistinctOptions from chapter 11; a determinism test, with the same seed and level giving the same cards, is the obvious one to add as an exercise.

Checkpoint ​

  1. In your LastPerimeter folder, run dotnet test. It reports 73 passing tests. If it does not, compare your Source and Tests folders with the chapter 13 snapshot.
  2. Run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen and choose START RUN (the Controls table in chapter 03 lists every key).
  3. Clear level 1 by claiming area until the claim goal is reached. The LEVEL COMPLETE overlay appears with PRESS ENTER FOR UPGRADES. Press Enter, and the three-card draft appears (the screenshots above).
  4. Highlight a card with Up and Down and press Enter. If COOL FUSE is offered, pick it, then stop moving while you draw on level 2 and confirm that the fuse ignites later than it did on level 1.
  5. Press Escape, choose QUIT TO MENU, and start a second run with START RUN. Clear level 1 again and confirm the draft offers the same three cards, since the seed is the level number. Then explain why that determinism matters for the daily challenge in chapter 14.
  6. In one run, pick QUICKSTEP every time it is offered and find the speed at which corners stop working (the tip under "The risk of runaway stacking" gives the numbers). If QUICKSTEP never appears in the first drafts, open Source/Game/LastPerimeterApp.cs and find the line in UpdateLevelComplete that calls CreateUpgradeChoices(_gameSession.Level, _gameSession.Level). Change the second argument, which is the seed, to another number such as _gameSession.Level + 100, and run again. Change it back when you have finished.

What you should have now ​

You now have:

  • run state in its own model: RunModifiers and ChosenUpgrades on GameSession, created once per run,
  • a between-level draft of three upgrade cards, drawn by a deterministic, seeded shuffle,
  • five upgrades (QUICKSTEP, COOL FUSE, DOUBLE DOWN, SAFE RETURN, EXTRA LIFE) covering mobility, pacing, scoring, survival and an instant resource,
  • one place, SetupLevel, where run modifiers reach the in-level systems, so a new run starts clean,
  • RunModifiersTests, which takes the suite to 73 tests.

Common mistakes ​

  • applying an upgrade by mutating a live system (it evaporates at the next SetupLevel, or double-applies),
  • storing run modifiers on the profile (they would leak into the next run),
  • reshuffling with an unseeded Random (no two runs comparable),
  • forgetting that additive multipliers have no ceiling.

Extensions ​

Try to prototype:

  1. branching upgrade trees,
  2. relic-style permanent modifiers (these would live on PlayerProfile, not RunModifiers; defend the layer choice),
  3. shop choices instead of free picks,
  4. difficulty escalation that reacts to a strong build,
  5. a determinism test: the same seed and level must give the same three cards,
  6. upgrade categories the build does not have yet, such as capture efficiency and enemy control.