Appearance
Chapter 06: The Wall Path Service
In Chapter 05: Scenes and the Gameplay Simulation, you moved the player inside GameplaySimulation and kept it in the arena with a clamp. The player could still wander anywhere inside the rectangle. In Qix, the player is safe only on the wall and takes a risk only when leaving it.
In this chapter, you build the wall path service. It derives the safe wall from the tile grid and constrains the player to it.
| Figure 06-1: The chapter 06 window. The player is on the left wall and can only slide along the outline. This is a drawn illustration, not a screenshot. |
Time: [TODO Simon: time estimate for chapter 06]
In this chapter, you will:
- Learn why the wall is rebuilt from the grid and never patched.
- Build
WallSystemV2.RebuildPlayablePathwith a four-neighbour face test. - Merge collinear faces into segments, and see why merging matters.
- Give
PathSegmentandPlayableWallPaththeir containment and snapping operations. - Add
TryMoveAlongPathtoMovementSystem, so the player slides along the wall and turns at corners. - Start each level with the player on the top-left node.
Requirements in this chapter
| ID | Short name |
|---|---|
| WAL-01 | Wall derived from the grid |
| WAL-02 | Collinear faces merged |
| WAL-03 | Rebuilt in full after a claim |
| WAL-04 | 2 px tolerance for containment |
| WAL-05 | Snapping to the nearest wall point |
| WAL-06 | Nodes and connected segment counts |
| MOV-03 | Wall-only movement when not drawing |
| MOV-04 | Turning at corners |
| MOV-05 | Start on the top-left node |
Three representations
The game keeps three separate pictures of the same arena. The grid is the tile array from Chapter 03: The Service Pattern and the Arena. It says which tiles are claimed, and it is the only source of truth. The wall path is a short list of straight lines. It says where the player may stand when not drawing. The trail, which Chapter 07 adds, is the temporary line the player draws while taking a risk.
Each picture answers a different question, so each has its own type. The grid is good at "who owns this tile?", and poor at "where may I stand?". A list of segments is the opposite. This chapter builds the second picture from the first.
Why the wall is rebuilt
Every successful capture changes the shape of the unclaimed area, so it changes where the safe wall runs. The hard part of the game is not drawing the new claim. It is keeping the movement boundary correct after each change.
The first design for this game kept one mutable model of the perimeter. Claiming ground edited that model in place. It looked fine for one simple capture. Then captures began to touch earlier walls, and the model drifted from the grid. The player could stand on a wall that was no longer there, or be refused a wall that was.
A second design mixed the models. The trail, the wall and the claimed fill each changed the others directly. The stale geometry was still there, now spread over three places, and nobody could say which one was right.
The design in this chapter removes the question. The wall is a pure function of the grid. After every claim, the whole wall is thrown away and derived again. A rebuilt wall cannot be stale, because it holds nothing that the grid does not say. Figure 06-2 shows the idea.
The class is named WallSystemV2 because it is the second design. The first one no longer exists in the code.
| Figure 06-2: Rebuild before and after. The old path is discarded and the new path is derived from the grid alone |
The face test
A face is one side of one tile. The rule is local. Look at every unclaimed tile. For each of its four sides, look at the neighbour on that side. If the neighbour is not unclaimed, that side is wall. A neighbour is not unclaimed when it is claimed, or when it lies off the grid.
The second case is why GetTileState answers Boundary for points off the grid. The edge of the grid acts like a claimed tile, so a fresh arena gets a wall all the way round with no special case. Figure 06-3 shows the faces on a small grid.
| Figure 06-3: The face test on a 6 by 4 grid. A face is emitted where a neighbour is claimed or off the grid, then collinear faces merge |
Merging faces
The face test gives one tiny segment per tile side. A real arena has 231 tiles along its top edge, so the top wall would be 231 segments of 4 pixels each. That is correct but wasteful. Every containment and snapping check loops over the segments, and each of those checks runs several times per frame.
The fix is to merge. Group the horizontal faces by their row line, and the vertical faces by their column line. Sort each group along its line. Then join any face that starts exactly where the previous one ended. A new arena merges down to 4 segments. Merging also keeps the node list honest. A node is where two segments meet, and a merged wall has no node in the middle of a straight run.
Tolerance and snapping
The player moves in fractions of a pixel, and a wall is a line with no width. If the player had to land exactly on the line, it would almost never be on it. The game therefore accepts a position within 2 pixels of a segment. That distance is the tolerance.
Tolerance does a second job. When the player presses a perpendicular direction at a corner, the candidate position is a little off the old wall and a little along the new one. The 2 pixel band of the new wall catches it, so the turn works. After a move is accepted, the position is snapped. Snapping moves it to the nearest point on the wall, so small errors never build up. Figure 06-4 shows both cases.
| Figure 06-4: Tolerance and snapping. A candidate within 2 px of a segment is accepted and snapped onto it, and a candidate farther away is refused |
The wall segment
PathSegment already exists from Chapter 05, as a single line of code with no operations. You now give it three. Contains tells whether a point is within the tolerance of the segment. Snap gives the nearest point on it. DistanceSquared gives the squared distance to that point. Distances are compared squared, because that avoids a square root.
You also add the PlayableWallPath class to the same file. It holds the segments, finds the nodes from their ends, and loops over the segments for Contains and Snap. Because it only loops, you write it in full now. The segment operations are the part with something to prove, so they start as stubs.
PathSegment.Contains(point, tolerance) : bool
- Takes: a point and a tolerance, 2 pixels by default.
- Gives:
truewhen the point is within the tolerance of the segment, including just past its ends.- Promises: the check works for horizontal and for vertical segments.
- Refuses: nothing. A point too far away gives
false.- Requirements: WAL-04.
PathSegment.Snap(point) : Vector2andDistanceSquared(point) : float
- Takes: a point.
- Gives: the nearest point on the segment, and the squared distance to it.
- Promises: the snapped point lies between the two ends, on the segment's own line.
- Refuses: nothing.
- Requirements: WAL-05.
PlayableWallPath.Contains,Snap,NodesandGetConnectedSegmentCount
- Takes: a point, or a node.
- Gives: whether any segment contains the point, the nearest point on the nearest segment, each segment end once, and how many segments meet at a node.
- Promises:
Containsallocates nothing. An empty path returns the input fromSnap.- Refuses: nothing.
- Requirements: WAL-04, WAL-05, WAL-06.
Open Source/Entities/PlayableWallPath.cs and replace the whole file with the following. The file now holds two types, so you replace it instead of editing one member. The three PathSegment operations throw, and PlayableWallPath is complete.
replace-file Source/Entities/PlayableWallPath.cs
csharp
using Microsoft.Xna.Framework;
namespace LastPerimeter.Entities;
public readonly record struct PathSegment(Vector2 Start, Vector2 End)
{
public bool Contains(Vector2 point, float tolerance = 2f)
{
throw new NotImplementedException();
}
public Vector2 Snap(Vector2 point)
{
throw new NotImplementedException();
}
public float DistanceSquared(Vector2 point)
{
throw new NotImplementedException();
}
}
public sealed class PlayableWallPath
{
private readonly List<PathSegment> _segments;
private readonly List<Vector2> _nodes;
public PlayableWallPath(IEnumerable<PathSegment> segments)
{
_segments = segments.ToList();
_nodes = _segments.SelectMany(segment => new[] { segment.Start, segment.End }).Distinct().ToList();
}
public IReadOnlyList<PathSegment> Segments => _segments;
public IReadOnlyList<Vector2> Nodes => _nodes;
public bool Contains(Vector2 point, float tolerance = 2f)
{
// A plain loop, not LINQ Any: this runs several times every frame, and a
// lambda that captures point and tolerance allocates on each call.
foreach (PathSegment segment in _segments)
{
if (segment.Contains(point, tolerance))
{
return true;
}
}
return false;
}
public Vector2 Snap(Vector2 point)
{
PathSegment? nearestSegment = null;
float nearestDistance = float.MaxValue;
foreach (PathSegment segment in _segments)
{
float distance = segment.DistanceSquared(point);
if (distance < nearestDistance)
{
nearestDistance = distance;
nearestSegment = segment;
}
}
return nearestSegment?.Snap(point) ?? point;
}
public int GetConnectedSegmentCount(Vector2 node, float tolerance = 0.5f)
{
return _segments.Count(segment => Vector2.DistanceSquared(segment.Start, node) <= tolerance * tolerance || Vector2.DistanceSquared(segment.End, node) <= tolerance * tolerance);
}
}The key things to note are:
PlayableWallPathtakes its segments in the constructor and never changes them afterwards. A new wall is a new object.- The nodes are every segment end, with duplicates removed.
Distinctworks becauseVector2compares by value. New to LINQ? See the C# primer. Containsuses a plainforeachloop. The comment explains why. A LINQ call with a lambda would allocate memory on every call, and this runs several times each frame.GetConnectedSegmentCountcounts the segments whose start or end is within 0.5 pixels of the node. A corner of a rectangle has 2.- From the
LastPerimeterfolder, rundotnet build. The build should succeed, which proves the stubs compile.
In the Tests/Systems folder, create a new file named PlayableWallPathTests.cs and add the following code. It starts with one test. The segment is 20 pixels long. A point 1.9 pixels off is on the wall, and a point 2.5 pixels off is not. A point 1.5 pixels past the end is still inside, because the tolerance applies along the line too.
new-file Tests/Systems/PlayableWallPathTests.cs
csharp
using LastPerimeter.Entities;
using Microsoft.Xna.Framework;
using LastPerimeter.Systems;
using LastPerimeter.Tests.TestHelpers;
namespace LastPerimeter.Tests.Systems;
public sealed class PlayableWallPathTests
{
[Fact]
public void Contains_UsesTwoPixelTolerance()
{
PlayableWallPath path = new(new[] { new PathSegment(new Vector2(0, 0), new Vector2(20, 0)) });
Assert.True(path.Contains(new Vector2(10, 1.9f)));
Assert.False(path.Contains(new Vector2(10, 2.5f)));
Assert.True(new PathSegment(new Vector2(0, 0), new Vector2(20, 0)).Contains(new Vector2(21.5f, 0)));
}
}The file has five using lines, because the tests you add later need them. Some are unused for now, which is harmless.
In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 19. The 19 passes are the tests from earlier chapters. The failure is your new test, which reached a stub.
In Source/Entities/PlayableWallPath.cs, find the Contains method of PathSegment and replace the whole method with the following. The PlayableWallPath class has a method with the same name further down the file. Replace the one inside PathSegment, which comes first.
replace-method Source/Entities/PlayableWallPath.cs Contains type=PathSegment
csharp
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;
}In the same file, find the Snap method of PathSegment and replace the whole method with the following:
replace-method Source/Entities/PlayableWallPath.cs Snap type=PathSegment
csharp
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);
}Find the DistanceSquared method and replace the whole method with the following:
replace-method Source/Entities/PlayableWallPath.cs DistanceSquared
csharp
public float DistanceSquared(Vector2 point)
{
return Vector2.DistanceSquared(Snap(point), point);
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 20.
The key things to note are:
- A segment is vertical when its start and end have the same X, within 0.01. Otherwise the code treats it as horizontal, because the wall only ever has these two kinds.
Containswidens the range along the line by the tolerance, and it limits the distance across the line to the tolerance. That makes a small box around the segment.Snapclamps the point along the line and keeps the segment's own coordinate across it. The result always lies on the segment.DistanceSquaredis built fromSnap, so the two can never disagree about which point is nearest.Snaphas no test of its own in this chapter. The traversal tests later in this chapter compare snapped positions, and Chapter 09 adds a test that snaps a finished trail back onto the wall.
Building the wall system
WallSystemV2 has one public operation. It has no fields, so any number of calls give the same answer for the same grid.
WallSystemV2.RebuildPlayablePath(arenaSystem) : PlayableWallPath
- Takes: an arena.
- Gives: a wall path.
- Promises: every face between an unclaimed tile and anything else is wall. Collinear faces are merged. The result depends only on the grid.
- Refuses: it never patches an old path. There is no old path to pass in.
- Requirements: WAL-01, WAL-02, WAL-03.
The wall tests need to list the unclaimed tiles, so you add one helper to ArenaSystem first. It has no card and no test of its own. The wall tests below use it, and they would fail if it were wrong.
Open Source/Systems/ArenaSystem.cs. Add the following method to the ArenaSystem class, below the IsClaimedWorld method:
add-member Source/Systems/ArenaSystem.cs after=IsClaimedWorld
csharp
public IEnumerable<Point> EnumerateUnclaimedTiles()
{
for (int x = 0; x < GridWidth; x++)
{
for (int y = 0; y < GridHeight; y++)
{
if (_grid[x, y] == TileState.Unclaimed)
{
yield return new Point(x, y);
}
}
}
}The key things to note are:
- The method uses
yield return, so it hands back one tile at a time and never builds a list. - It scans column by column, and down each column tile by tile.
In the Source/Systems folder, create a new file named WallSystemV2.cs and add the following code:
new-file Source/Systems/WallSystemV2.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
namespace LastPerimeter.Systems;
public sealed class WallSystemV2
{
public PlayableWallPath RebuildPlayablePath(ArenaSystem arenaSystem)
{
throw new NotImplementedException();
}
}In the Tests/Systems folder, create a new file named WallSystemV2Tests.cs and add the following code. A new 40 by 20 arena has 10 by 5 tiles. Without merging, its wall would be 30 segments: 10 faces along the top, 10 along the bottom, and 5 on each side. With merging it must be 4.
new-file Tests/Systems/WallSystemV2Tests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
using LastPerimeter.Systems;
using LastPerimeter.Tests.TestHelpers;
namespace LastPerimeter.Tests.Systems;
public sealed class WallSystemV2Tests
{
[Fact]
public void RebuildPlayablePath_MergesCollinearFaces()
{
ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));
PlayableWallPath path = new WallSystemV2().RebuildPlayablePath(arena);
Assert.Equal(4, path.Segments.Count);
}
}Add the following test to the WallSystemV2Tests class, above the RebuildPlayablePath_MergesCollinearFaces test. It claims a block of six tiles in the top-left corner and then rebuilds. A point on the new wall must be on the path, and a point inside the claim must not be.
add-member Tests/Systems/WallSystemV2Tests.cs before=RebuildPlayablePath_MergesCollinearFaces
csharp
[Fact]
public void RebuildPlayablePath_AfterClaim_MatchesRemainingPlayableRegion()
{
ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));
WallSystemV2 wallSystem = new();
Region captured = new();
captured.Tiles.AddRange(new[]
{
new Point(0, 0), new Point(0, 1), new Point(1, 0), new Point(1, 1), new Point(2, 0), new Point(2, 1),
});
Region remaining = new();
remaining.Tiles.AddRange(arena.EnumerateUnclaimedTiles().Except(captured.Tiles));
arena.ApplyClaimResult(new ClaimResult(captured, remaining, Array.Empty<Point>()));
PlayableWallPath path = wallSystem.RebuildPlayablePath(arena);
Assert.True(path.Contains(new Vector2(12, 4)));
Assert.False(path.Contains(new Vector2(2, 2)));
}Open Tests/Systems/PlayableWallPathTests.cs. Add the following test to the PlayableWallPathTests class, above the Contains_UsesTwoPixelTolerance test. It checks that a new arena gives a closed rectangle, with one segment on each edge of the arena.
add-member Tests/Systems/PlayableWallPathTests.cs before=Contains_UsesTwoPixelTolerance
csharp
[Fact]
public void InitialArenaPath_IsClosedRectangle()
{
ArenaSystem arena = new(TestConfigFactory.Create());
WallSystemV2 wallSystem = new();
var path = wallSystem.RebuildPlayablePath(arena);
Assert.Equal(4, path.Segments.Count);
Assert.Contains(path.Segments, segment => segment.Start.Y == segment.End.Y && segment.Start.Y == arena.Bounds.Top);
Assert.Contains(path.Segments, segment => segment.Start.Y == segment.End.Y && segment.Start.Y == arena.Bounds.Bottom);
Assert.Contains(path.Segments, segment => segment.Start.X == segment.End.X && segment.Start.X == arena.Bounds.Left);
Assert.Contains(path.Segments, segment => segment.Start.X == segment.End.X && segment.Start.X == arena.Bounds.Right);
}Add the following test below the Contains_UsesTwoPixelTolerance test. It checks the node rule: a rectangle has 4 nodes, and exactly 2 segments meet at each.
add-member Tests/Systems/PlayableWallPathTests.cs after=Contains_UsesTwoPixelTolerance
csharp
[Fact]
public void Rectangle_HasFourNodesWithTwoSegmentsEach()
{
ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));
PlayableWallPath path = new WallSystemV2().RebuildPlayablePath(arena);
Assert.Equal(4, path.Nodes.Count);
foreach (Vector2 node in path.Nodes)
{
Assert.Equal(2, path.GetConnectedSegmentCount(node));
}
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 4 and Passed: 20. The four new wall tests reach the stub.
Now you write the body in three steps. Each step adds a helper that the final method needs, so the project compiles at every step. Open Source/Systems/WallSystemV2.cs. Add the following method to the WallSystemV2 class, below the RebuildPlayablePath method. It is the one line of policy that the face test depends on:
add-member Source/Systems/WallSystemV2.cs after=RebuildPlayablePath
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;
}The key things to note are:
- A neighbour counts as wall material when it is off the grid or not
Unclaimed. The grid check comes first, so a bad point never reaches the grid. GetTileStatewould answerBoundaryfor an off-grid point anyway. The explicit check makes the rule visible at the place that relies on it.
Add the following method below IsBoundary. It merges the horizontal faces. Each face is a tuple of the row line Y and the start and end X. New to tuples? See the C# primer. Type the method:
add-member Source/Systems/WallSystemV2.cs after=IsBoundary
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));
}
}Add the following method below MergeHorizontal. It does the same for the vertical faces, with the roles of X and Y swapped:
add-member Source/Systems/WallSystemV2.cs after=MergeHorizontal
csharp
private static IEnumerable<PathSegment> MergeVertical(IEnumerable<(int X, int StartY, int EndY)> segments)
{
foreach (IGrouping<int, (int X, int StartY, int EndY)> group in segments.GroupBy(segment => segment.X))
{
List<(int X, int StartY, int EndY)> ordered = group.OrderBy(segment => segment.StartY).ToList();
if (ordered.Count == 0)
{
continue;
}
int start = ordered[0].StartY;
int end = ordered[0].EndY;
foreach ((int _, int currentStart, int currentEnd) in ordered.Skip(1))
{
if (currentStart == end)
{
end = currentEnd;
continue;
}
yield return new PathSegment(new Vector2(group.Key, start), new Vector2(group.Key, end));
start = currentStart;
end = currentEnd;
}
yield return new PathSegment(new Vector2(group.Key, start), new Vector2(group.Key, end));
}
}The key things to note are:
GroupBycollects the faces that lie on the same line, andOrderByputs them in order along it.- A face joins the run when its start equals the end of the run. If there is a gap, the run is emitted and a new one begins. The last run is emitted after the loop.
- Two faces on the same line with a claimed tile between them are not joined, because the second one does not start where the first ended.
- The methods use
yield return. They run once per rebuild, not once per frame, so the small cost of LINQ is fine here. New to deferred execution? See the C# primer.
Find the RebuildPlayablePath method and replace the whole method with the following:
replace-method Source/Systems/WallSystemV2.cs RebuildPlayablePath
csharp
public PlayableWallPath RebuildPlayablePath(ArenaSystem arenaSystem)
{
List<(int Y, int StartX, int EndX)> horizontalSegments = new();
List<(int X, int StartY, int EndY)> verticalSegments = new();
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);
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 24.
The key things to note are:
- The loops visit every tile. Anything that is not
Unclaimedis skipped, so claimed tiles never produce a wall. Only the border of the open area does. - Each of the four
ifstatements checks one neighbour. A top face is horizontal, so it goes tohorizontalSegments, with the tile's top edge as its line. The other three faces work the same way. - A tile in the middle of a large open area has four unclaimed neighbours and adds nothing. This is why the wall is so much shorter than the grid.
- The method reads the arena and builds a new path. It does not change the arena, and it takes no old path. This is the "rebuild, never patch" rule in the code.
Moving along the wall
The last piece of the wall is the movement rule. TryMoveAlongPath calculates where the player would go, using the CalculateNextPosition operation from Chapter 04. It then asks the wall whether that place is on the wall.
MovementSystem.TryMoveAlongPath(path, currentPosition, direction, speed, deltaTime, out nextPosition) : bool
- Takes: a wall path, the current position, a direction, a speed and the frame time.
- Gives:
trueand the candidate position snapped onto the wall.- Promises: a candidate on the path is accepted, so a perpendicular move at a corner succeeds.
- Refuses: a candidate off the path leaves the position unchanged and gives
false.- Requirements: MOV-03, MOV-04.
This method only checks the path. It never asks the arena whether a tile is claimed. It does not need to, because the path was derived from the claims. A position that is not on the wall is either inside a claim or inside the open area, and the player may not stand in either while not drawing.
Open Source/Systems/MovementSystem.cs. At the top of the file, add the following line below the using LastPerimeter.Data; line:
add-using Source/Systems/MovementSystem.cs after=LastPerimeter.Data
csharp
using LastPerimeter.Entities;Add the following method to the MovementSystem class, below the CalculateNextPosition method:
add-member Source/Systems/MovementSystem.cs at=end
csharp
public bool TryMoveAlongPath(PlayableWallPath path, Vector2 currentPosition, Direction direction, float speed, float deltaTime, out Vector2 nextPosition)
{
throw new NotImplementedException();
}Open Tests/Systems/MovementSystemTests.cs. At the top of the file, add the following line below the using LastPerimeter.Data; line:
add-using Tests/Systems/MovementSystemTests.cs after=LastPerimeter.Data
csharp
using LastPerimeter.Entities;Add the following test to the MovementSystemTests class, below the DetermineDirection_WithNoInput_ReturnsNone test. The path is two segments forming a corner. The player stands on the top-left end of the top segment and presses Down, where there is no wall:
add-member Tests/Systems/MovementSystemTests.cs after=DetermineDirection_WithNoInput_ReturnsNone
csharp
[Fact]
public void PlayerCannotTraverseClaimedInterior_WhenNotDrawing()
{
MovementSystem movementSystem = new();
PlayableWallPath path = new(new[]
{
new PathSegment(new Vector2(0, 0), new Vector2(40, 0)),
new PathSegment(new Vector2(40, 0), new Vector2(40, 40)),
});
bool moved = movementSystem.TryMoveAlongPath(path, new Vector2(0, 0), Direction.Down, 10f, 1f, out _);
Assert.False(moved);
}Add the following test below the PlayerCannotTraverseClaimedInterior_WhenNotDrawing test. The player stands on the corner node and presses Down, where the second segment runs:
add-member Tests/Systems/MovementSystemTests.cs after=PlayerCannotTraverseClaimedInterior_WhenNotDrawing
csharp
[Fact]
public void PlayerCanTraverseConnectedCornerSegment_WhenDirectionChangesAtNode()
{
MovementSystem movementSystem = new();
PlayableWallPath path = new(new[]
{
new PathSegment(new Vector2(0, 0), new Vector2(40, 0)),
new PathSegment(new Vector2(40, 0), new Vector2(40, 40)),
});
bool moved = movementSystem.TryMoveAlongPath(path, new Vector2(40, 0), Direction.Down, 10f, 1f, out Vector2 next);
Assert.True(moved);
Assert.Equal(new Vector2(40, 10), next);
}In the Tests/Systems folder, create a new file named PlayableWallPathTraversalTests.cs and add the following code. The test claims a block in the top-left corner, rebuilds the wall, finds the first node that starts a horizontal run, and moves right along it. The new wall is no longer the arena edge, and the player must still be able to follow it:
new-file Tests/Systems/PlayableWallPathTraversalTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
using LastPerimeter.Systems;
using LastPerimeter.Tests.TestHelpers;
namespace LastPerimeter.Tests.Systems;
public sealed class PlayableWallPathTraversalTests
{
[Fact]
public void RebuiltPath_AllowsTraversalAlongRemainingBoundaryAfterClaim()
{
ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));
WallSystemV2 wallSystem = new();
MovementSystem movementSystem = new();
Region captured = new();
captured.Tiles.AddRange(new[]
{
new Point(0, 0), new Point(0, 1), new Point(1, 0), new Point(1, 1), new Point(2, 0), new Point(2, 1),
});
Region remaining = new();
remaining.Tiles.AddRange(arena.EnumerateUnclaimedTiles().Except(captured.Tiles));
arena.ApplyClaimResult(new ClaimResult(captured, remaining, Array.Empty<Point>()));
PlayableWallPath path = wallSystem.RebuildPlayablePath(arena);
Vector2 start = path.Nodes
.OrderBy(node => node.Y)
.ThenBy(node => node.X)
.First(node => path.Segments.Any(segment => Math.Abs(segment.Start.Y - segment.End.Y) < 0.01f && segment.Contains(node, 0.1f) && Math.Max(segment.Start.X, segment.End.X) > node.X));
bool moved = movementSystem.TryMoveAlongPath(path, start, Direction.Right, 8f, 1f, out Vector2 next);
Assert.True(moved);
Assert.Equal(start.Y, next.Y);
Assert.True(next.X > start.X);
}
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 3 and Passed: 24.
Find the TryMoveAlongPath method in Source/Systems/MovementSystem.cs and replace the whole method with the following:
replace-method Source/Systems/MovementSystem.cs TryMoveAlongPath
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;
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 27.
The key things to note are:
- The candidate is tested, and the current position is not. A player on the wall who presses toward the interior produces a candidate off the wall, so nothing moves.
- A candidate on the wall is replaced by
path.Snap(candidate). The player's position is always a point on the wall, never merely close to it. - On a refusal,
nextPositionis set to the current position. Anoutparameter must always be assigned. - The third test matters most for the game. After a capture, the old edge is gone, and only the rebuilt path says where the new wall is.
Starting a level
A level needs an arena and a wall before the first frame, and it needs the player on that wall. StartLevel builds all three. Chapter 14 later adds the level number to it.
The player starts on the top-left node, which is the node with the lowest X and, among those, the lowest Y. On a fresh arena, this is the arena's top-left corner.
GameplaySimulation.StartLevel() : void
- Takes: nothing.
- Gives: nothing. The simulation changes.
- Promises: a new arena, a wall built from it, the player on the top-left node and the state set to
Running.- Refuses: nothing.
- Requirements: MOV-05.
The simulation now needs a WallSystemV2 and a current arena. Open Source/Data/GameSession.cs. Add the following property to the GameSession class, below the Player property. It has a default, an empty path, because the session exists before the level does:
add-member Source/Data/GameSession.cs after=Player
csharp
public PlayableWallPath PlayableWallPath { get; set; } = new([]);Open Source/Simulation/GameplaySimulation.cs. Add the following field to the GameplaySimulation class, below the _movement field. The wall system has no state, so one instance serves the whole run:
add-member Source/Simulation/GameplaySimulation.cs after=_movement
csharp
private readonly WallSystemV2 _walls = new();Add the following field below the _events field. Unlike the services, the arena is replaced for each level, so the field is not readonly:
add-member Source/Simulation/GameplaySimulation.cs after=_events
csharp
private ArenaSystem _arena;In Source/Simulation/GameplaySimulation.cs, the constructor must build a first arena, so the field is never empty. Find this line in the GameplaySimulation constructor:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
_session = session;Add the following line directly after it:
csharp
_arena = new ArenaSystem(baseConfig);Add the following method below the Session property. It is a stub for now:
add-member Source/Simulation/GameplaySimulation.cs after=Session
csharp
// Builds the arena and the wall for a level and puts the player on the first node.
// Chapter 14 adds the level number.
public void StartLevel()
{
throw new NotImplementedException();
}In the Tests/Simulation folder, create a new file named LevelStartScenarioTests.cs and add the following code. It builds a simulation with a 10 pixel margin, so the arena corner is at (10, 10) and not at the origin. Then it starts the level and checks the player's position and the state.
new-file Tests/Simulation/LevelStartScenarioTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Simulation;
using LastPerimeter.Tests.TestHelpers;
namespace LastPerimeter.Tests.Simulation;
public sealed class LevelStartScenarioTests
{
[Fact]
public void StartLevel_PlacesPlayerOnTopLeftNode()
{
GameplaySimulation sim = SimulationBuilder.Create(margin: 10);
sim.StartLevel();
Assert.Equal(new Vector2(10, 10), sim.Session.Player.Position);
Assert.Equal(SimulationState.Running, sim.State);
}
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 27.
In Source/Simulation/GameplaySimulation.cs, find the StartLevel method and replace the whole method with the following:
replace-method Source/Simulation/GameplaySimulation.cs StartLevel
csharp
// Builds the arena and the wall for a level and puts the player on the first node.
// Chapter 14 adds the level number.
public void StartLevel()
{
_arena = new ArenaSystem(_baseConfig);
_session.PlayableWallPath = _walls.RebuildPlayablePath(_arena);
_session.Player.Position = SelectStartNode(_session.PlayableWallPath);
State = SimulationState.Running;
}Add the following method to the end of the GameplaySimulation class. It is a private helper, so it has no card:
add-member Source/Simulation/GameplaySimulation.cs at=end
csharp
// The top-left node: the lowest X, then the lowest Y.
private static Vector2 SelectStartNode(PlayableWallPath path)
{
IReadOnlyList<Vector2> nodes = path.Nodes;
Vector2 start = nodes[0];
for (int index = 1; index < nodes.Count; index++)
{
Vector2 node = nodes[index];
if (node.X < start.X || (node.X == start.X && node.Y < start.Y))
{
start = node;
}
}
return start;
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 28.
The key things to note are:
StartLevelmakes a freshArenaSystemand asksWallSystemV2for its wall, so the same code path will serve every level.SelectStartNodekeeps the lowest X, and breaks ties by the lowest Y. It does not sort, so it allocates nothing.
Wiring it into the game
Three files still need to change. The test helper must start the level, so every simulation test begins on the wall. The simulation's Tick must move along the wall. The scene must start the level, and the renderer must draw the wall.
In the Tests/TestHelpers folder, open SimulationBuilder.cs. The helper must now start the level, so every simulation test begins on the wall. Find this comment above the class:
find Tests/TestHelpers/SimulationBuilder.cs
csharp
// Builds a small arena (80 by 80, 4 pixel tiles) with a player at its top-left corner.Replace it with:
csharp
// Builds a small arena (80 by 80, 4 pixel tiles) with a player on the top-left node of the wall.In the Create method, find this line:
find Tests/TestHelpers/SimulationBuilder.cs
csharp
return new GameplaySimulation(config, session);Replace it with:
csharp
GameplaySimulation simulation = new(config, session);
simulation.StartLevel();
return simulation;Open Source/Simulation/GameplaySimulation.cs, find the Tick method and replace the whole method with the following:
replace-method Source/Simulation/GameplaySimulation.cs Tick
csharp
// One frame of rules. Returns the reused list of events raised in this frame.
public IReadOnlyList<GameEvent> Tick(float deltaTime, InputState input)
{
_events.Clear();
// 4. Intent: which way does the player want to go?
Direction direction = _movement.DetermineDirection(input);
if (direction == Direction.None)
{
return _events;
}
// 9b. Move along the wall. Chapter 07 adds drawing a trail when there is no wall ahead.
Player player = _session.Player;
if (_movement.TryMoveAlongPath(_session.PlayableWallPath, player.Position, direction, _baseConfig.PlayerSpeed, deltaTime, out Vector2 nextOnPath))
{
player.Position = nextOnPath;
}
return _events;
}The key changes are:
- The method returns early when the direction is
None, so a frame with no key does no wall work. - The clamp from Chapter 05 is gone.
TryMoveAlongPathreplaces it, and the player's position changes only when the move is accepted. - The comment marks this as step 9b of the tick. Chapter 07 adds the code for a trail when there is no wall ahead. The step numbers are explained in the order of one tick.
Open Source/Rendering/ArenaRenderer.cs. At the top of the file, add the following line below the using Microsoft.Xna.Framework.Graphics; line:
add-using Source/Rendering/ArenaRenderer.cs after=Microsoft.Xna.Framework.Graphics
csharp
using LastPerimeter.Entities;Find the Draw method and replace the whole method with the following. It fills the arena with black, then draws each segment of the wall. PrimitiveDrawing.DrawSegment is already in your project.
replace-method Source/Rendering/ArenaRenderer.cs Draw
csharp
public void Draw(SpriteBatch spriteBatch, Texture2D pixel, Rectangle arenaBounds, PlayableWallPath playableWallPath)
{
spriteBatch.Draw(pixel, arenaBounds, Color.Black);
foreach (PathSegment segment in playableWallPath.Segments)
{
PrimitiveDrawing.DrawSegment(spriteBatch, pixel, segment, Color.LightGray, 2f);
}
}Open Source/Scenes/GameplayScene.cs. Add the following method to the GameplayScene class, above the Update method. A scene's Enter runs when the scene becomes active, which is the right moment to start a level:
add-member Source/Scenes/GameplayScene.cs before=Update
csharp
public override void Enter()
{
_simulation.StartLevel();
}In the same file, find the Draw method and replace the whole method with the following:
replace-method Source/Scenes/GameplayScene.cs Draw
csharp
public override void Draw(SpriteBatch spriteBatch)
{
GameSession session = _simulation.Session;
_arenaRenderer.Draw(spriteBatch, _services.Pixel, _services.Config.ArenaBounds, session.PlayableWallPath);
_playerRenderer.Draw(spriteBatch, _services.Pixel, session.Player, Color.Cyan);
}The key changes are:
EntercallsStartLevel, so the wall exists before the first frame.Drawpasses the session's wall path toArenaRenderer, so the picture and the movement use the same wall.
Running the tests
In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 28. The 28 tests are the 19 from earlier chapters and the 9 below.
| Test | Proves |
|---|---|
InitialArenaPath_IsClosedRectangle | WAL-01 |
RebuildPlayablePath_MergesCollinearFaces | WAL-02 |
RebuildPlayablePath_AfterClaim_MatchesRemainingPlayableRegion | WAL-03 |
Contains_UsesTwoPixelTolerance | WAL-04 |
PlayerCanTraverseConnectedCornerSegment_WhenDirectionChangesAtNode | MOV-04, and WAL-05 in part |
Rectangle_HasFourNodesWithTwoSegmentsEach | WAL-06 |
PlayerCannotTraverseClaimedInterior_WhenNotDrawing | MOV-03 |
RebuiltPath_AllowsTraversalAlongRemainingBoundaryAfterClaim | WAL-03, MOV-04 |
StartLevel_PlacesPlayerOnTopLeftNode | MOV-05 |
Running the game
From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen. The player appears at the top-left corner of the arena, and the arena is drawn as a light grey outline, as in Figure 06-1.
Hold the Down arrow. The cyan dot slides down the left wall. Release it, and the dot stops. At the bottom-left corner, press Right. The dot turns the corner and follows the bottom wall. While it is on the bottom wall, press Up. Nothing happens, because the interior is not wall. Close the window with its close button. The tests prove the wall shape, the movement rules and the start position. Only the window shows that the outline and the dot look right.
The next section is optional. It replaces your files with the chapter 06 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 06 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/06-The-Wall-Path-Service"
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/06-The-Wall-Path-Service"
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: 28.
Common mistakes
- The player does not move at all.
StartLevelwas never called, so the wall path is empty and every move is refused. Check thatGameplayScene.Entercalls it. - The player sticks at a corner. The tolerance is below 2, or
Containschecks only one axis. A corner needs the band of the new wall to catch the candidate. RebuildPlayablePath_MergesCollinearFacesreports 30 segments. The merge methods were not called, or the join testcurrentStart == endwas written with the wrong operands.- A wall is missing after a claim.
IsBoundarytreats a claimed neighbour as open space. The test must be "notUnclaimed". - The build says
EnumerateUnclaimedTilesis not found. You skipped theArenaSystemstep before the wall tests. - The window shows the dot but no arena.
ArenaRenderer.Drawstill has the old signature, orGameplayScene.Drawdoes not pass the wall path.
Conclusion
In this chapter, you accomplished the following:
- Learned why the wall is rebuilt from the grid and never patched.
- Built the face test and the merge in
WallSystemV2.RebuildPlayablePath. - Gave
PathSegmentandPlayableWallPaththeir containment and snapping operations. - Added
TryMoveAlongPath, so the player slides along the wall and turns at corners. - Started each level with the player on the top-left node.
The tests now prove WAL-01 to WAL-04, WAL-06 and MOV-03 to MOV-05. The traversal tests exercise WAL-05, and Chapter 09 adds the test that snaps a finished trail back onto the wall. In the next chapter, Chapter 07: The Trail Service, the player leaves the wall and draws a trail across the open area.
Test Your Knowledge
Why does an unclaimed tile on the edge of the grid produce wall faces, when there is no tile beyond it?
Answer
IsBoundarytreats an off-grid neighbour like a claimed one. TheBoundaryanswer from Chapter 03 makes the edge of the grid behave as a wall, so no special case is needed.What breaks if the faces are not merged?
Answer
A new arena would have hundreds of 4 pixel segments. Every containment and snapping check would loop over all of them, several times a frame. The node list would also fill with points that are not corners.
Why is the whole wall rebuilt after a capture, instead of editing the old one?
Answer
A rebuilt wall is a pure function of the grid, so it is always right. Editing in place is how the first designs went stale, with a wall that no longer matched the claims.
TryMoveAlongPathnever looks at the grid. Why is that safe?Answer
The wall was derived from the grid. A point on the wall is therefore on the border of the open area, and a point off it is not a place the player may stand.
Extensions
- Change the tolerance in
PathSegment.Containsto 0.5 and rundotnet test. Which test fails first, and what does that say about the corner turn? - Write a test that claims a block in the middle of the arena and checks that the wall now has more than 4 segments. How many do you expect, and why?

