Appearance
Chapter 09 - Testing, Debugging, and Course Extensions
Where this chapter fits: no new runtime code. The chapter 09 build is intentionally identical to chapter 08. The subject is proving that the hard parts work. That means the test suite you have accumulated, the smoke-test option and a formal root-cause analysis (RCA) of the systems you already built.
Time: [TODO Simon: time estimate for chapter 09]
Prerequisites
Chapters 01-08 complete and passing their tests. You should recognise every system named in a test file. There is nothing to copy for this chapter, because the chapter 09 snapshot equals the chapter 08 one. Keep working in your LastPerimeter folder.
Learning objectives
By the end of this chapter you should be able to:
- organise gameplay validation into three layers (unit tests, playable checkpoints, debug visualisation),
- run, filter and read the output of the xUnit suite, and name what each test file protects,
- write a regression test that pins a fixed bug in place, using the partition-guard and backtrack tests as models,
- run the real game for a few seconds with the smoke-test option for scripted verification,
- conduct a formal RCA that separates algorithm failures from contract failures,
- name which rule still owns level completion, and why eliminating the last enemy does not end the level.
Code anchors
Tests/LastPerimeter.Tests.csprojTests/Systems/*.csandTests/Game/GameLaunchOptionsTests.csTests/TestHelpers/TestConfigFactory.csSource/Game/GameLaunchOptions.csandLastPerimeterApp.ShouldAutoExit(the smoke-test option)Platforms/DesktopVK/Program.csscripts/test-chapters.sh,scripts/TestChapterProjects.ps1(in the course repository)
Why testing matters so much here
This kind of game hides many of its hardest failures behind visuals that can look "close enough". A region claims incorrectly, the wall path fails after a topology change, or a self-intersection is missed. Flood fill leaks through a one-cell gap, or collision feels random because update order is wrong. That is why this project suits the lesson that gameplay code needs tests too.
Three-layer testing strategy
Validate at three levels:
- unit tests for geometry and algorithms,
- playable checkpoints for feel and usability (every chapter's Checkpoint section),
- debug visualisation for invisible internal state.
The smoke-test option sits between the first two. It is scriptable like a test, but it exercises the real window, graphics device and update loop.
The suite you have built so far
Forty-five tests across seventeen files, all against pure systems that need no window:
| File | Tests | What it protects |
|---|---|---|
GameLaunchOptionsTests | 3 | smoke-test argument and environment parsing (chapter 01) |
ArenaSystemTests | 3 | world-to-grid mapping, idempotent claim counting, the Boundary sentinel (chapter 02) |
PlayableWallPathTests | 1 | the initial arena path is a closed rectangle of four segments (chapter 04) |
PlayableWallPathTraversalTests | 1 | movement still works on the rebuilt path after a claim (chapter 04) |
WallSystemV2Tests | 1 | the rebuilt path matches the remaining playable region (chapter 04) |
MovementSystemTests | 3 | no input means no direction, interior moves are refused, corners connect (chapter 04) |
TrailTests | 4 | half-pixel point rejection, arc-length interpolation, endpoint clamping, the empty trail (chapter 05) |
TrailSystemTests | 3 | the no-backtrack rule, anchoring to the wall, gap-free completion (chapter 05) |
TrailLoopTests | 1 | self-intersection is detected at the closure point (chapter 05) |
FuseSystemTests | 3 | the fuse ignites after the delay, pauses while the player moves and resumes on the next stop, and is extinguished when the trail ends (chapter 05) |
AreaClaimingSystemTests | 4 | smaller-region preference, enemy avoidance, the partition guard, the both-sides fallback (chapter 06) |
CollisionSystemTests | 2 | trail contact, and player contact only while drawing (chapter 07) |
EnemySystemTests | 6 | variant speed applies to movement, frozen enemies stay put, clones expire, a seeded Random gives identical retargeting, and an enemy on claimed ground recovers to free ground (chapter 07) |
EnemySplitterTests | 3 | a Splitter emits a clone only when its split timer runs out and then re-arms the timer, the clone is a smaller, slower, temporary Hunter, and clones, other variants and frozen Splitters never split (chapter 07) |
ScoringSystemTests | 3 | tile scoring, the slow-draw and run multipliers, 1,000 points per percent above the goal (chapter 08) |
TrailSlowDrawTests | 3 | TryStart latches slow draw, defaults to fast, and releasing the input demotes the trail permanently (chapter 08) |
AudioCuePlayerTests | 1 | a player built with no audio device runs silent and playing a cue does nothing (chapter 08) |
Run them all, or just one file, from your LastPerimeter folder. The first command builds and tests the whole solution, and the filters run from the same folder:
bash
dotnet build
dotnet test
dotnet test --filter AreaClaimingSystemTests
dotnet test --filter "FullyQualifiedName~ProcessCompletedTrail_ReturnsNull"The last line of the output for the chapter 09 snapshot has this shape. Your duration will differ:
text
Passed! - Failed: 0, Passed: 45, Skipped: 0, Total: 45, Duration: ... - LastPerimeter.Tests.dll (net10.0)The suite runs fast because nothing in it touches MonoGame's graphics or audio. The test project in Tests/LastPerimeter.Tests.csproj is small. It compiles the game source directly instead of referencing a class library:
xml
<ItemGroup>
<Compile Include="..\Source\**\*.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MonoGame.Framework.Native" Version="$(MonoGameVersion)" />
</ItemGroup>The tests need MonoGame only for types such as Vector2, Point and Rectangle. MonoGame.Framework.Native supplies them without a window, and $(MonoGameVersion) comes from Directory.Packages.props, so the version is set in one place. The speed comes from the pure systems under Source/, which keep game rules apart from rendering.
Good tests to start with
- initial arena produces exactly four outer wall segments (
InitialArenaPath_IsClosedRectangle), - world-to-grid mapping rejects out-of-bounds positions and claim counting is idempotent (
ArenaSystemTests), - self-intersection is detected at the expected closure point (
SelfIntersection_IsDetected_AtLoopClosure), - the player cannot reverse onto the active trail (
CanAdvance_BlocksReversal_OntoActiveTrail), - a trail that fails to partition the arena claims nothing (
ProcessCompletedTrail_ReturnsNull_WhenTrailDoesNotPartitionArena), - enemy occupancy changes which region is captured (
ProcessCompletedTrail_AvoidsEnemyRegion), - enemy variant speed multipliers affect actual movement, not only intent (
Update_AppliesVariantSpeedMultiplier_ToActualMovement), - the playable path is rebuilt after a claim (
RebuildPlayablePath_AfterClaim_MatchesRemainingPlayableRegion).
Anatomy of a regression test
The partition-guard test is the model. It encodes a real shipped bug, and the comment says exactly what went wrong and what the guard prevents:
csharp
[Fact]
public void ProcessCompletedTrail_ReturnsNull_WhenTrailDoesNotPartitionArena()
{
ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));
AreaClaimingSystem areaClaimingSystem = new(arena);
// An out-and-back spur along a single line encloses no area; without the
// partition guard the smallest-region fallback would claim the whole arena.
Trail trail = new();
trail.AddPoint(new Vector2(0, 8));
trail.AddPoint(new Vector2(20, 8));
trail.AddPoint(new Vector2(1, 8));
ClaimResult? result = areaClaimingSystem.ProcessCompletedTrail(trail);
Assert.Null(result);
}Three habits are visible. The arena is tiny and comes from TestConfigFactory, so coordinates are readable. The test follows an arrange/act/assert shape. The comment names the bug rather than the code.
The backtrack test shows the other essential pattern. Assert the rejection and the nearby acceptances, so the rule cannot silently become "block everything":
csharp
trailSystem.TryStart(new Vector2(0, 8), new Vector2(4, 8));
Assert.False(trailSystem.CanAdvance(new Vector2(2, 8), arena, Direction.Left, Direction.Right));
Assert.True(trailSystem.CanAdvance(new Vector2(6, 8), arena, Direction.Right, Direction.Right));
Assert.True(trailSystem.CanAdvance(new Vector2(4, 12), arena, Direction.Down, Direction.Right));The smoke-test option
The host in Platforms/DesktopVK/Program.cs accepts --smoke-test-seconds N (or the LASTPERIMETER_SMOKE_TEST_SECONDS environment variable). GameLaunchOptions.Parse reads it, and the app's auto-exit check enforces it:
csharp
private bool ShouldAutoExit(GameTime gameTime)
{
if (_launchOptions.AutoExitAfter is TimeSpan autoExitAfter && gameTime.TotalGameTime >= autoExitAfter)
{
Exit();
return true;
}
return false;
}A script can launch the real game, let it run for a few seconds of real frames, and treat a clean exit as a pass. For example, dotnet run --project Platforms/DesktopVK -- --smoke-test-seconds 2 runs for two seconds and exits on its own.
NOTE
From chapter 12 the game loads the player profile when it starts and saves it when it changes, and a smoke run does the same. The file is profile.json in a LastPerimeter folder under your local application data folder, which is %LOCALAPPDATA%\LastPerimeter\profile.json on Windows.
In the course repository, <course-repo>/scripts/TestChapterProjects.ps1 uses this option (--smoke-test-seconds 0.75) to smoke-run every chapter snapshot on Windows. <course-repo>/scripts/test-chapters.sh covers the build-and-test half on Linux and macOS. Neither script is in your own project. The repository's CI workflow builds and tests the game in last-perimeter/ and every snapshot on each pull request.
The screenshots in this course were captured the same way. scripts/capture-chapter-screenshots.sh launches each chapter build on a virtual display, drives it with scripted key presses, and grabs frames at the moments the chapters describe.
Debugging advice
Visualise path segments, node endpoints, rasterised trail tiles, discovered BFS regions and the fuse position along the trail. The game becomes much easier to debug once invisible state is made visible. Three cheap techniques the chapter apps already use:
- the window title (
Window.Title = $"Last Perimeter | Lives {lives} | Claim {percent}%"), a HUD that costs one line, - the status line in the HUD (
GameSession.StatusMessage), set at every interesting transition, - temporary draws with
PrimitiveDrawing: a dot per path node, a rectangle per rasterised tile, a differently coloured fill per BFS region.
One platform note. The executables are built as WinExe, so on Windows Console.WriteLine has nowhere to go. Use System.Diagnostics.Debug.WriteLine and your IDE's output window, or temporarily change OutputType to Exe in the platform project. On Linux and macOS the console output appears in the terminal you ran dotnet run from.
How to judge your own work
Judge your work on architectural clarity, correctness of the maths and algorithms, and quality of testing. Judge it also on the quality of game feel and feedback, and on your ability to explain trade-offs rather than only present code.
Postmortem exercise
Walk through the capture regression as a formal RCA. The full analysis is in chapter 06:
- the PRD originally said a region with an enemy should not be claimed if no enemy-free option exists,
- the runtime later added a smallest-region fallback that can capture and eliminate an enemy,
- one symptom of "always return a region" has since been fixed in code: the partition guard in
AreaClaimingSystem.ProcessCompletedTrailnow returns null for degenerate trails, with the regression test above pinning it, - but the level-complete logic still only checks
ClaimedAreaPercentage >= WinClaimPercentage. That check sits inHandleClaimin the chapter 08 and 09 apps, and inCompleteTrailClaimin the final game, - therefore the game can eliminate the last enemy and still continue running.
That last tension is still live in the code. Eliminating every enemy is neither a win condition nor a loss condition, and simply leaves a quieter arena. It makes a good case study. The maths can be correct, a regression can be fixed and tested, and the product behaviour can still be unresolved. Ask: should the fix go in the solver, in CompleteTrailClaim, or in the design document first?
Chapter snapshot
The matching buildable project is DOCUMENTATION/LastPerimeter-Source/09-Testing-Debugging-And-Course-Extensions in the course repository, and its source and tests are identical to the chapter 08 build (only the folder README differs). No files change in this chapter, so there is nothing to copy. That is the point of the chapter. Run dotnet build and dotnet test from your LastPerimeter folder. The full suite of 45 tests should pass, covering every test file in the table above.
Checkpoint
- In your
LastPerimeterfolder, rundotnet test. 45 tests pass. If your count differs, run the same command in<course-repo>/DOCUMENTATION/LastPerimeter-Source/09-Testing-Debugging-And-Course-Extensions/and compare. - In your
LastPerimeterfolder, rundotnet run --project Platforms/DesktopVK -- --smoke-test-seconds 3. The window opens and closes by itself after three seconds. Then explain how you would script that into CI, and read<course-repo>/.github/workflows/lastperimeter-ci.ymlto see how the course builds and tests. That file is in the course repository, not in your project. - Break the partition guard on purpose. Open
Source/Systems/AreaClaimingSystem.cs, findProcessCompletedTrail, and changeregions.Count < 2toregions.Count < 1. Save the file, rundotnet test, and note exactly which test fails. Then change the line back toregions.Count < 2and rundotnet testagain to see 45 tests pass. - Write one new regression test of your own against a rule from chapters 05-07. Add it to the matching file under
Tests/Systems/(for exampleTests/Systems/TrailSystemTests.cs), rundotnet test, and justify what it pins down. - Add a temporary debug draw that marks every wall path node with a small circle. Open
Source/Game/LastPerimeterApp.cs, findDraw, and add this line directly above the_hudRenderer.Drawcall:foreach (Vector2 node in _gameSession.PlayableWallPath.Nodes) { PrimitiveDrawing.DrawFilledCircle(_spriteBatch, _pixel, node, 3f, Color.Yellow); }. Run the game withdotnet run --project Platforms/DesktopVKand count the circles. Make one capture with the arrow keys (the Controls table in chapter 03 lists every input) and count them again. Then delete the line you added.
Extensions
- incremental wall-path updates,
- advanced debug overlays,
- dynamic difficulty tuning,
- accessibility improvements,
- replay and capture-history playback (
GameSession.CaptureHistoryalready records every claim in order).
The final lesson
The deepest lesson of this project is:
great game systems come from giving each representation one clear responsibility, then connecting those representations deliberately.
That is the idea to take with you long after this project is finished. The advanced track (chapters 10-15) applies it to progression, enemies, powerups, menus, runs, and themes.

