Appearance
Chapter 13: Proving the Level
In Chapter 12: Events, Score and Feedback, you made the game talk back. You now have one complete level. The player can draw a trail, capture an area, score, lose a life and respawn. Each rule has its own tests, but you have only watched the rules work together by playing.
In this chapter, you prove that they work together. You grow the test helpers into a small language for scenarios, write four tests that play whole sequences, and time the capture solver. You also make the smoke run play a short scripted capture. You do not change the simulation. It stays exactly as it is, and that is the point.
| Figure 13-1: The chapter 13 result, a test run with 85 passing tests, including the four new scenarios. This is a drawn illustration, not a screenshot. |
Time: [TODO Simon: time estimate for chapter 13]
In this chapter, you will:
- Learn the four layers of testing in this course.
- Extend the test helpers so a scenario reads like a list of moves.
- Write scenario tests for a fuse death, two captures in a row, a loop and a repeated run.
- Check a wall invariant after a second capture.
- Prove that the same seed and the same input give the same result.
- Time the capture solver and read an allocation figure.
- Make the smoke run play a scripted capture, and fail with exit code 3 when none completes.
Requirements in this chapter
| ID | Short name |
|---|---|
| CAP-10 | Solving fits in a frame |
| NFR-01 | No per-frame heap allocation in hot paths |
| NFR-03 | Rules testable without a window (proved end to end) |
| PLT-04 | The smoke run plays a capture, for CI |
Four layers of testing
A test checks one kind of claim. Using one kind for everything leaves gaps, so this course uses four layers, shown in Figure 13-2. Each layer is cheaper and more exact than the one above it, and each sees less of the real game.
| Figure 13-2: Four layers of testing, from service tests to manual play |
- Service tests check one operation.
ScoreClaim_UsesTileCountis one. They are fast and they name the exact operation that broke. - Scenario tests drive
GameplaySimulation.Tickwith a script of moves and check what happened. They find rules that work alone but fail together, for example a capture and a fuse kill in the same frame. - The smoke run starts the real host, feeds it a scripted keyboard and plays one capture. It exits with code 0 only if the capture completed. It proves that the window, the graphics device, the input path and gameplay run together. It checks no other rule, and it cannot see what is on the screen.
- Manual play proves what no test can, which is how the game feels. It cannot be repeated exactly.
Visuals lie, as Chapter 03 said. The scenario layer is where this course answers that. The rules were built without a window, so a scenario test plays the real simulation at full speed with no graphics at all. This proves NFR-03, that every rule can be tested without a window.
Scenarios as scripts
A scenario is a script. It says "move right for four frames, then down for three, then do nothing", and then it checks the result. Two things make a script exact. The first is a fixed time step. ScriptedInput.Frame is 0.05 seconds, so a frame is always 0.05 seconds, however fast the test machine is. The second is that the helpers return every event the simulation raised, so the test can ask what happened as well as where things ended up.
ScriptedInput already has Run, which holds one input for a number of frames, RunUntil, which stops at the first event of a type, and DrawRectangleFromTopWall. This chapter adds one more word to the language, Move. It does the same as Run, but it reads as a verb on the simulation: sim.Move(ScriptedInput.Right, 4).
Invariants
An invariant is a statement that must be true after every step, not only at the end. For the wall path, three statements hold after any capture. The player stands on the path. Every node of the path joins at least two segments, so the path has no loose ends. Every node lies inside the arena.
The second scenario checks these after the second capture. A wrong path in the middle of a long run can be hidden by a later rebuild, so the habit is to check after each capture. The test here checks after two captures, and an Extension asks you to build on it.
Determinism
A run is deterministic when the same input always gives the same result. Two things can break that. One is real time, which varies. The other is an unseeded random number generator. The scenarios avoid both. The time step is fixed, and SimulationBuilder.Create(seed: 42) gives the simulation a Random built from the seed 42. Every random choice an enemy makes comes from that Random, which is requirement ENM-11. Two runs with the same seed and the same script must therefore end identically. Chapter 19 builds the daily challenge on this property.
Setting up the helpers
You add two small helpers before the scenarios. Open Tests/TestHelpers/ScriptedInput.cs. Add the following method to the ScriptedInput class, below the Run method. It is an extension method, which is why the first parameter has this. It lets you write sim.Move(...). New to extension methods? See the C# primer.
add-member Tests/TestHelpers/ScriptedInput.cs after=Run
csharp
public static List<GameEvent> Move(this GameplaySimulation simulation, InputState input, int frames) => Run(simulation, input, frames);Open Tests/TestHelpers/SimulationBuilder.cs. Add the following method to the SimulationBuilder class, below the Create method. It removes every enemy, so a scenario can test a rule with nothing else moving. Like Move, it is an extension method, and it returns the simulation so calls can be chained.
add-member Tests/TestHelpers/SimulationBuilder.cs after=Create
csharp
public static GameplaySimulation WithoutEnemies(this GameplaySimulation simulation)
{
simulation.Session.Enemies.Clear();
return simulation;
}The key things to note are:
Moveis a one-line wrapper. Its value is the name. A list ofMovecalls reads as a list of moves.WithoutEnemiesclears the enemy list on the session.SimulationBuilder.Createalready starts a level with no enemies unlesswithEnemiesistrue, soWithoutEnemiesis for a simulation that was built with enemies.- No test in this chapter calls
MoveorWithoutEnemies. The four scenarios callScriptedInput.Rundirectly. The helpers are for the Extensions and for your own scenarios. Extension 1 usesMoveto rewrite the stop mid trail scenario. Extension 2 usesWithoutEnemiesto check a capture with nothing else moving.
Writing the scenarios
The simulation is unchanged, so there is no stub and no red step for a missing body. The scenarios are red only if a rule is wrong. You still see one fail, in a tip below, because a test that has never failed has not proved anything.
A stop mid trail
Scenario: stop mid trail
- Plays: leave the wall, stop moving, and wait.
- Expects: the fuse warns, then the fuse costs one life, and the trail is cancelled.
- Requirements: FUS-02, FUS-05 and LIV-04, together.
In the Tests/Simulation folder, create a new file named LevelScenarioTests.cs and add the following code. The test moves right for 4 frames and down for 3 to leave the wall. New to lambdas? See the C# primer. It then holds no input until a LifeLost event appears, with a limit of 100 frames so a bug cannot loop for ever.
new-file Tests/Simulation/LevelScenarioTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Entities;
using LastPerimeter.Simulation;
using LastPerimeter.Tests.TestHelpers;
namespace LastPerimeter.Tests.Simulation;
public sealed class LevelScenarioTests
{
[Fact]
public void Scenario_StopMidTrail_FuseCostsALife()
{
GameplaySimulation sim = SimulationBuilder.Create();
ScriptedInput.Run(sim, ScriptedInput.Right, 4);
ScriptedInput.Run(sim, ScriptedInput.Down, 3);
List<GameEvent> events = ScriptedInput.RunUntil<LifeLost>(sim, ScriptedInput.Idle, 100);
Assert.Contains(events, e => e is FuseWarning);
Assert.Contains(events, e => e is LifeLost { LivesLeft: 2 });
Assert.Null(sim.Session.Player.CurrentTrail);
}
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 82.
The key things to note are:
RunUntil<LifeLost>stops as soon as the life is lost, so the events list ends at the moment that matters.- The test checks three results from three chapters.
FuseWarningis from Chapter 12,LifeLostfrom Chapter 11 and the cancelled trail from Chapter 07. LifeLost { LivesLeft: 2 }is a property pattern. It matches aLifeLostevent whoseLivesLeftis 2, which is 3 starting lives minus one. New to patterns? See the C# primer.
TIP
To see a scenario fail, open Tests/Simulation/LevelScenarioTests.cs and change LivesLeft: 2 to LivesLeft: 3. From the LastPerimeter folder, run dotnet test --filter Scenario_StopMidTrail_FuseCostsALife. The test fails and names the events it found. Change the value back and run the filter again before you go on.
Two captures in a row
Scenario: two captures in a row
- Plays: draw the standard rectangle, then draw a second shape from the new wall.
- Expects: two captures are recorded, and the wall path is still sound.
- Requirements: WAL-03, as an invariant.
Add the following test to the LevelScenarioTests class, below the Scenario_StopMidTrail_FuseCostsALife test. The first capture ends with the player on the new wall, which the test checks. The second shape then runs right, down and right. The three final assertions are the invariants.
add-member Tests/Simulation/LevelScenarioTests.cs after=Scenario_StopMidTrail_FuseCostsALife
csharp
[Fact]
public void Scenario_TwoCapturesInARow_KeepWallConsistent()
{
GameplaySimulation sim = SimulationBuilder.Create();
ScriptedInput.DrawRectangleFromTopWall(sim);
Assert.True(sim.Session.PlayableWallPath.Contains(sim.Session.Player.Position));
ScriptedInput.Run(sim, ScriptedInput.Right, 4);
ScriptedInput.Run(sim, ScriptedInput.Down, 4);
ScriptedInput.Run(sim, ScriptedInput.Right, 4);
Assert.Equal(2, sim.Session.CaptureHistory.Count);
PlayableWallPath path = sim.Session.PlayableWallPath;
Assert.True(path.Contains(sim.Session.Player.Position));
Assert.All(path.Nodes, node => Assert.True(path.GetConnectedSegmentCount(node) >= 2));
Assert.All(path.Nodes, node => Assert.True(sim.Arena.IsWithinBounds(node)));
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 83.
The key things to note are:
- The second capture starts from the position the first one left the player in. That position is the output of Chapter 09 and the input of this scenario.
Assert.Allruns one assertion for every node of the path. A single bad node fails the test and names itself.- The test checks properties of the path. It does not compare the path with a fresh rebuild from the grid, which is the strongest form of the invariant. An Extension asks you to add that.
A loop
Scenario: a loop
- Plays: draw a trail that crosses its own earlier leg.
- Expects: one capture, reported as a loop, with the enclosed tiles claimed and a tile outside them not claimed.
- Requirements: TRL-07, CAP-06.
Add the following test below the Scenario_TwoCapturesInARow_KeepWallConsistent test. The trail goes right, down, right, up, then left across the first downward leg. Crossing the trail closes the loop. The test checks the point (30, 30), which lies inside the loop, and the point (30, 10), which lies above it.
add-member Tests/Simulation/LevelScenarioTests.cs after=Scenario_TwoCapturesInARow_KeepWallConsistent
csharp
[Fact]
public void Scenario_LoopCapture_ClaimsInsideOfLoop()
{
GameplaySimulation sim = SimulationBuilder.Create();
ScriptedInput.Run(sim, ScriptedInput.Right, 4);
ScriptedInput.Run(sim, ScriptedInput.Down, 8);
ScriptedInput.Run(sim, ScriptedInput.Right, 4);
ScriptedInput.Run(sim, ScriptedInput.Up, 4);
List<GameEvent> events = ScriptedInput.Run(sim, ScriptedInput.Left, 6);
CaptureCompleted capture = Assert.Single(events.OfType<CaptureCompleted>());
Assert.True(capture.WasLoop);
Assert.True(sim.Arena.IsClaimedWorld(new Vector2(30, 30)));
Assert.False(sim.Arena.IsClaimedWorld(new Vector2(30, 10)));
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 84.
The key things to note are:
Assert.Singlefails if there are zero captures or two, so the scenario also proves that the loop is captured once.WasLoopis true because the capture ended at a crossing and not at a wall.- The claimed point and the unclaimed point are asked of the arena with
IsClaimedWorld, a Chapter 03 operation.
The same script twice
Scenario: the same script twice
- Plays: the same seed and the same moves, in two separate simulations.
- Expects: the same score, position, claimed percentage and enemy positions.
- Requirements: ENM-11, NFR-03.
Add the following test below the Scenario_LoopCapture_ClaimsInsideOfLoop test. The local function Play builds a simulation with enemies, seeded with 42, draws the rectangle and then waits 60 frames while the enemies move. The test calls it twice.
add-member Tests/Simulation/LevelScenarioTests.cs after=Scenario_LoopCapture_ClaimsInsideOfLoop
csharp
[Fact]
public void Scenario_ReplayingTheSameScript_GivesTheSameResult()
{
static GameplaySimulation Play()
{
GameplaySimulation sim = SimulationBuilder.Create(seed: 42, withEnemies: true);
ScriptedInput.DrawRectangleFromTopWall(sim);
ScriptedInput.Run(sim, ScriptedInput.Idle, 60);
return sim;
}
GameplaySimulation first = Play();
GameplaySimulation second = Play();
Assert.Equal(first.Session.Score, second.Session.Score);
Assert.Equal(first.Session.Player.Position, second.Session.Player.Position);
Assert.Equal(first.Session.ClaimedAreaPercentage, second.Session.ClaimedAreaPercentage);
Assert.Equal(first.Session.Enemies.Select(enemy => enemy.Position), second.Session.Enemies.Select(enemy => enemy.Position));
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 85.
The key things to note are:
- The local function is
static, so it cannot use any outer variable. Each call starts from nothing, which is what the test needs. - Enemy positions are compared as a sequence, built with a LINQ
Select. New to LINQ? See the C# primer. A single enemy that moved differently would fail the equality. - The test would fail if an enemy used
new Random()or the real clock. That makes it a guard on every later chapter that adds a random choice.
Timing the solver
The capture solver is the one operation that does real work in a single frame. It copies the grid, rasterises the trail, finds the regions and picks one. Requirement CAP-10 says this fits in a frame. At 60 frames per second a frame is about 16.7 milliseconds. A test that asserts a time would fail on a slow or busy machine, so the course measures it instead.
The measurement has two rules. Use a Release build, because a Debug build is slower and says nothing about the game. Run the solver many times, because a single run includes the cost of compiling the code the first time. The program below runs it 20 times to warm up and then 200 times to measure.
You build the measuring program in a scratch console project, outside your solution. Your solution stays as it is. The project lists the seven source files it needs from your LastPerimeter folder, so it uses your real solver.
In a terminal, from the folder that contains your LastPerimeter folder, run the following. The folder LastPerimeter-Timing then sits next to LastPerimeter.
text
mkdir LastPerimeter-TimingIn the LastPerimeter-Timing folder, create a new file named LastPerimeter-Timing.csproj and add the following code. The MonoGame.Framework.Native version must match the MonoGameVersion value in LastPerimeter/Directory.Packages.props, which is 3.8.6.1.
xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\LastPerimeter\Source\Data\Enums.cs" />
<Compile Include="..\LastPerimeter\Source\Data\GameConfig.cs" />
<Compile Include="..\LastPerimeter\Source\Data\ClaimResult.cs" />
<Compile Include="..\LastPerimeter\Source\Entities\Region.cs" />
<Compile Include="..\LastPerimeter\Source\Entities\Trail.cs" />
<Compile Include="..\LastPerimeter\Source\Systems\ArenaSystem.cs" />
<Compile Include="..\LastPerimeter\Source\Systems\AreaClaimingSystem.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MonoGame.Framework.Native" Version="3.8.6.1" />
</ItemGroup>
</Project>In the same LastPerimeter-Timing folder, create a new file named Program.cs and add the following code. The trail runs straight from the top wall to the bottom wall, which splits the full 231 by 138 grid into two regions.
csharp
using System.Diagnostics;
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
using LastPerimeter.Systems;
GameConfig config = new();
ArenaSystem arena = new(config);
AreaClaimingSystem solver = new(arena);
// A straight trail from the top wall to the bottom wall splits the full arena in two.
Rectangle bounds = arena.Bounds;
Trail trail = new();
trail.AddPoint(new Vector2(bounds.Left + 400, bounds.Top));
trail.AddPoint(new Vector2(bounds.Left + 400, bounds.Bottom));
trail.State = TrailState.Completed;
// Warm up, so the first call does not include the cost of compiling the code.
for (int i = 0; i < 20; i++)
{
solver.ProcessCompletedTrail(trail);
}
const int runs = 200;
double[] milliseconds = new double[runs];
long allocatedBefore = GC.GetAllocatedBytesForCurrentThread();
for (int i = 0; i < runs; i++)
{
long start = Stopwatch.GetTimestamp();
ClaimResult? result = solver.ProcessCompletedTrail(trail);
milliseconds[i] = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
if (result is null)
{
Console.WriteLine("The trail did not capture anything. Check the trail points.");
return;
}
}
long allocated = GC.GetAllocatedBytesForCurrentThread() - allocatedBefore;
Array.Sort(milliseconds);
Console.WriteLine($"Grid: {arena.GridWidth} x {arena.GridHeight} = {arena.TotalTileCount} tiles");
Console.WriteLine($"Median: {milliseconds[runs / 2]:0.00} ms, slowest: {milliseconds[^1]:0.00} ms over {runs} runs");
Console.WriteLine($"Allocated per call: {allocated / runs / 1024} KB");In PowerShell, from the LastPerimeter-Timing folder, run the following:
powershell
dotnet run -c ReleaseIn bash, from the LastPerimeter-Timing folder, run the following:
bash
dotnet run -c ReleaseThe first line should read Grid: 231 x 138 = 31878 tiles. The second line is the time, and the third is the memory. The numbers depend on your machine. Four runs on the machine that tested this chapter gave a median between 2.9 and 3.7 milliseconds, and about 3,265 KB allocated per call. Expect a median of a few milliseconds. A median under 16 milliseconds means the capture fits in a frame, which proves CAP-10.
The key things to note are:
- The median is a better measure than the average, because one slow run, such as a garbage collection pause, moves an average but not a median. The slowest run is printed so you can see the spread. On the test machine it ranged from 7 to 37 milliseconds, and the largest value came from the first, coldest run.
- A capture happens once per finished trail, not once per frame. A pause of a few milliseconds on that frame is acceptable. It would not be acceptable every frame.
- About 3 MB per capture is a lot of memory, mostly the copied grid, the tile sets and the region lists. NFR-01 forbids per-frame allocation in hot paths such as
Tick,UpdateandDraw. A capture is a rare event, so this cost is allowed. The figure tells you where to look first if a later chapter must reduce it.
When you have your numbers, you may delete the LastPerimeter-Timing folder. It is not part of your game.
Making the smoke run play the game
Until now the smoke run proved only that the window opens and closes. It stopped on the title scene and waited, because nothing pressed a key. In this section you make it play a short capture, and you make it fail when no capture happens.
The idea rests on a seam you built in Chapter 04: Input and Frame Time. InputManager takes an optional function that returns the keyboard state. When the function is missing, the manager reads the real keyboard. In smoke mode the host passes a function that returns whatever keys a script says are held at that moment. Everything after the seam runs as in real play: the scene, the simulation, the capture solver and the drawing. A run that completes a capture therefore proves that gameplay runs from input to capture, with nobody at the keyboard. New to Func? See the C# primer.
The script is a method, SmokeScript.At, that takes the time since the game started and returns the keys held. The player starts on the top-left corner of the wall and moves at 150 pixels per second, so 0.4 seconds is 60 pixels. The script draws a square and closes it on the wall:
| Time | Key held | What happens |
|---|---|---|
| 0.0 to 0.4 seconds | Right | The player walks 60 pixels along the top wall. |
| 0.4 to 0.8 seconds | Down | The player steps into the arena. The trail starts and runs 60 pixels down. |
| 0.8 to 1.2 seconds | Right | The trail runs 60 pixels across. |
| 1.2 to 1.6 seconds | Up | The trail returns to the wall. The capture completes and claims a 60 by 60 pixel region in the top-left corner. |
| After 1.6 seconds | None | The player stands still until the run exits. |
Three decisions keep the run reliable:
- The seed is fixed. In smoke mode the scene builds its
Randomfrom the seed 1, so the enemies move the same way every run. With a random seed an enemy could touch the trail, a life would be lost, and the run would fail on some runs and pass on others. A fixed seed applies the determinism you tested in this chapter to the whole host. - A missing capture exits with code 3. A run that exits with 0 after doing nothing proves nothing. The scene counts completed captures in
CaptureCount, andSmokeScript.Finishturns the count into the exit code. Any non-zero code fails a build server job, and 3 tells you the capture was the check that failed. - The run needs about 1.7 seconds. The script takes 1.6 seconds of game time. A shorter
--smoke-test-secondsvalue exits before the capture and returns 3 by design. The commands in this chapter use 3.
In the Source/Game folder, create a new file named SmokeScript.cs and add the following code. At reads the elapsed time and returns a KeyboardState built from one key. Finish returns the exit code and writes a message to the error stream when it is 3.
new-file Source/Game/SmokeScript.cs
csharp
using Microsoft.Xna.Framework.Input;
namespace LastPerimeter.Game;
// The scripted play used by the smoke run. The host feeds it to the input manager
// in place of the real keyboard, so every smoke run plays the same capture.
public static class SmokeScript
{
// A fixed seed, so the enemies behave the same way every time.
public const int Seed = 1;
// The smoke run writes its profile here, never to the player's real profile.
public static string ProfilePath { get; } = Path.Combine(Path.GetTempPath(), "LastPerimeter-smoke", "profile.json");
// The keys held at this moment. The player starts on the top-left corner of the wall
// and moves at 150 pixels per second, so 0.4 seconds is 60 pixels.
public static KeyboardState At(TimeSpan elapsed)
{
double seconds = elapsed.TotalSeconds;
// Along the top wall, 60 pixels to the right.
if (seconds < 0.4)
{
return new KeyboardState(Keys.Right);
}
// Step into the arena, which starts the trail, 60 pixels down.
if (seconds < 0.8)
{
return new KeyboardState(Keys.Down);
}
// Across, 60 pixels to the right.
if (seconds < 1.2)
{
return new KeyboardState(Keys.Right);
}
// Back up to the wall, which closes a 60 by 60 pixel region in the top-left corner.
if (seconds < 1.6)
{
return new KeyboardState(Keys.Up);
}
return new KeyboardState();
}
// Returns the process exit code: 0 when the scripted capture completed, otherwise 3.
public static int Finish(int captures)
{
if (captures > 0)
{
return 0;
}
Console.Error.WriteLine("Smoke test failed: the scripted capture did not complete.");
return 3;
}
}The key things to note are:
SeedandAtarestatic, so the host can passSmokeScript.Atto the input seam with no object to create.- The four
ifblocks are in time order, and the last line returns an emptyKeyboardState, which means no key is held. ProfilePathis not used yet. Chapter 16 uses it, so the smoke run never writes your real profile.
Now teach GameServices to accept the keyboard function. Open Source/Game/GameServices.cs. At the top of the file, add the following line below the using Microsoft.Xna.Framework.Graphics; line:
add-using Source/Game/GameServices.cs after=Microsoft.Xna.Framework.Graphics
csharp
using Microsoft.Xna.Framework.Input;Find this line in Source/Game/GameServices.cs:
find Source/Game/GameServices.cs type=GameServices
csharp
public GameServices(GameConfig config, GraphicsDevice graphicsDevice, Action<string> setWindowTitle)Replace it with the following line. The new last parameter is optional, so no existing caller changes. New to ? on a type? See the C# primer.
csharp
public GameServices(GameConfig config, GraphicsDevice graphicsDevice, Action<string> setWindowTitle, Func<KeyboardState>? readKeyboard = null)Find this line in the same constructor:
find Source/Game/GameServices.cs type=GameServices
csharp
Input = new InputManager();Replace it with the following line. When readKeyboard is null, the input manager reads the real keyboard as before.
csharp
Input = new InputManager(readKeyboard);Next, teach the gameplay scene to take a seed and to count captures. Open Source/Scenes/GameplayScene.cs. Find this line:
find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
public GameplayScene(GameServices services)Replace it with the following lines. They add the CaptureCount property above the constructor, and the constructor gains an optional seed parameter.
csharp
// How many captures have completed. The smoke run reads it.
public int CaptureCount { get; private set; }
public GameplayScene(GameServices services, int? seed = null)In the same constructor, find this line:
find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
_simulation = new GameplaySimulation(services.Config, session, new Random());Replace it with the following line. Without a seed, the scene behaves as before and builds an unseeded Random.
csharp
_simulation = new GameplaySimulation(services.Config, session, seed is null ? new Random() : new Random(seed.Value));In the scene's event handling, find this line:
find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
case CaptureCompleted:Add the following line directly below it:
csharp
CaptureCount++;In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 85. This is a build checkpoint. The host does not use the new members yet.
Last, change the host. Open Source/Game/LastPerimeterApp.cs. Find this line in the LastPerimeterApp class:
find Source/Game/LastPerimeterApp.cs type=LastPerimeterApp
csharp
private readonly Lazy<GameServices> _services;Add the following two fields directly below it. _smokeScene holds the scene the smoke run plays, so the host can read its capture count at exit. _elapsed holds the time since the game started.
csharp
private GameplayScene? _smokeScene;
private TimeSpan _elapsed;In the constructor, find this line:
find Source/Game/LastPerimeterApp.cs type=LastPerimeterApp
csharp
_services = new Lazy<GameServices>(() => new GameServices(_config, GraphicsDevice, title => Window.Title = title));Replace it with the following lines. In smoke mode the keyboard function reads SmokeScript.At at the stored time. Otherwise it is null, and the real keyboard is used.
csharp
_services = new Lazy<GameServices>(() => new GameServices(_config, GraphicsDevice, title => Window.Title = title,
_launchOptions.AutoExitAfter is null ? null : () => SmokeScript.At(_elapsed)));In the LoadContent method, find this line:
find Source/Game/LastPerimeterApp.cs type=LastPerimeterApp
csharp
_scenes.Change(new TitleScene(_services.Value));Replace it with the following lines. Smoke mode skips the title scene and starts gameplay with the fixed seed. A normal run starts on the title scene as before.
csharp
if (_launchOptions.AutoExitAfter is null)
{
_scenes.Change(new TitleScene(_services.Value));
}
else
{
// Smoke mode skips the menus and plays the scripted capture.
_smokeScene = new GameplayScene(_services.Value, SmokeScript.Seed);
_scenes.Change(_smokeScene);
}In the Update method, find this line:
find Source/Game/LastPerimeterApp.cs type=LastPerimeterApp
csharp
InputState input = _services.Value.Input.GetCurrentInput();Add the following line directly above it, so the stored time is current when the input is read:
csharp
_elapsed = gameTime.TotalGameTime;In the ShouldAutoExit method, find this line:
find Source/Game/LastPerimeterApp.cs type=LastPerimeterApp
csharp
Exit();Add the following line directly above it. It sets the process exit code before the game exits. New to ?. and ??? See the C# primer.
csharp
Environment.ExitCode = SmokeScript.Finish(_smokeScene?.CaptureCount ?? 0);In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 85. The count does not change, because you added no test.
The key things to note are:
- The host changes by a few lines. It stores the time, hands the script to the input seam and reads one number at exit. It still holds no game rules.
_smokeScene?.CaptureCount ?? 0means "the count, or 0 if no scene was started". A normal run never uses the result, because the exit code only matters for the smoke run.- The smoke change leaves the simulation alone. The test count stays at 85.
Debugging advice
When a rule fails, follow the same order each time.
- Write the scenario that fails. Reproduce the bug as a script before you touch any code. A bug you can replay is half fixed.
- Run only that scenario with a filter, for example
dotnet test --filter Scenario_LoopCapture_ClaimsInsideOfLoop. A short run keeps the loop of change and check fast. - Print the events. The list returned by
Runsays what the simulation did, in order. A missing or an extra event usually names the rule. - Narrow the script with
RunUntil. Stop at the event before the one you suspect, and inspectsim.Sessionthere. - Fix the service, and add a service test for the exact promise that was broken. The scenario stays as the guard.
- Run the whole suite once more with
dotnet test.
Running the tests
In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 85. The 85 tests are the 81 from earlier chapters and the 4 new scenarios.
| Test | Proves |
|---|---|
Scenario_StopMidTrail_FuseCostsALife | FUS-02, FUS-05 and LIV-04 together |
Scenario_TwoCapturesInARow_KeepWallConsistent | WAL-03 as an invariant |
Scenario_LoopCapture_ClaimsInsideOfLoop | TRL-07, CAP-06 |
Scenario_ReplayingTheSameScript_GivesTheSameResult | ENM-11, NFR-03 |
CAP-10 and NFR-01 are proved by the timing run above, and PLT-04 by the smoke run below.
Running the game
The smoke run starts the real game in gameplay with the seed 1, plays the scripted capture, and exits by itself. From the LastPerimeter folder, run dotnet build once. Then run one of the following, and check the exit code straight after it.
In PowerShell, from the LastPerimeter folder, run the following. The second line prints the exit code.
powershell
dotnet run --project Platforms/DesktopVK -- --smoke-test-seconds 3
$LASTEXITCODEIn bash, from the LastPerimeter folder, run the following. The second line prints the exit code.
bash
dotnet run --project Platforms/DesktopVK -- --smoke-test-seconds 3
echo $?A window opens on the arena, not on the title screen. The player walks along the top wall, leaves it and returns, and a square in the top-left corner fills in. After three seconds the window closes without a key press and the exit code is 0, which proves PLT-04. The window and the picture need a screen. The exit code does not, and neither do the four scenario tests, so you can confirm the rules without looking.
TIP
To see the failure path, run the same command with --smoke-test-seconds 1. The game exits before the capture is complete, prints Smoke test failed: the scripted capture did not complete. and the exit code is 3. Run the command with 3 again before you go on.
A continuous integration job can use the same command. The step below is for reading only, because your project has no workflow file. It needs a machine with a graphics driver, so many hosted build machines run the tests and skip this step.
yaml
- name: Smoke run
run: dotnet run --project Platforms/DesktopVK -- --smoke-test-seconds 3Now play one level by hand. Seeing the window and hearing the game are the checks no script makes for you. From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen. Walk the wall with the arrow keys, draw a rectangle and capture it. Then leave the wall and stop with every key released until the fuse costs a life. Compare what you saw with the scenario names. Each one describes something you just did, and each one now runs in a fraction of a second without a window.
Close the window with its close button. The next section is optional. It replaces your files with the chapter 13 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 13 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/13-Proving-The-Level"
Remove-Item -Recurse -Force Source, Tests
Copy-Item -Recurse "$snapshot/Source" Source
Copy-Item -Recurse "$snapshot/Tests" TestsIn 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/13-Proving-The-Level"
rm -rf Source Tests
cp -r "$snapshot/Source" Source
cp -r "$snapshot/Tests" TestsThen run dotnet test from the LastPerimeter folder and check for Passed: 85.
Common mistakes
- A scenario fails with a position that is slightly different. The script uses a different frame count from the one in the chapter. Every
Runcount matters, because a frame moves the player a fixed distance. - The replay scenario fails. Something random is not coming from the injected
Random, or the enemies were built without the seed. Check that the test callsSimulationBuilder.Create(seed: 42, withEnemies: true). - The build says
Moveis not found. The method is missing fromScriptedInput, or thethiskeyword was left off the first parameter. Withoutthisit is not an extension method. - The timing program says the trail did not capture anything. The trail points are outside the arena, or
trail.Statewas not set toCompleted. Check the twoAddPointlines. - The timing project does not restore. The
MonoGame.Framework.Nativeversion differs from the one inDirectory.Packages.props, or the machine has no access to NuGet. - The timing is far above 16 milliseconds. You ran without
-c Release. A Debug build is much slower.
Conclusion
In this chapter, you accomplished the following:
- Learned the four layers of testing and what each one proves.
- Extended the helpers so a scenario reads as a list of moves.
- Wrote four scenario tests that play whole sequences through the real simulation.
- Checked a wall invariant and proved that a run is deterministic.
- Timed the solver and read an allocation figure.
- Made the smoke run play a scripted capture and exit with code 3 when none completes.
The tests now prove NFR-03 end to end, and the timing run proves CAP-10, and the smoke run proves PLT-04 by playing a capture. NFR-01 is checked by measurement and code review. The rules that earlier chapters could only check by playing are now tested. This closes Part 2. In the next chapter, Chapter 14: Levels and Difficulty, you replace the single level with a roster of enemies and a goal that grows with each level.
Test Your Knowledge
What can a scenario test catch that a service test cannot?
Answer
Rules that interact in the wrong order, such as a capture and a fuse kill in the same frame. A service test calls one operation, so it never sees two rules meet.
Why does a scenario use a fixed time step instead of real time?
Answer
So the same script always produces the same frames. Real time varies from run to run, and then a position or a fuse could differ by a frame.
Why check the wall invariant after every capture instead of once at the end?
Answer
A wrong path in the middle can be repaired by a later rebuild, and the final check then passes. Checking after each capture catches the bug where it happens.
Why is it acceptable that the solver allocates about 3 MB, when NFR-01 forbids per-frame allocation?
Answer
A capture happens once per finished trail, not once per frame. NFR-01 is about hot paths that run every frame, such as
Tick,UpdateandDraw.Why does the smoke run exit with code 3 when no capture completed, instead of code 0?
Answer
A run that exits with 0 after doing nothing proves nothing. The non-zero code makes a build server job fail, so a broken input path or a stuck scene cannot pass unnoticed.
Extensions
- Rewrite
Scenario_StopMidTrail_FuseCostsALifewithsim.Move(...)instead ofScriptedInput.Run. Does it still read clearly? - Add a scenario that builds a simulation with enemies, calls
WithoutEnemies(), and checks that a capture reports no eliminated enemies. - Add a helper that builds a fresh wall path from the arena grid, and compare it with
sim.Session.PlayableWallPathafter each capture. This is the strongest form of the invariant. - Change a key in
SmokeScript.Atso the player never returns to the wall. Run the smoke command and confirm the exit code is 3, then restore the key. - Take a bug you met while following the course. Write the scenario that shows it, run it with a filter, and keep it as a guard. Then write a short note on the root cause: what broke, why the earlier tests missed it, and which test now catches it.

