Appearance
Chapter 04 - The Playable Wall Path Node System
Where this chapter fits: free movement from chapter 03 becomes movement on the wall. The wall is no longer four hand-built segments: it is derived from the tile grid, and it will be derived again after every capture. This is the chapter the whole architecture rests on.
Time: [TODO Simon: time estimate for chapter 04]
Path-constrained movement in the chapter 04 build: the player starts at the top-left node and slides along the outline. Pressing toward the interior does nothing.
Prerequisites
Chapters 01-03 (tile grid, TileState, cardinal movement, deltaTime). This chapter leans on the grid model from chapter 02 more than any other.
Learning objectives
By the end of this chapter you should be able to:
- derive the safe wall outline from the tile grid using a local four-neighbour face test,
- merge collinear face segments and explain why merging matters,
- implement tolerance-based containment and snapping on axis-aligned segments, and explain how they let the player turn corners,
- constrain player movement to the derived path with
TryMoveAlongPath, and say precisely what that method does and does not check, - justify full-rebuild-after-claim over incremental path mutation, and pass the chapter's 12 tests.
Code anchors
Source/Systems/WallSystemV2.csSource/Entities/PlayableWallPath.csSource/Systems/MovementSystem.cs(TryMoveAlongPath)Tests/Systems/PlayableWallPathTests.cs,PlayableWallPathTraversalTests.cs,WallSystemV2Tests.cs,MovementSystemTests.cs
Why "V2" when there is no V1?
There is no WallSystemV1 in the codebase: the name records history. The first wall-system design (a mutable perimeter model) was integrated, found architecturally broken, and abandoned under the restart plan in the product requirements document (PRD). See "The Wall System" section of DOCUMENTATION/Plan/QIX_GAME_PRD.md for the full postmortem. WallSystemV2 is the rebuilt design this chapter covers.
The central problem
Every successful capture changes the shape of the playable interior. That means the safe boundary the player moves on also changes. The hard part is not drawing the newly claimed area, but keeping the movement boundary correct after each topological change.
Territory-capture implementations often fail by keeping one giant hybrid model. The trail, the wall, the claimed fill, and the movement rules all mutate each other directly. That quickly produces stale geometry and impossible-to-debug edge cases.
The architecture you must understand
There are three separate runtime truths (chapter 00 drew them in one frame):
| Representation | What it owns |
|---|---|
| Grid | Claim solving, occupancy checks, rendering support |
| Playable wall path | Where the player can move safely |
| Trail | Temporary risky geometry during capture |
The lesson here goes beyond separation of concerns, to separation of representations.
How the wall path is rebuilt
WallSystemV2.RebuildPlayablePath follows this pattern:
- scan every unclaimed tile,
- inspect its four neighbours,
- emit a segment wherever a face borders out-of-bounds space or claimed space,
- merge adjacent collinear segments,
- build a
PlayableWallPathfrom the merged result.
This means the safe path is derived from authoritative arena state instead of manually patched in place.
The code
The heart of the rebuild is the face-test loop. For every unclaimed tile, each of its four faces is emitted as a provisional wall segment if the neighbour on that side is not unclaimed playable space:
csharp
for (int x = 0; x < arenaSystem.GridWidth; x++)
{
for (int y = 0; y < arenaSystem.GridHeight; y++)
{
Point current = new(x, y);
if (arenaSystem.GetTileState(current) != TileState.Unclaimed)
{
continue;
}
Rectangle tileBounds = arenaSystem.GetTileBounds(current);
if (IsBoundary(arenaSystem, x, y - 1))
{
horizontalSegments.Add((tileBounds.Top, tileBounds.Left, tileBounds.Right));
}
if (IsBoundary(arenaSystem, x, y + 1))
{
horizontalSegments.Add((tileBounds.Bottom, tileBounds.Left, tileBounds.Right));
}
if (IsBoundary(arenaSystem, x - 1, y))
{
verticalSegments.Add((tileBounds.Left, tileBounds.Top, tileBounds.Bottom));
}
if (IsBoundary(arenaSystem, x + 1, y))
{
verticalSegments.Add((tileBounds.Right, tileBounds.Top, tileBounds.Bottom));
}
}
}
List<PathSegment> mergedSegments = new();
mergedSegments.AddRange(MergeHorizontal(horizontalSegments));
mergedSegments.AddRange(MergeVertical(verticalSegments));
return new PlayableWallPath(mergedSegments);The boundary predicate is one line of policy: out of bounds counts the same as claimed. This is exactly why chapter 02's GetTileState returns the Boundary sentinel instead of throwing:
csharp
private static bool IsBoundary(ArenaSystem arenaSystem, int x, int y)
{
Point neighbor = new(x, y);
return !arenaSystem.IsValidGridPoint(neighbor) || arenaSystem.GetTileState(neighbor) != TileState.Unclaimed;
}Merging groups the faces by row (or column), sorts them, and joins any face that starts exactly where the previous one ended:
csharp
private static IEnumerable<PathSegment> MergeHorizontal(IEnumerable<(int Y, int StartX, int EndX)> segments)
{
foreach (IGrouping<int, (int Y, int StartX, int EndX)> group in segments.GroupBy(segment => segment.Y))
{
List<(int Y, int StartX, int EndX)> ordered = group.OrderBy(segment => segment.StartX).ToList();
if (ordered.Count == 0)
{
continue;
}
int start = ordered[0].StartX;
int end = ordered[0].EndX;
foreach ((int _, int currentStart, int currentEnd) in ordered.Skip(1))
{
if (currentStart == end)
{
end = currentEnd;
continue;
}
yield return new PathSegment(new Vector2(start, group.Key), new Vector2(end, group.Key));
start = currentStart;
end = currentEnd;
}
yield return new PathSegment(new Vector2(start, group.Key), new Vector2(end, group.Key));
}
}Because faces are integer tile edges, the join test is an exact integer comparison; no tolerance is needed here. MergeVertical is the same code with X and Y swapped.
On the real arena the scan visits 31,878 tiles. At the start of a level it emits 738 faces (231 + 231 + 138 + 138), and they merge into exactly four segments. That is the assertion in InitialArenaPath_IsClosedRectangle.
The graph interpretation
Even though the code stores segments, you should think in graph terms:
- segment endpoints act as nodes (
PlayableWallPath.Nodesis the distinct set of endpoints), - segments act as edges,
- node degree tells us how connected a location is (
GetConnectedSegmentCount, used by the respawn rule in later chapters), - captures change the graph topology,
- traversal is edge-following under directional constraints.
That mental model makes the system easier to explain. Notice in the diagram that nothing "moves" the two vanished edges. The claimed tiles are no longer Unclaimed, so the face test never emits them again.
Maths: adjacency and edge extraction
For each unclaimed tile (x, y), test (x, y - 1), (x, y + 1), (x - 1, y), and (x + 1, y). If the neighbour is out of bounds or not Unclaimed, then that tile face belongs to the safe wall. This is a local rule producing a global boundary.
Maths: complexity of the rebuild
Let W be the grid width, H the grid height, and S the provisional face-segment count. Then the scan is O(W * H), and grouping and ordering segments is roughly O(S log S). Traversal becomes cheaper after merging, because the final segment count is much smaller. The rebuild runs only at level start and after each finalised claim, never per frame, so this cost is invisible in play. It is an excellent case study in preferring a clear full rebuild over a brittle incremental update.
Maths: containment, snapping, and tolerance
PathSegment carries the geometry. Contains accepts any point within a small band around the segment, and Snap projects a point onto the segment (clamped to its extent):
csharp
public readonly record struct PathSegment(Vector2 Start, Vector2 End)
{
public bool Contains(Vector2 point, float tolerance = 2f)
{
if (Math.Abs(Start.X - End.X) < 0.01f)
{
float minY = Math.Min(Start.Y, End.Y) - tolerance;
float maxY = Math.Max(Start.Y, End.Y) + tolerance;
return Math.Abs(point.X - Start.X) <= tolerance && point.Y >= minY && point.Y <= maxY;
}
float minX = Math.Min(Start.X, End.X) - tolerance;
float maxX = Math.Max(Start.X, End.X) + tolerance;
return Math.Abs(point.Y - Start.Y) <= tolerance && point.X >= minX && point.X <= maxX;
}
public Vector2 Snap(Vector2 point)
{
if (Math.Abs(Start.X - End.X) < 0.01f)
{
return new Vector2(Start.X, MathHelper.Clamp(point.Y, Math.Min(Start.Y, End.Y), Math.Max(Start.Y, End.Y)));
}
return new Vector2(MathHelper.Clamp(point.X, Math.Min(Start.X, End.X), Math.Max(Start.X, End.X)), Start.Y);
}
}PlayableWallPath.Contains asks every segment; PlayableWallPath.Snap picks the nearest segment (by DistanceSquared) and snaps to it.
Tolerance is the second lesson of the chapter: games use tolerance because movement is floating point and frame steps are imperfect. At 60 Hz the player moves 2.5 px per frame. A candidate position is often a fraction of a pixel off the line, so exact equality would refuse almost every frame. The band absorbs that imperfection, and Snap removes the drift it allowed. The same band lets the player turn corners. A candidate that runs more than 2 px past the end of a segment is refused, so the player can stop short of a corner by up to the step minus the tolerance, which is 0.5 px at the default speed. The turn is still accepted, because that shortfall is inside the perpendicular segment's 2 px band, and Snap pulls the player onto that segment.
Traversal: what the game actually does
Movement becomes path-constrained through MovementSystem.TryMoveAlongPath. Read it as candidate first, legality second, snap last:
csharp
public bool TryMoveAlongPath(PlayableWallPath path, Vector2 currentPosition, Direction direction, float speed, float deltaTime, out Vector2 nextPosition)
{
Vector2 candidate = CalculateNextPosition(currentPosition, direction, speed, deltaTime);
if (!path.Contains(candidate))
{
nextPosition = currentPosition;
return false;
}
nextPosition = path.Snap(candidate);
return true;
}Be precise about what this is: a containment-plus-snap check, not a graph walk. It works while the per-frame step is no more than twice the tolerance, which is 4 px per frame, or about 240 px/s at 60 Hz. Past that, the player stops too far short of a corner for the perpendicular band to catch the turn. PlayableWallPath deliberately ships only Contains, Snap, and GetConnectedSegmentCount; there is no segment-following walker in the codebase. The second extension at the end of the chapter asks you to write one and compare it with the simple check. Doing so is the best way to understand what the containment check quietly relies on. The walker finds the segment under the player, measures the distance left on it in the chosen direction, moves, and continues onto the next segment at the corner.
Why this approach works
This chapter should make the design win explicit:
- the wall path is rebuilt from authoritative state,
- stale movement geometry is discarded instead of patched,
- the trail stays temporary,
- captured fill stays separate,
- movement uses the path, not the fill.
That is the breakthrough to remember.
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 in this chapter 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/04-The-Playable-Wall-Path-Node-System/Source", "<course-repo>/DOCUMENTATION/LastPerimeter-Source/04-The-Playable-Wall-Path-Node-System/Tests" .In bash:
bash
cp -R "<course-repo>/DOCUMENTATION/LastPerimeter-Source/04-The-Playable-Wall-Path-Node-System/Source" "<course-repo>/DOCUMENTATION/LastPerimeter-Source/04-The-Playable-Wall-Path-Node-System/Tests" .That copy brings in these files:
New files:
Source/Systems/WallSystemV2.csTests/Systems/MovementSystemTests.csTests/Systems/PlayableWallPathTests.csTests/Systems/PlayableWallPathTraversalTests.csTests/Systems/WallSystemV2Tests.cs
Replaced files (the copy overwrites your versions):
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 - Read the wall system
Open Source/Systems/WallSystemV2.cs and match it against the listings above.
Step 3 - The game class: LastPerimeterApp (chapter 04 version)
Open Source/Game/LastPerimeterApp.cs. Initialize no longer hand-builds the rectangle. It builds the path from the arena and starts the player on its top-left node:
csharp
_arenaSystem = new ArenaSystem(_config);
_wallSystem = new WallSystemV2();
_movementSystem = new MovementSystem();
_inputManager = new InputManager();
PlayableWallPath playableWallPath = _wallSystem.RebuildPlayablePath(_arenaSystem);
Vector2 start = playableWallPath.Nodes.OrderBy(node => node.X).ThenBy(node => node.Y).First();
_gameSession = new GameSession
{
Player = new Player { Position = start, Speed = _config.PlayerSpeed },
PlayableWallPath = playableWallPath,
CaptureHistory = [],
Enemies = [],
};Update replaces the clamp with the path move. ClampInsideArena and CreateRectanglePath are gone, because nothing needs them any more:
csharp
float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
InputState inputState = _inputManager.GetCurrentInput();
Direction direction = _movementSystem.DetermineDirection(inputState);
if (direction != Direction.None
&& _movementSystem.TryMoveAlongPath(_gameSession.PlayableWallPath, _gameSession.Player.Position, direction, _gameSession.Player.Speed, deltaTime, out Vector2 next))
{
_gameSession.Player.Position = next;
_gameSession.Player.CurrentDirection = direction;
}Step 4 - Read the tests
Open Tests/Systems/PlayableWallPathTests.cs and Tests/Systems/WallSystemV2Tests.cs. Between them they hold the two tests that deserve a read now. InitialArenaPath_IsClosedRectangle asserts that the rebuilt path has exactly four segments on the arena's four edges. RebuildPlayablePath_AfterClaim_MatchesRemainingPlayableRegion claims a 3 x 2 block of tiles in the corner through ArenaSystem.ApplyClaimResult and rebuilds. It then asserts two things. The path contains a point on the new inner edge, and it no longer contains a point on the old outer corner. That second test is the whole chapter in ten lines.
Step 5 - Build, test, run
Run these commands from the LastPerimeter folder:
bash
dotnet build
dotnet test
dotnet run --project Platforms/DesktopVKdotnet test reports 12 passing tests. On Windows you can also run dotnet run --project Platforms/WindowsDX12.
Whiteboard exercise
Draw:
- the initial rectangle,
- a trail cutting inward,
- the smaller region becoming claimed,
- the new safe wall path around the remaining unclaimed area.
Then ask yourself: Which edges vanished? Which nodes were created? Which old assumptions about the wall are no longer true? Compare with the before/after diagram above.
Chapter snapshot
The matching buildable project is DOCUMENTATION/LastPerimeter-Source/04-The-Playable-Wall-Path-Node-System; build and test it standalone with dotnet build and dotnet test. This chapter stages four new test files, PlayableWallPathTests, PlayableWallPathTraversalTests, WallSystemV2Tests, and MovementSystemTests, bringing the suite to 12 passing tests.
Checkpoint
- In your
LastPerimeterfolder, rundotnet test: 12 tests pass, includingInitialArenaPath_IsClosedRectangleandRebuildPlayablePath_AfterClaim_MatchesRemainingPlayableRegion. If yours differ, compare your files with the snapshot inDOCUMENTATION/LastPerimeter-Source/04-The-Playable-Wall-Path-Node-System. - Run
dotnet run --project Platforms/DesktopVK: the player starts at the top-left corner. Hold Down and the dot slides down the left wall. At the bottom, hold Right and it turns the corner cleanly and follows the bottom edge without drifting off the line (screenshot above). - Run the game again, hold Down until the dot is part-way down the left wall, then hold Right. The dot does not move, because drawing into the interior arrives in chapter 05. Press Escape to close the game.
- Open
Source/Entities/PlayableWallPath.csand, inPathSegment.Contains, change thetolerancedefault from2fto0.5f. Run the game, hold Down to the bottom of the left wall, then hold Right and try to turn the corner. Explain what you see using the snap-tolerance diagram. Then change the default back to2f.
What you should have now
You now have:
- face extraction from the tile grid,
- segment merging,
- node generation from segment endpoints,
- snapping and containment,
- directional movement across the rebuilt path.
Common mistakes
- forgetting to rebuild after a claim,
- mixing temporary trail geometry into the permanent path too early,
- using exact coordinate equality,
- rendering the claimed area correctly but leaving movement logic stale,
- trying to manually mutate old segments instead of deriving a new path,
- a per-frame step more than twice the tolerance band (for example after raising
PlayerSpeedto 400), which makes corners unreachable with the containment check.
Extensions
Compare:
- full rebuild after every claim,
- incremental path mutation.
Then justify the trade-off in terms of correctness, implementation complexity, debugging cost, asymptotic performance, and clarity of explanation.
For a second, more concrete extension, write your own PlayableWallPath.TryTraverse(Vector2 position, Direction direction, float distance, out Vector2 nextPosition). It is a segment-following graph walker. It finds the segment under the player, measures the distance left on it in the chosen direction, and moves that far. If distance remains, it continues onto a connected segment at the corner. Make MovementSystem.TryMoveAlongPath call it instead of the containment check, run the 12 tests, and then raise PlayerSpeed until one of the two implementations stops turning corners. Write down which one survived and why.

