Appearance
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
RunModifiersobject, andSetupLevelis the single place where those modifiers touch the live systems.
Time: [TODO Simon: time estimate for chapter 13]
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:
- separate in-level state, run state, and meta progression into distinct owned objects with distinct lifetimes,
- implement an upgrade draft with a deterministic, seed-driven shuffle (
PowerupSystem.CreateUpgradeChoices), - accumulate picked upgrades into a
RunModifiersaggregate and apply it at well-defined points in level setup, - trace exactly which state resets at level start and which carries across the run,
- reason about runaway stacking using additive caps and per-pick increments.
Code anchors
Source/Data/RunModifiers.cs(the run-state aggregate andApply),Tests/Systems/RunModifiersTests.csSource/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 inSetupLevel)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
This codebase keeps the three layers as three different objects with three different lifetimes:
- in-level state: rebuilt by
SetupLevelevery level (ArenaSystem, trail, fuse, powerups, enemies), - run state: lives on
GameSession, created once perStartRun(Score,Lives,RunModifiers,ChosenUpgrades), - meta progression: lives on
PlayerProfile, kept byProfileTrackerand persisted byProfileStorageacross 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.
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.csTests/Systems/RunModifiersTests.cs
Replaced files (you already have these, so overwrite them):
Source/Data/GameSession.csSource/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/DesktopVKdotnet 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 testRunModifiersTests 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
- In your
LastPerimeterfolder, rundotnet test. It reports 73 passing tests. If it does not, compare yourSourceandTestsfolders with the chapter 13 snapshot. - Run
dotnet run --project Platforms/DesktopVK. Press Enter on the title screen and chooseSTART RUN(the Controls table in chapter 03 lists every key). - Clear level 1 by claiming area until the claim goal is reached. The
LEVEL COMPLETEoverlay appears withPRESS ENTER FOR UPGRADES. Press Enter, and the three-card draft appears (the screenshots above). - Highlight a card with Up and Down and press Enter. If
COOL FUSEis 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. - Press Escape, choose
QUIT TO MENU, and start a second run withSTART 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. - In one run, pick
QUICKSTEPevery time it is offered and find the speed at which corners stop working (the tip under "The risk of runaway stacking" gives the numbers). IfQUICKSTEPnever appears in the first drafts, openSource/Game/LastPerimeterApp.csand find the line inUpdateLevelCompletethat callsCreateUpgradeChoices(_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:
RunModifiersandChosenUpgradesonGameSession, 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:
- branching upgrade trees,
- relic-style permanent modifiers (these would live on
PlayerProfile, notRunModifiers; defend the layer choice), - shop choices instead of free picks,
- difficulty escalation that reacts to a strong build,
- a determinism test: the same seed and level must give the same three cards,
- upgrade categories the build does not have yet, such as capture efficiency and enemy control.

