Appearance
Chapter 06 - Capture System, Capturing Logic, and Region Solving
Where this chapter fits: a completed trail finally changes the world. The solver decides which side of the trail is captured, the grid records it, the claimed area is drawn, and the wall path is rebuilt around what is left. This is the hardest algorithmic chapter and the one where chapters 02, 04, and 05 meet.
Time: [TODO Simon: time estimate for chapter 06]
A capture in the chapter 06 build: the trail went down the left wall, across, and down to the bottom wall. The smaller (left) region was claimed, the fill was drawn, and the light-grey wall outline was rebuilt around the remaining region.
Prerequisites
Chapters 01-05. You need the tile grid (chapter 02), the wall path rebuild (chapter 04), and completed trails (chapter 05).
Learning objectives
By the end of this chapter you should be able to:
- rasterise a world-space trail into grid cells with a Bresenham-style walk (a line algorithm that steps along one axis and tracks an error term),
- discover disconnected regions with BFS and state its complexity,
- implement the region-selection rule pipeline, including the partition guard for degenerate trails (trails that enclose nothing),
- apply a
ClaimResultto the live arena and rebuild the wall path in the right order, - explain (via the root-cause analysis, or RCA) how a rules change in the solver rippled into a level-completion bug, and pass the chapter's 27 tests.
Code anchors
Source/Systems/AreaClaimingSystem.csSource/Data/ClaimResult.cs,Source/Entities/Region.csSource/Rendering/ClaimedAreaRenderer.cs(used here, explained in chapter 08)Source/Game/LastPerimeterApp.cs(chapter 06 staged version)Tests/Systems/AreaClaimingSystemTests.cs
The capture system in one sentence
The capture system starts when the player leaves the playable wall path and records a temporary trail. It resolves a completed trail into captured and remaining regions, applies the result to the arena and removes any trapped enemies. Only then does it rebuild the next playable wall path.
Capture lifecycle
The whole system is a strict runtime sequence. The solver is only one stage inside it:
This ordering is part of the lesson. The path is rebuilt only after the claim is finalised, exactly as the restart plan in the product requirements document demanded (the PRD, DOCUMENTATION/Plan/QIX_GAME_PRD.md).
The solving pipeline
The implementation is a three-stage solver with one guard:
- rasterise the completed trail into grid cells,
- find disconnected unclaimed regions, and bail out (return null) unless the trail produced at least two,
- choose which region becomes captured.
This stays clean, testable and easy to reason about while each stage remains separate. The orchestration is short:
csharp
public ClaimResult? ProcessCompletedTrail(Trail completedTrail, IReadOnlyList<Vector2>? enemies = null)
{
TileState[,] tempGrid = _arenaSystem.CloneGrid();
HashSet<Point> trailTiles = RasterizeTrailToGrid(completedTrail);
foreach (Point tile in trailTiles)
{
if (_arenaSystem.IsValidGridPoint(tile))
{
tempGrid[tile.X, tile.Y] = TileState.Boundary;
}
}
// A valid capture must split the playable space into at least two regions.
// A degenerate trail (for example one drawn out and straight back along the
// same line) encloses nothing, and without this guard the smallest-region
// fallback would select the entire arena.
List<Region> regions = FindRegions(tempGrid);
if (regions.Count < 2)
{
return null;
}
RegionSelection? selection = SelectRegionToClaim(regions, enemies ?? Array.Empty<Vector2>());
if (selection is null)
{
return null;
}
Region capturedRegion = selection.Region;
Region remainingRegion = new();
foreach (Region region in regions)
{
if (ReferenceEquals(region, capturedRegion))
{
continue;
}
remainingRegion.Tiles.AddRange(region.Tiles);
}
return new ClaimResult(capturedRegion, remainingRegion, trailTiles.ToList(), selection.EliminatedEnemyIndexes);
}Note the first line: the system clones the arena grid before solving. That lets the algorithm experiment safely, because failed solves do not corrupt live state and unit tests can inspect deterministic intermediate behaviour. The live update only happens once the result is known.
Stage 1 - Rasterising the trail
The trail exists in world space as line segments. The claim solver works on the tile grid. That means the trail has to become a blocking line in grid space first.
csharp
private HashSet<Point> RasterizeTrailToGrid(Trail trail)
{
HashSet<Point> tiles = new();
for (int index = 0; index < trail.Points.Count - 1; index++)
{
if (!_arenaSystem.TryWorldToGrid(trail.Points[index], out Point start) || !_arenaSystem.TryWorldToGrid(trail.Points[index + 1], out Point end))
{
continue;
}
foreach (Point point in RasterizeLine(start, end))
{
if (_arenaSystem.IsValidGridPoint(point))
{
tiles.Add(point);
}
}
}
return tiles;
}
private static IEnumerable<Point> RasterizeLine(Point start, Point end)
{
int x0 = start.X;
int y0 = start.Y;
int x1 = end.X;
int y1 = end.Y;
int dx = Math.Abs(x1 - x0);
int sx = x0 < x1 ? 1 : -1;
int dy = -Math.Abs(y1 - y0);
int sy = y0 < y1 ? 1 : -1;
int err = dx + dy;
while (true)
{
yield return new Point(x0, y0);
if (x0 == x1 && y0 == y1)
{
yield break;
}
int errorTwice = 2 * err;
if (errorTwice >= dy)
{
err += dy;
x0 += sx;
}
if (errorTwice <= dx)
{
err += dx;
y0 += sy;
}
}
}Why rasterisation matters
Without rasterisation, flood fill leaks through what looks visually like a closed line. This is one of the classic bugs of the genre. The player sees a closed shape, the algorithm sees a gap, and the wrong region gets claimed.
Maths: Bresenham-style line stepping
You do not need to memorise the implementation. You should understand three points: a dominant axis is stepped through, an accumulated error term decides when the secondary axis advances, and every touched grid cell is emitted. The output is an 8-connected line, which allows diagonal steps. The flood fill in stage 2 only walks 4-neighbours, so a region can never slip through a diagonal step. The player moves in cardinal directions, so most trail segments are straight rows or columns. The walk handles both.
Stage 2 - Region discovery with BFS
Once the trail tiles are marked as temporary boundary cells, the remaining unclaimed cells form one or more disconnected regions.
csharp
private List<Region> FindRegions(TileState[,] tempGrid)
{
bool[,] visited = new bool[_arenaSystem.GridWidth, _arenaSystem.GridHeight];
List<Region> regions = new();
for (int x = 0; x < _arenaSystem.GridWidth; x++)
{
for (int y = 0; y < _arenaSystem.GridHeight; y++)
{
if (visited[x, y] || tempGrid[x, y] != TileState.Unclaimed)
{
continue;
}
Region region = new();
Queue<Point> queue = new();
Point start = new(x, y);
queue.Enqueue(start);
visited[x, y] = true;
while (queue.Count > 0)
{
Point point = queue.Dequeue();
region.Tiles.Add(point);
foreach (Point neighbor in GetNeighbors(point))
{
if (!_arenaSystem.IsValidGridPoint(neighbor) || visited[neighbor.X, neighbor.Y] || tempGrid[neighbor.X, neighbor.Y] != TileState.Unclaimed)
{
continue;
}
visited[neighbor.X, neighbor.Y] = true;
queue.Enqueue(neighbor);
}
}
regions.Add(region);
}
}
return regions;
}Why BFS works well here
The grid is a graph: every unclaimed tile is a node, every orthogonal adjacency is an edge. That makes connected-region discovery a standard graph problem.
Complexity
Let V be the number of tiles and E the number of orthogonal adjacency links. BFS is O(V + E). Because E is proportional to V on a four-neighbour grid, the solve is effectively linear in the size of the arena (31,878 tiles). A Release-build measurement on the full arena gave about 3.6 ms per ProcessCompletedTrail call, which is fine because it runs once per capture, not every frame. This is one reason the grid model works so well.
The partition guard
Between discovery and selection sits the most important correctness rule in the file. A trail that does not split the playable space into at least two regions enclosed nothing, so there is nothing to claim:
csharp
List<Region> regions = FindRegions(tempGrid);
if (regions.Count < 2)
{
return null;
}Without this guard, an out-and-back trail leaves one region (the whole arena) and the smallest-region fallback would happily capture all of it in one move. ProcessCompletedTrail_ReturnsNull_WhenTrailDoesNotPartitionArena in AreaClaimingSystemTests is the regression test that keeps this honest.
When the solver returns null, the app must still recover gracefully. A loop endpoint can sit mid-arena, so the chapter app returns the player to the wall anchor where the trail began:
csharp
if (completedTrail is not null && claimResult is null)
{
// The trail enclosed nothing; return the player to the wall
// anchor where the trail began and discard the trail.
_gameSession.Player.Position = completedTrail.Points[0];
_gameSession.Player.CurrentTrail = null;
_fuseSystem.Reset();
}Stage 3 - Selecting the captured region
Selection is an explicit, ordered rule pipeline. The regions are analysed to find which enemies sit in which region, then sorted smallest-first. Each rule then gets a chance to decide:
csharp
_selectionRules =
[
TrySelectEnemyFreeRegion,
TrySelectSmallestRegion,
];
private static RegionSelection? TrySelectEnemyFreeRegion(IReadOnlyList<RegionAnalysis> analyses)
{
RegionAnalysis? enemyFreeRegion = analyses.FirstOrDefault(analysis => analysis.EnemyIndexes.Count == 0);
return enemyFreeRegion is null
? null
: new RegionSelection(enemyFreeRegion.Region, Array.Empty<int>());
}
private static RegionSelection? TrySelectSmallestRegion(IReadOnlyList<RegionAnalysis> analyses)
{
RegionAnalysis? smallestRegion = analyses.FirstOrDefault();
return smallestRegion is null
? null
: new RegionSelection(smallestRegion.Region, smallestRegion.EnemyIndexes);
}Because analyses is pre-sorted by tile count, the rules read as plain English:
- prefer a region with no enemy (the smallest such region, since the list is sorted),
- otherwise take the smallest region anyway and mark its enemies for elimination.
A consequence worth saying out loud: if the enemy happens to sit in the small region you cut off, the large enemy-free region is captured instead. Cutting a corner with the enemy inside it can hand you 80% of the arena in one move. That is the enemy-free rule working as designed, and chapter 07's checkpoint asks you to see it happen.
The solver encodes design intent as well as maths. Enemies protect the region they occupy. Smaller safe regions are the ones the player carved away. The fallback rule is a product decision, not an implementation detail.
What changed from the original capture rule
The original capture rule in the PRD was stricter. It claimed an enemy-free region if one existed, and claimed nothing if both sides contained enemies.
The current runtime deliberately diverges. AreaClaimingSystem falls back to the smallest region even when it contains an enemy, and returns those contained enemy indexes so the app can remove them after the claim is committed. In the final game that removal lives in LastPerimeterApp.CompleteTrailClaim. The chapter apps do the same work inline in Update. Be precise about names here. The method on LastPerimeterApp is CompleteTrailClaim, and ApplyClaimResult is the grid-write method on ArenaSystem.
That gives two truths to hold together. The classic rule explains the original design intent, and the shipped rule explains the current game behaviour. Without that context, you would read the code as a bug instead of as an explicit rules update.
RCA: why the system diverged and why the game did not finish
This postmortem links architecture, rules and game-state outcomes. Chapter 09 turns it into an exercise.
Root cause 1: rules drift from the original capture contract. The PRD described enemy presence as a hard blocker. The code added a fallback (TrySelectSmallestRegion) that captures the smallest region even if it contains an enemy, because the solver was optimised for always returning a deterministic region. In isolation that looks harmless, but at the game-rule level it is a meaningful rules change. The "always return something" instinct has since been partially walked back: the partition guard restores the "claim nothing" outcome for trails that never partitioned the space. What remains, intentionally, is the smallest-region fallback when the trail genuinely splits the arena and both regions contain enemies.
Root cause 2: enemy elimination was added without a matching completion rule review. Once the solver started returning EliminatedEnemyIndexes, the app began removing trapped enemies. But level completion still only checks ClaimedAreaPercentage >= WinClaimPercentage. So a capture can remove the last enemy, the claimed area can still be below the win threshold, and the game continues in a quiet arena. The bug was not in the solver, but in the mismatch between an updated capture rule and an unchanged end-of-level rule.
Root cause 3: separation of concerns was correct, but product rules were not re-synchronised. Separating trail solving, arena mutation, enemy removal, and path rebuilding fixed the earlier hybrid failures. Once the systems were cleanly separated, a higher-level rule review was still needed. What does capturing an enemy mean? Is elimination a bonus, a fallback or a win condition? Which system owns the final decision to complete the level?
Takeaway: many gameplay bugs are not algorithm failures, but contract failures between the design document, the solver rules and the outer game-state transitions. That is exactly why capture-system chapters should include both algorithms and rule ownership.
Seeing the claim: ClaimedAreaRenderer
A claim that only exists in the grid is invisible. ClaimedAreaRenderer (added to the build in this chapter, explained as a performance lesson in chapter 08) paints every ClaimedByPlayer tile into a cached texture. The app has to tell it when the grid changed:
csharp
_claimedAreaRenderer?.MarkDirty();The app calls that exactly once per successful capture, right after ApplyClaimResult. In Draw, _claimedAreaRenderer.Draw(_spriteBatch) goes between the arena and the trail.
_claimedAreaRenderer.Prepare() runs before GraphicsDevice.Clear. A rebuild switches render targets, which must not happen inside an open batch.
The key maths connections
This chapter connects several ideas into one chain. World space trail points become a grid space rasterised boundary. Graph traversal finds connected regions. Rule-based selection makes the final claim. State application writes the result back to the live arena. Each representation has a clear job.
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.
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/06-Capture-System-Capturing-Logic-And-Region-Solving/Source", "<course-repo>/DOCUMENTATION/LastPerimeter-Source/06-Capture-System-Capturing-Logic-And-Region-Solving/Tests" .In bash:
bash
cp -R "<course-repo>/DOCUMENTATION/LastPerimeter-Source/06-Capture-System-Capturing-Logic-And-Region-Solving/Source" "<course-repo>/DOCUMENTATION/LastPerimeter-Source/06-Capture-System-Capturing-Logic-And-Region-Solving/Tests" .That copy brings in these files. The listings in this chapter show the parts worth studying, not every line.
New files:
Source/Rendering/ClaimedAreaRenderer.csSource/Systems/AreaClaimingSystem.csTests/Systems/AreaClaimingSystemTests.cs
Replaced files:
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 - Construct the solver and the renderer
Open Source/Game/LastPerimeterApp.cs. Initialize now constructs _areaClaimingSystem = new AreaClaimingSystem(_arenaSystem). LoadContent now constructs _claimedAreaRenderer = new ClaimedAreaRenderer(_arenaSystem!, GraphicsDevice, _pixel, _config.ClaimedColor). The renderer needs the graphics device for its render target, which is why it cannot be built in Initialize.
Step 3 - Hand the completed trail to the solver
Open Source/Game/LastPerimeterApp.cs and find Update. The two completion branches from chapter 05 now hand the completed trail to the solver instead of discarding it:
csharp
ClaimResult? claimResult = null;
Trail? completedTrail = null;
if (_trailSystem.CanCompleteOnPath(intendedPosition, _gameSession.PlayableWallPath))
{
_gameSession.Player.Position = _gameSession.PlayableWallPath.Snap(intendedPosition);
completedTrail = _trailSystem.Complete(_gameSession.Player.Position);
claimResult = _areaClaimingSystem.ProcessCompletedTrail(completedTrail);
}
else if (_trailSystem.TryGetSelfIntersection(intendedPosition, out Vector2 loopIntersection))
{
_gameSession.Player.Position = loopIntersection;
completedTrail = _trailSystem.Complete(loopIntersection);
claimResult = _areaClaimingSystem.ProcessCompletedTrail(completedTrail);
}
else if (_trailSystem.CanAdvance(intendedPosition, _arenaSystem, direction, _gameSession.Player.CurrentDirection))
{
// unchanged from chapter 05
}Step 4 - Null-claim recovery and the apply block
Open Source/Game/LastPerimeterApp.cs and stay in Update. After the branches come the null-claim recovery (the listing in "The partition guard" above) and the apply block. The order inside the apply block is the lifecycle diagram made concrete:
csharp
if (claimResult is not null)
{
_arenaSystem.ApplyClaimResult(claimResult);
_gameSession.ClaimedAreaPercentage = _arenaSystem.GetClaimedPercentage();
_gameSession.CaptureHistory.Add(new CapturedZone(_gameSession.CaptureHistory.Count + 1, claimResult.CapturedRegion.Tiles, false));
_gameSession.PlayableWallPath = _wallSystem.RebuildPlayablePath(_arenaSystem);
_gameSession.Player.Position = _gameSession.PlayableWallPath.Snap(_gameSession.Player.Position);
_claimedAreaRenderer?.MarkDirty();
_gameSession.Player.CurrentTrail = null;
_fuseSystem.Reset();
}The order is grid first, percentage second, history third, path rebuilt fourth, player snapped onto the new path fifth and renderer told sixth. The trail and the fuse are cleared last.
Step 5 - Draw the claimed area
Open Source/Game/LastPerimeterApp.cs and find Draw. It now calls _claimedAreaRenderer.Prepare() just before GraphicsDevice.Clear, and _claimedAreaRenderer.Draw(_spriteBatch) between the arena and the trail. Dispose now disposes the renderer.
Step 6 - Read the tests
Open Tests/Systems/AreaClaimingSystemTests.cs. It covers smaller-region preference, enemy avoidance, the partition guard, and the both-sides-have-enemies fallback.
Step 7 - Build, test, run
Run these commands from your LastPerimeter folder:
bash
dotnet build
dotnet test
dotnet run --project Platforms/DesktopVKdotnet test reports 27 passing tests.
The last command opens the game window. Press Escape to close it.
Chapter snapshot
The matching buildable project is DOCUMENTATION/LastPerimeter-Source/06-Capture-System-Capturing-Logic-And-Region-Solving; build and test it standalone with dotnet build and dotnet test. This chapter stages AreaClaimingSystemTests (smaller-region preference, enemy avoidance, the partition guard, and the both-sides-have-enemies fallback), bringing the suite to 27 passing tests.
Checkpoint
| a hairpin: out, one sideways step, back | the sideways step spanned a tile, so a sliver was enclosed and claimed |
- In your
LastPerimeterfolder, rundotnet test. 27 tests pass, includingProcessCompletedTrail_ReturnsNull_WhenTrailDoesNotPartitionArena. If your count differs, run the same command in<course-repo>/DOCUMENTATION/LastPerimeter-Source/06-Capture-System-Capturing-Logic-And-Region-Solving/and compare. - Run the game with
dotnet run --project Platforms/DesktopVK. Walk along a wall with the arrow keys (the Controls table in chapter 03 lists every input). Press the arrow that points into the arena to leave the wall, then turn towards the nearest side wall and keep going until you reach it. You have cut a corner off the arena. The smaller side fills with the claimed colour and the wall path redraws around the remaining space, as in the screenshot at the top of the chapter. - Draw a hairpin. From the bottom wall, hold Up to go out, tap Left or Right once, then hold Down to come back to the wall. Direct reversal is blocked by chapter 05's no-backtrack rule. If the sideways step spanned at least one 4 px tile, you enclose a sliver and the solver correctly claims it, as in the screenshots above. If it was thinner than a tile, the two lines rasterise into the same or adjacent tiles. Nothing is enclosed, the guard returns null, and you return to the anchor with nothing claimed. That second outcome needs a single-frame tap, so treat the unit test, not the keyboard, as the reliable check for the guard.
- Explain to a partner why the player is snapped onto the new path after a claim rather than left where the trail ended.
What you should have now
You now have:
- trail rasterisation,
- temporary boundary marking,
- BFS region discovery,
- the partition guard and enemy-aware region selection,
- application of
ClaimResultback to the arena.
Common mistakes
- tiny gaps in the rasterised trail,
- diagonal neighbour checks accidentally connecting separated regions,
- degenerate out-and-back trails that leave only one region (now caught by the partition guard),
- mixing live arena state with temporary solver state,
- using world coordinates when grid coordinates are required,
- claiming the region with an enemy because selection rules were vague,
- removing an enemy during capture without revisiting the level-complete rules,
- rebuilding movement state before the claim result is fully finalised.
Extensions
- Visualise each discovered region in a different colour before committing the claim.
- Compare BFS and DFS implementations.
- Change tile size and measure its impact on visual quality and solver cost.
- Extend selection rules for multiple enemies or future enemy types.

