Appearance
Chapter 07: The Trail Service
In Chapter 06: The Wall Path Service, you derived the safe wall from the grid and kept the player on it. The player can now slide round the arena, but cannot leave the wall. Nothing in the game is risky yet.
In this chapter, you build the trail service. The player leaves the wall, draws a line into open space, and returns to the wall or crosses the line to close a loop.
| Figure 07-1: The chapter 07 window. A yellow trail runs from the left wall into the arena, with the player at its end. This is a drawn illustration, not a screenshot. |
Time: [TODO Simon: time estimate for chapter 07]
In this chapter, you will:
- Learn why the trail is a separate representation from the wall and the grid.
- Build
Trail, which stores its points and its own length. - Build
TrailSystemone operation at a time: start, advance, slow draw, complete, loop and cancel. - Learn the no-backtrack rule and why it exists.
- Find where two segments cross with a determinant test.
- Add the drawing branch to the simulation's tick, and raise the first two events.
Requirements in this chapter
| ID | Short name |
|---|---|
| TRL-01 | Start from the wall into unclaimed space |
| TRL-02 | Anchor on the wall, no gap |
| TRL-03 | Ignore tiny steps, track length |
| TRL-04 | No reversal |
| TRL-05 | Never into claimed tiles |
| TRL-06 | Complete on the wall after the minimum length |
| TRL-07 | Loop closure |
| TRL-08 | Slow draw latched, lost on release |
| TRL-09 | Cancel |
| MOV-06 | Half speed while slow drawing, first half |
Temporary danger
The trail is the third picture of the arena from Chapter 06. It exists only while the player is out in the open. Its State is InProgress while the player draws, Completed when it ends safely, and Cancelled when something destroys it. Chapter 11 cancels trails when the player is hit.
The trail is not stored in the grid. Claimed ground is permanent, and a trail is not. If the trail lived in the grid, every failed attempt would need to be undone tile by tile. As its own object, a failed trail is simply dropped.
Arc length
A trail is a list of points joined by straight lines. Each time a point is added, the trail adds the distance from the previous point to a running total called TotalLength. The total is the arc length: how far a walker would travel along the line. The minimum length rule uses it in this chapter. In Chapter 08, the fuse walks along the trail by this distance, so the number has to be right from the start. Figure 07-2 shows a trail of four segments with a total of 600.
| Figure 07-2: A trail as a polyline measured by arc length. Each segment adds its length to the total |
Points closer than half a pixel to the last point are ignored. The player moves in small steps, and without this rule a player who stands still would add a point every frame.
No backtracking
If the player could reverse along their own trail, the line would retrace itself and enclose nothing. The game refuses a move in the opposite direction to the last accepted one. Figure 07-3 shows the rule for a player heading right.
There is a subtle point. The last direction is recorded only when a move is accepted. If the game recorded a refused reversal, the next frame would compare against the refused direction, and the reversal would then look like a normal move. The player could back up one frame later.
| Figure 07-3: The no-backtrack rule. A move opposite to the last accepted direction is refused, and the recorded direction does not change |
Crossing your own trail
The player can also finish a trail by crossing it. When the next segment of the trail crosses an earlier one, the trail closes a loop at the crossing point. The test finds where two lines meet using determinants, which are two small sums of products. It then checks that the meeting point lies on both finite segments, and not merely on the infinite lines through them. Figure 07-4 shows the difference.
Two cases return no crossing. Parallel segments make the denominator zero, so they are rejected first. A trail of fewer than 4 points is also skipped. Four is a safe floor. The new segment starts at the last point, so the check skips the segment that ends there. With three points, the only segment left is the first one, and the new segment could reach it only by turning straight back along the second. The no-backtracking rule refuses that move, so a trail of three points cannot close a loop.
| Figure 07-4: Self-intersection. Two infinite lines always cross, but a loop closes only when the crossing lies inside both finite segments |
Slow draw
The player can hold Space or Left Shift to draw slowly. A slow trail moves at half speed and scores a bonus, which Chapter 12 adds up. The risk is that a slow trail is exposed for longer.
Slow draw is a latch. The choice is made when the trail starts. If the player releases the key mid-trail, the trail turns fast and stays fast, even if the key is pressed again. Without the latch, the player could tap the key at the end of a fast trail and collect the bonus with none of the risk.
The trail
You start with Trail, because TrailSystem is built on it. Trail is a plain object that holds the points and the length.
Trail.AddPoint(point) : void
- Takes: a point.
- Gives: nothing. The trail changes.
- Promises: the point is appended and the distance from the previous point is added to
TotalLength.- Refuses: a point within 0.5 pixels of the last one is ignored.
- Requirements: TRL-03.
Trail.ContainsPoint(point, tolerance) : bool
- Takes: a point and a tolerance, 2 pixels by default.
- Gives:
truewhen the point is within the tolerance of any segment of the trail.- Promises: the distance is measured to the segment, not only to its points.
- Refuses: nothing. A trail of fewer than 2 points gives
false.- Requirements: COL-02, which Chapter 10 uses and tests.
In the Source/Entities folder, create a new file named Trail.cs and add the following code. The state and slow flag are written in full. The two operations throw.
new-file Source/Entities/Trail.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
namespace LastPerimeter.Entities;
public sealed class Trail
{
private readonly List<Vector2> _points = new(capacity: 256);
public IReadOnlyList<Vector2> Points => _points;
public TrailState State { get; set; } = TrailState.InProgress;
public bool IsSlowDraw { get; set; }
public float TotalLength { get; private set; }
public void AddPoint(Vector2 point)
{
throw new NotImplementedException();
}
public bool ContainsPoint(Vector2 point, float tolerance = 2f)
{
throw new NotImplementedException();
}
}The key things to note are:
_pointsstarts with room for 256 points, so a normal trail never needs to grow the list.Pointsis exposed asIReadOnlyList, so other code can read the trail but cannot add to it.TotalLengthhas a private setter, so onlyAddPointcan change it.GetPointAtDistance, which the fuse needs, arrives in Chapter 08.
In the Tests/Systems folder, create a new file named TrailTests.cs and add the following code. The test adds three points. The second is 0.3 pixels from the first, so it is ignored. The length is the distance from the first point to the third.
new-file Tests/Systems/TrailTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Entities;
namespace LastPerimeter.Tests.Systems;
public sealed class TrailTests
{
[Fact]
public void AddPoint_IgnoresPointsCloserThanHalfPixel()
{
Trail trail = new();
trail.AddPoint(new Vector2(10f, 10f));
trail.AddPoint(new Vector2(10.3f, 10f));
trail.AddPoint(new Vector2(20f, 10f));
Assert.Equal(2, trail.Points.Count);
Assert.Equal(10f, trail.TotalLength, precision: 3);
}
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 28. The 28 passes are the tests from earlier chapters. The failure is your new test, which reached the stub.
Open Source/Entities/Trail.cs, find the AddPoint method and replace the whole method with the following:
replace-method Source/Entities/Trail.cs AddPoint
csharp
public void AddPoint(Vector2 point)
{
if (_points.Count > 0)
{
float distance = Vector2.Distance(_points[^1], point);
if (distance <= 0.5f)
{
return;
}
TotalLength += distance;
}
_points.Add(point);
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 29.
The key things to note are:
- The first point has nothing to measure against, so it is added without a distance.
_points[^1]is the last element of the list. It is the index from end syntax.- The
0.5fcheck comes before the length is added, so an ignored point changes neither the count nor the total.
ContainsPoint has no test in this chapter, because nothing calls it until the enemies of Chapter 10. You write it now so that the class is complete. Find the ContainsPoint method and replace the whole method with the following:
replace-method Source/Entities/Trail.cs ContainsPoint
csharp
public bool ContainsPoint(Vector2 point, float tolerance = 2f)
{
float toleranceSquared = tolerance * tolerance;
for (int index = 0; index < _points.Count - 1; index++)
{
if (DistanceSquaredToSegment(point, _points[index], _points[index + 1]) <= toleranceSquared)
{
return true;
}
}
return false;
}Add the following method to the Trail class, below the ContainsPoint method. It is a private helper, so it has no card:
add-member Source/Entities/Trail.cs after=ContainsPoint
csharp
private static float DistanceSquaredToSegment(Vector2 point, Vector2 start, Vector2 end)
{
Vector2 segment = end - start;
float segmentLengthSquared = segment.LengthSquared();
if (segmentLengthSquared <= float.Epsilon)
{
return Vector2.DistanceSquared(point, start);
}
float projection = Vector2.Dot(point - start, segment) / segmentLengthSquared;
projection = MathHelper.Clamp(projection, 0f, 1f);
Vector2 snapped = start + (segment * projection);
return Vector2.DistanceSquared(point, snapped);
}The key things to note are:
- The helper projects the point onto the segment's line, then clamps the projection between 0 and 1. The clamp keeps the nearest point on the segment, never beyond its ends.
- Distances are compared squared, so the code never takes a square root.
- A segment of zero length is handled first, because dividing by its length would fail.
Setting up the trail service
Three small pieces of data are needed before the service. The simulation raises events, the player carries a trail, and the session reports whether the trail is slow.
Open Source/Simulation/GameEvent.cs. Add the following two records below the GameEvent record. TrailStarted says whether the trail began slow. SlowDrawLost says that the player released the key.
add-type Source/Simulation/GameEvent.cs
csharp
public sealed record TrailStarted(bool SlowDraw) : GameEvent;
public sealed record SlowDrawLost : GameEvent;Open Source/Entities/Player.cs. At the top of the file, add the following line below the using Microsoft.Xna.Framework; line:
add-using Source/Entities/Player.cs after=Microsoft.Xna.Framework
csharp
using LastPerimeter.Data;Add the following property to the Player class, below the Position property:
add-member Source/Entities/Player.cs after=Position
csharp
public Direction CurrentDirection { get; set; } = Direction.None;Add the following property below the Radius property:
add-member Source/Entities/Player.cs after=Radius
csharp
public Trail? CurrentTrail { get; set; }Open Source/Data/GameSession.cs. Add the following property to the GameSession class, below the Level property:
add-member Source/Data/GameSession.cs after=Level
csharp
public bool SlowDrawActive => Player.CurrentTrail?.IsSlowDraw == true;Open Source/Data/GameConfig.cs. Add the following property to the GameConfig class, below the PlayerSpeed property. A trail must be at least 20 pixels long to count as complete.
add-member Source/Data/GameConfig.cs after=PlayerSpeed
csharp
public float MinimumTrailLength { get; init; } = 20f;Open Tests/TestHelpers/TestConfigFactory.cs. The small test arena would never hold a 20 pixel trail, so tests use a minimum of 4 pixels. In the Create method, find this line:
find Tests/TestHelpers/TestConfigFactory.cs
csharp
PlayerSpeed = 100f,Add the following line directly after it:
csharp
MinimumTrailLength = 4f,Building the trail service
TrailSystem owns the one active trail. Its first listing is the shell: the constant, the minimum length, the constructor and two properties are written, and every operation throws.
In the Source/Systems folder, create a new file named TrailSystem.cs and add the following code:
new-file Source/Systems/TrailSystem.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
namespace LastPerimeter.Systems;
public sealed class TrailSystem
{
public const float SlowDrawSpeedFactor = 0.5f;
private readonly float _minimumTrailLength;
public TrailSystem(float minimumTrailLength)
{
_minimumTrailLength = minimumTrailLength;
}
public Trail? ActiveTrail { get; private set; }
public bool HasActiveTrail => ActiveTrail is not null;
public bool TryStart(Vector2 wallAnchor, Vector2 firstInteriorPoint, bool slowDraw = false)
{
throw new NotImplementedException();
}
public void AppendPoint(Vector2 point)
{
throw new NotImplementedException();
}
public void UpdateSlowDraw(bool slowDrawHeld)
{
throw new NotImplementedException();
}
public bool CanAdvance(Vector2 intendedPosition, ArenaSystem arenaSystem, Direction direction = Direction.None, Direction lastDirection = Direction.None)
{
throw new NotImplementedException();
}
public bool TryGetSelfIntersection(Vector2 nextPoint, out Vector2 intersectionPoint)
{
throw new NotImplementedException();
}
public bool CanCompleteOnPath(Vector2 position, PlayableWallPath playableWallPath)
{
throw new NotImplementedException();
}
public Trail Complete(Vector2 snappedEndPoint)
{
throw new NotImplementedException();
}
public void Cancel()
{
throw new NotImplementedException();
}
}The key things to note are:
SlowDrawSpeedFactoris a constant of 0.5. The simulation multiplies the player's speed by it for a slow trail, which is the first half of MOV-06.- The service holds at most one trail, in
ActiveTrail. A trail exists when the property is notnull. - From the
LastPerimeterfolder, rundotnet build. The build should succeed, which proves the stubs compile.
Starting a trail
A trail starts at a point on the wall and continues into open space. The first point is the wall anchor, so the drawn line has no gap at the wall.
TrailSystem.TryStart(wallAnchor, firstInteriorPoint, slowDraw) : bool
- Takes: a point on the wall, the first point in the open area, and whether slow draw is held.
- Gives:
truewhen a trail started.- Promises: the trail begins with the anchor and the first point, and latches the slow flag.
- Refuses: a second trail while one is active gives
false.- Requirements: TRL-01, TRL-02, TRL-08.
TrailSystem.AppendPoint(point) : void
- Takes: a point.
- Gives: nothing. The active trail changes.
- Promises: the point is added to the active trail.
- Refuses: nothing happens when there is no trail. No test covers that refusal in this chapter.
- Requirements: TRL-03.
In the Tests/Systems folder, create a new file named TrailSystemTests.cs and add the following code. The file starts with one test. It lists all the using lines that later tests need.
new-file Tests/Systems/TrailSystemTests.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 TrailSystemTests
{
[Fact]
public void StartTrail_FromWallPath_AnchorsToPath()
{
TrailSystem trailSystem = new(4f);
bool started = trailSystem.TryStart(new Vector2(0, 0), new Vector2(4, 0));
Assert.True(started);
Assert.NotNull(trailSystem.ActiveTrail);
Assert.Equal(new Vector2(0, 0), trailSystem.ActiveTrail!.Points[0]);
}
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 29.
Open Source/Systems/TrailSystem.cs. Find the TryStart method and replace the whole method with the following:
replace-method Source/Systems/TrailSystem.cs TryStart
csharp
public bool TryStart(Vector2 wallAnchor, Vector2 firstInteriorPoint, bool slowDraw = false)
{
if (ActiveTrail is not null)
{
return false;
}
Trail trail = new() { IsSlowDraw = slowDraw };
trail.AddPoint(wallAnchor);
trail.AddPoint(firstInteriorPoint);
ActiveTrail = trail;
return true;
}Find the AppendPoint method and replace the whole method with the following:
replace-method Source/Systems/TrailSystem.cs AppendPoint
csharp
public void AppendPoint(Vector2 point)
{
ActiveTrail?.AddPoint(point);
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 30.
The key things to note are:
- The method refuses first. A second trail would replace the first, so an active trail stops it.
- Both points go in through
AddPoint, so the length is tracked from the first segment. AppendPointuses?., so a call with no trail does nothing and never throws.
Advancing a trail
Each frame, the simulation asks whether the trail may advance to the position the player wants. Two rules say no. The move must not reverse, and the target must not be claimed.
TrailSystem.CanAdvance(intendedPosition, arenaSystem, direction, lastDirection) : bool
- Takes: the position the player wants, the arena, the new direction and the last accepted direction.
- Gives:
truewhen the target is unclaimed.- Promises: a move that is not a reversal, onto an unclaimed tile, is allowed.
- Refuses: a reversal, a claimed target, or no active trail gives
false.- Requirements: TRL-04, TRL-05.
Open Tests/Systems/TrailSystemTests.cs. Add the following test to the TrailSystemTests class, above the StartTrail_FromWallPath_AnchorsToPath test. A trail has gone right, so Left is refused, while Right and Down are allowed.
add-member Tests/Systems/TrailSystemTests.cs before=StartTrail_FromWallPath_AnchorsToPath
csharp
[Fact]
public void CanAdvance_BlocksReversal_OntoActiveTrail()
{
ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));
TrailSystem trailSystem = new(4f);
trailSystem.TryStart(new Vector2(0, 8), new Vector2(4, 8));
Assert.False(trailSystem.CanAdvance(new Vector2(2, 8), arena, Direction.Left, Direction.Right));
Assert.True(trailSystem.CanAdvance(new Vector2(6, 8), arena, Direction.Right, Direction.Right));
Assert.True(trailSystem.CanAdvance(new Vector2(4, 12), arena, Direction.Down, Direction.Right));
}Add the following test below the StartTrail_FromWallPath_AnchorsToPath test. It claims one tile and checks that a position inside it is refused:
add-member Tests/Systems/TrailSystemTests.cs after=StartTrail_FromWallPath_AnchorsToPath
csharp
[Fact]
public void CanAdvance_RefusesClaimedTile()
{
ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));
Region claimed = new();
claimed.Tiles.Add(new Point(2, 2));
arena.ApplyClaimResult(new ClaimResult(claimed, new Region(), []));
TrailSystem trailSystem = new(4f);
trailSystem.TryStart(new Vector2(0, 8), new Vector2(4, 8));
Assert.False(trailSystem.CanAdvance(new Vector2(9, 9), arena, Direction.Right, Direction.Right));
Assert.True(trailSystem.CanAdvance(new Vector2(6, 8), arena, Direction.Right, Direction.Right));
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 2 and Passed: 30.
Open Source/Systems/TrailSystem.cs, find the CanAdvance method and replace the whole method with the following:
replace-method Source/Systems/TrailSystem.cs CanAdvance
csharp
public bool CanAdvance(Vector2 intendedPosition, ArenaSystem arenaSystem, Direction direction = Direction.None, Direction lastDirection = Direction.None)
{
if (ActiveTrail is null)
{
return false;
}
// The player cannot back up along their own active trail; reversing
// re-traces the drawn line without enclosing anything.
if (direction != Direction.None && lastDirection != Direction.None && direction == lastDirection.Opposite())
{
return false;
}
if (!arenaSystem.IsUnclaimedWorld(intendedPosition))
{
return false;
}
return true;
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 32.
The key things to note are:
- A reversal needs both directions to be real.
Direction.Nonehas no opposite, so the first move of a trail is never a reversal. Opposite()is the extension method already in yourEnums.cs.- A claimed target is refused through
IsUnclaimedWorld, which also refuses a position outside the arena. CanAdvancedoes not record the direction. The simulation does that, and only when the move is accepted.
Slow draw
The latch from earlier is two small operations. TryStart already stores the flag. UpdateSlowDraw clears it when the key is released.
TrailSystem.UpdateSlowDraw(slowDrawHeld) : void
- Takes: whether the slow draw key is held.
- Gives: nothing. The active trail may change.
- Promises: releasing the key clears the slow flag for good.
- Refuses: it never sets the flag back, and does nothing with no trail.
- Requirements: TRL-08.
In the Tests/Systems folder, create a new file named TrailSlowDrawTests.cs and add the following code. Two of the three tests check what TryStart already does, so they pass at once. The third releases the key, presses it again, and checks that the trail stayed fast.
new-file Tests/Systems/TrailSlowDrawTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Entities;
using LastPerimeter.Systems;
namespace LastPerimeter.Tests.Systems;
public sealed class TrailSlowDrawTests
{
[Fact]
public void TryStart_LatchesSlowDrawOntoTrail()
{
TrailSystem trailSystem = new(minimumTrailLength: 20f);
trailSystem.TryStart(new Vector2(0f, 0f), new Vector2(0f, 5f), slowDraw: true);
Assert.True(trailSystem.ActiveTrail!.IsSlowDraw);
}
[Fact]
public void TryStart_DefaultsToFastDraw()
{
TrailSystem trailSystem = new(minimumTrailLength: 20f);
trailSystem.TryStart(new Vector2(0f, 0f), new Vector2(0f, 5f));
Assert.False(trailSystem.ActiveTrail!.IsSlowDraw);
}
[Fact]
public void UpdateSlowDraw_ReleasingTheInputDemotesTheTrailPermanently()
{
TrailSystem trailSystem = new(minimumTrailLength: 20f);
trailSystem.TryStart(new Vector2(0f, 0f), new Vector2(0f, 5f), slowDraw: true);
trailSystem.UpdateSlowDraw(slowDrawHeld: true);
Assert.True(trailSystem.ActiveTrail!.IsSlowDraw);
trailSystem.UpdateSlowDraw(slowDrawHeld: false);
trailSystem.UpdateSlowDraw(slowDrawHeld: true);
Trail completed = trailSystem.Complete(new Vector2(0f, 40f));
Assert.False(completed.IsSlowDraw);
}
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 34.
Open Source/Systems/TrailSystem.cs, find the UpdateSlowDraw method and replace the whole method with the following:
replace-method Source/Systems/TrailSystem.cs UpdateSlowDraw
csharp
public void UpdateSlowDraw(bool slowDrawHeld)
{
if (ActiveTrail is not null && !slowDrawHeld)
{
ActiveTrail.IsSlowDraw = false;
}
}Run dotnet test from the LastPerimeter folder. The summary line should still report Failed: 1 and Passed: 34. The third test calls Complete to read the final flag, and Complete is still a stub. The test stays red until the next group.
The key things to note are:
- The method only ever writes
false. Nothing in the service writestrueafter the start, which is the latch. - The test reads the final flag through
Complete, which you write in the next group. That is why it is still red.
Completing and cancelling a trail
A trail ends in one of three ways. It reaches the wall, it crosses itself, or something cancels it. This group handles the first and last.
TrailSystem.CanCompleteOnPath(position, playableWallPath) : bool
- Takes: a position and the wall path.
- Gives:
truewhen the position is on the wall.- Promises: the trail must be at least the minimum length.
- Refuses: a shorter trail, or no trail, gives
false.- Requirements: TRL-06.
TrailSystem.Complete(snappedEndPoint) : Trail
- Takes: the end point, already snapped to the wall.
- Gives: the finished trail.
- Promises: the end point is appended, the state is
Completed, and the active trail is cleared.- Refuses: it throws with no active trail, because that is a wiring bug. No test covers the throw in this chapter.
- Requirements: TRL-06.
TrailSystem.Cancel() : void
- Takes: nothing.
- Gives: nothing. The trail changes.
- Promises: the trail is marked
Cancelledand cleared.- Refuses: nothing happens with no trail.
- Requirements: TRL-09.
Open Tests/Systems/TrailSystemTests.cs. Add the following test below the StartTrail_FromWallPath_AnchorsToPath test. It draws a short trail and checks that it can finish on the wall and that the end lands exactly on the snapped point.
add-member Tests/Systems/TrailSystemTests.cs before=CanAdvance_RefusesClaimedTile
csharp
[Fact]
public void CompleteTrail_OnPathReconnect_SnapsWithoutGap()
{
TrailSystem trailSystem = new(4f);
PlayableWallPath path = new(new[] { new PathSegment(new Vector2(0, 0), new Vector2(20, 0)) });
trailSystem.TryStart(new Vector2(0, 0), new Vector2(4, 4));
trailSystem.AppendPoint(new Vector2(8, 4));
trailSystem.AppendPoint(new Vector2(12, 0));
Assert.True(trailSystem.CanCompleteOnPath(new Vector2(12, 0), path));
Trail completed = trailSystem.Complete(path.Snap(new Vector2(12, 0)));
Assert.Equal(new Vector2(12, 0), completed.Points[^1]);
}Add the following test below the CanAdvance_RefusesClaimedTile test. Two services see the same trail, but one demands 100 pixels and the other 4. Only the second may complete.
add-member Tests/Systems/TrailSystemTests.cs after=CanAdvance_RefusesClaimedTile
csharp
[Fact]
public void CanCompleteOnPath_RequiresMinimumLength()
{
PlayableWallPath path = new(new[] { new PathSegment(new Vector2(0, 0), new Vector2(20, 0)) });
TrailSystem shortRule = new(100f);
TrailSystem longRule = new(4f);
foreach (TrailSystem system in new[] { shortRule, longRule })
{
system.TryStart(new Vector2(0, 0), new Vector2(4, 4));
system.AppendPoint(new Vector2(8, 4));
system.AppendPoint(new Vector2(12, 0));
}
Assert.False(shortRule.CanCompleteOnPath(new Vector2(12, 0), path));
Assert.True(longRule.CanCompleteOnPath(new Vector2(12, 0), path));
}Add the following test below the CanCompleteOnPath_RequiresMinimumLength test:
add-member Tests/Systems/TrailSystemTests.cs after=CanCompleteOnPath_RequiresMinimumLength
csharp
[Fact]
public void Cancel_MarksTrailCancelled()
{
TrailSystem trailSystem = new(4f);
trailSystem.TryStart(new Vector2(0, 0), new Vector2(4, 0));
Trail trail = trailSystem.ActiveTrail!;
trailSystem.Cancel();
Assert.Equal(TrailState.Cancelled, trail.State);
Assert.False(trailSystem.HasActiveTrail);
trailSystem.Cancel();
}The slow draw test from the last group is also waiting for Complete, so four tests are red. In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 4 and Passed: 34.
Open Source/Systems/TrailSystem.cs. Find the CanCompleteOnPath method and replace the whole method with the following:
replace-method Source/Systems/TrailSystem.cs CanCompleteOnPath
csharp
public bool CanCompleteOnPath(Vector2 position, PlayableWallPath playableWallPath)
{
return ActiveTrail is not null && ActiveTrail.TotalLength >= _minimumTrailLength && playableWallPath.Contains(position);
}Find the Complete method and replace the whole method with the following:
replace-method Source/Systems/TrailSystem.cs Complete
csharp
public Trail Complete(Vector2 snappedEndPoint)
{
if (ActiveTrail is null)
{
throw new InvalidOperationException("No active trail to complete.");
}
ActiveTrail.AddPoint(snappedEndPoint);
ActiveTrail.State = TrailState.Completed;
Trail completedTrail = ActiveTrail;
ActiveTrail = null;
return completedTrail;
}Find the Cancel method and replace the whole method with the following:
replace-method Source/Systems/TrailSystem.cs Cancel
csharp
public void Cancel()
{
if (ActiveTrail is not null)
{
ActiveTrail.State = TrailState.Cancelled;
ActiveTrail = null;
}
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 38.
The key things to note are:
CanCompleteOnPathusesContainsfrom the wall path, so the 2 pixel tolerance of Chapter 06 applies when the trail meets the wall.Completecopies the trail into a local variable before it clearsActiveTrail. Otherwise the method would have nothing to return.Cancelkeeps the trail object alive for the caller who holds it. It only changes the state and clears the service's reference, which is what the test checks.
Closing a loop
The last operation finds where the next segment of the trail would cross an earlier one.
TrailSystem.TryGetSelfIntersection(nextPoint, out intersectionPoint) : bool
- Takes: the point the trail would move to.
- Gives:
trueand the crossing point.- Promises: the new segment, from the last point to
nextPoint, is tested against each earlier segment except its own neighbour.- Refuses: a trail of fewer than 4 points, or parallel segments, gives
false.- Requirements: TRL-07.
In the Tests/Systems folder, create a new file named TrailLoopTests.cs and add the following code. The trail runs right, down, left, then up the left side to (0, 2). The next move, to the right along row 2, crosses the earlier right-hand side at (8, 2). The test expects that point.
new-file Tests/Systems/TrailLoopTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Systems;
namespace LastPerimeter.Tests.Systems;
public sealed class TrailLoopTests
{
[Fact]
public void SelfIntersection_IsDetected_AtLoopClosure()
{
TrailSystem trailSystem = new(4f);
trailSystem.TryStart(new Vector2(0, 0), new Vector2(8, 0));
trailSystem.AppendPoint(new Vector2(8, 8));
trailSystem.AppendPoint(new Vector2(0, 8));
trailSystem.AppendPoint(new Vector2(0, 2));
bool intersects = trailSystem.TryGetSelfIntersection(new Vector2(8, 2), out Vector2 intersection);
Assert.True(intersects);
Assert.Equal(new Vector2(8, 2), intersection);
}
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 38.
Open Source/Systems/TrailSystem.cs. Find the TryGetSelfIntersection method and replace the whole method with the following:
replace-method Source/Systems/TrailSystem.cs TryGetSelfIntersection
csharp
public bool TryGetSelfIntersection(Vector2 nextPoint, out Vector2 intersectionPoint)
{
intersectionPoint = Vector2.Zero;
if (ActiveTrail is null || ActiveTrail.Points.Count < 4)
{
return false;
}
Vector2 segmentStart = ActiveTrail.Points[^1];
for (int index = 0; index < ActiveTrail.Points.Count - 2; index++)
{
if (TryGetSegmentIntersection(ActiveTrail.Points[index], ActiveTrail.Points[index + 1], segmentStart, nextPoint, out intersectionPoint))
{
return true;
}
}
return false;
}Add the following method to the end of the TrailSystem class. It solves the two line equations and checks that the result lies on both segments:
add-member Source/Systems/TrailSystem.cs at=end
csharp
private static bool TryGetSegmentIntersection(Vector2 a1, Vector2 a2, Vector2 b1, Vector2 b2, out Vector2 intersection)
{
intersection = Vector2.Zero;
float denominator = ((a1.X - a2.X) * (b1.Y - b2.Y)) - ((a1.Y - a2.Y) * (b1.X - b2.X));
if (Math.Abs(denominator) < 0.0001f)
{
return false;
}
float determinantA = (a1.X * a2.Y) - (a1.Y * a2.X);
float determinantB = (b1.X * b2.Y) - (b1.Y * b2.X);
float x = ((determinantA * (b1.X - b2.X)) - ((a1.X - a2.X) * determinantB)) / denominator;
float y = ((determinantA * (b1.Y - b2.Y)) - ((a1.Y - a2.Y) * determinantB)) / denominator;
Vector2 candidate = new(x, y);
if (!PointOnSegment(candidate, a1, a2) || !PointOnSegment(candidate, b1, b2))
{
return false;
}
intersection = candidate;
return true;
}Add the following method to the end of the TrailSystem class. It is the finite-segment check from Figure 07-4:
add-member Source/Systems/TrailSystem.cs at=end
csharp
private static bool PointOnSegment(Vector2 point, Vector2 start, Vector2 end)
{
const float tolerance = 0.5f;
return point.X >= Math.Min(start.X, end.X) - tolerance
&& point.X <= Math.Max(start.X, end.X) + tolerance
&& point.Y >= Math.Min(start.Y, end.Y) - tolerance
&& point.Y <= Math.Max(start.Y, end.Y) + tolerance;
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 39.
The key things to note are:
- The loop stops at
Count - 2, so the newest segment is never tested against the one it joins. - The new segment starts at the last point and ends at
nextPoint. It has not been added to the trail yet. - A denominator close to zero means the lines are parallel, so the method returns
falsebefore it divides. PointOnSegmentallows half a pixel of slack, so a crossing at a segment's end point is not lost to rounding.- The determinant formula is the standard line-intersection formula, so you may trust it. To see it work, take the numbers from the test. The earlier segment is
a1 = (8, 0)toa2 = (8, 8), and the new segment isb1 = (0, 2)tob2 = (8, 2). The denominator is(0 * 0) - (-8 * -8) = -64.determinantAis(8 * 8) - (0 * 8) = 64anddeterminantBis(0 * 2) - (2 * 8) = -16. Thenx = ((64 * -8) - (0 * -16)) / -64 = 8andy = ((64 * 0) - (-8 * -16)) / -64 = 2. That is the point (8, 2) that the test expects.
Wiring it into the game
The service is complete, but nothing calls it. The simulation's Tick decides what a frame means. It now has three situations. The player is on the wall and moves along it. The player is on the wall and pushes into open space, which starts a trail. Or the player is drawing, which advances, completes or closes the trail.
A completed trail just ends in this chapter. The trail is dropped and the player is put back on the wall, with no claim. This is deliberate scaffolding. Chapter 09 turns the completed trail into a capture at the same place.
The Tick method is long, so you build it from three small methods. Open Source/Simulation/GameplaySimulation.cs. Add the following field below the _events field:
add-member Source/Simulation/GameplaySimulation.cs after=_events
csharp
private readonly TrailSystem _trails;In the same file, the constructor must build the trail service. Find this line in the GameplaySimulation constructor:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
_arena = new ArenaSystem(baseConfig);Add the following line directly after it:
csharp
_trails = new TrailSystem(baseConfig.MinimumTrailLength);Add the following method below the Tick method. It runs while a trail is active. It tries to finish on the wall, then to cross the trail, then to advance:
add-member Source/Simulation/GameplaySimulation.cs after=Tick
csharp
private void TickWhileDrawing(Direction direction, Vector2 intendedPosition, InputState input)
{
Player player = _session.Player;
if (_trails.CanCompleteOnPath(intendedPosition, _session.PlayableWallPath))
{
// 8c. Reconnect to the wall.
CompleteTrail(_session.PlayableWallPath.Snap(intendedPosition), snappedToPath: true);
}
else if (_trails.TryGetSelfIntersection(intendedPosition, out Vector2 loopIntersection))
{
// 8d. Cross the own trail.
CompleteTrail(loopIntersection, snappedToPath: false);
}
else if (_trails.CanAdvance(intendedPosition, _arena, direction, player.CurrentDirection))
{
// 8e. Advance the trail.
player.Position = intendedPosition;
_trails.AppendPoint(player.Position);
bool wasSlowDraw = _session.SlowDrawActive;
_trails.UpdateSlowDraw(input.IsSlowDrawHeld);
if (wasSlowDraw && !_session.SlowDrawActive)
{
_events.Add(new SlowDrawLost());
}
player.CurrentTrail = _trails.ActiveTrail;
// Only record the heading when the move was accepted. Recording a
// blocked reversal would defeat the no-backtrack check next frame.
player.CurrentDirection = direction;
}
}Add the following method below TickWhileDrawing. It runs when there is no trail. It tries to move along the wall, and if that fails, it tries to start a trail:
add-member Source/Simulation/GameplaySimulation.cs after=TickWhileDrawing
csharp
private void TickOnWall(Direction direction, Vector2 intendedPosition, float speed, float deltaTime, InputState input)
{
Player player = _session.Player;
// 9b. Move along the wall.
if (_movement.TryMoveAlongPath(_session.PlayableWallPath, player.Position, direction, speed, deltaTime, out Vector2 nextOnPath))
{
player.Position = nextOnPath;
player.CurrentDirection = direction;
return;
}
// 9c. Otherwise try to start a trail into open space.
if (_session.PlayableWallPath.Contains(player.Position)
&& _arena.IsUnclaimedWorld(intendedPosition)
&& _trails.TryStart(_session.PlayableWallPath.Snap(player.Position), intendedPosition, input.IsSlowDrawHeld))
{
player.Position = intendedPosition;
player.CurrentTrail = _trails.ActiveTrail;
player.CurrentDirection = direction;
_events.Add(new TrailStarted(_session.SlowDrawActive));
}
}Add the following method below TickOnWall. It is the scaffolding that Chapter 09 replaces:
add-member Source/Simulation/GameplaySimulation.cs after=TickOnWall
csharp
// A completed trail just ends for now. Chapter 09 turns it into a claim here.
private void CompleteTrail(Vector2 endPoint, bool snappedToPath)
{
Player player = _session.Player;
Trail completedTrail = _trails.Complete(endPoint);
player.Position = snappedToPath ? endPoint : completedTrail.Points[0];
player.CurrentTrail = null;
}The key things to note are:
TickWhileDrawingchecks in order: reconnect to the wall, cross the trail, advance. The first rule that applies wins.- The direction is stored in
player.CurrentDirectiononly inside the accepted branches. This is the rule from "No backtracking". TickOnWallstarts a trail only when the player is on the wall, the target is unclaimed, andTryStartagrees.CompleteTrailhas a comment saying that Chapter 09 turns the trail into a claim.
Next, a scenario test. A scenario drives the whole simulation with scripted key presses. Open Tests/TestHelpers/ScriptedInput.cs. Add the following method to the end of the ScriptedInput class. It holds Right for 4 frames, Down for 8, Right for 4 and Up for 8, which draws a rectangle out from the top wall and back:
add-member Tests/TestHelpers/ScriptedInput.cs at=end
csharp
// Right 4, Down 8, Right 4, Up 8: out from the top wall and back, enclosing a 20 by 40 block.
public static List<GameEvent> DrawRectangleFromTopWall(GameplaySimulation simulation)
{
List<GameEvent> raised = [];
raised.AddRange(Run(simulation, Right, 4));
raised.AddRange(Run(simulation, Down, 8));
raised.AddRange(Run(simulation, Right, 4));
raised.AddRange(Run(simulation, Up, 8));
return raised;
}In the Tests/Simulation folder, create a new file named TrailScenarioTests.cs and add the following code. It checks that a trail started, that none is active at the end, and that the player is back on the top wall at (40, 0).
new-file Tests/Simulation/TrailScenarioTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Simulation;
using LastPerimeter.Tests.TestHelpers;
namespace LastPerimeter.Tests.Simulation;
public sealed class TrailScenarioTests
{
[Fact]
public void Tick_DrawingOutAndBackToWall_CompletesTheTrail()
{
GameplaySimulation sim = SimulationBuilder.Create();
List<GameEvent> events = ScriptedInput.DrawRectangleFromTopWall(sim);
Assert.Contains(events, e => e is TrailStarted { SlowDraw: false });
Assert.Null(sim.Session.Player.CurrentTrail);
Assert.Equal(new Vector2(40, 0), sim.Session.Player.Position);
}
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 39. The old Tick still only moves along the wall.
Find the Tick method in Source/Simulation/GameplaySimulation.cs 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);
// 6. Nothing to do with no input and no trail.
Trail? activeTrail = _trails.ActiveTrail;
if (direction == Direction.None && activeTrail is null)
{
return _events;
}
// 7. Where the player would like to be after this frame.
float speed = _baseConfig.PlayerSpeed * (_session.SlowDrawActive ? TrailSystem.SlowDrawSpeedFactor : 1f);
Vector2 intendedPosition = _movement.CalculateNextPosition(_session.Player.Position, direction, speed, deltaTime);
if (activeTrail is not null)
{
TickWhileDrawing(direction, intendedPosition, input);
}
else
{
TickOnWall(direction, intendedPosition, speed, deltaTime, input);
}
return _events;
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 40.
The key changes are:
- The early return now needs no key and no trail. While a trail is active the method keeps running with no key, so the slow draw check still happens.
- The speed is halved while a slow trail is active, using
SlowDrawSpeedFactor. - The work is split between
TickWhileDrawingandTickOnWall. - The step numbers in the comments are explained in the order of one tick.
Drawing the trail
The scene must draw the trail, or the player will not see it. In the Source/Rendering folder, create a new file named TrailRenderer.cs and add the following code. It draws a line between each pair of points, and does nothing for a missing or one-point trail.
new-file Source/Rendering/TrailRenderer.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Entities;
namespace LastPerimeter.Rendering;
public sealed class TrailRenderer
{
public void Draw(SpriteBatch spriteBatch, Texture2D pixel, Trail? trail, Color color, float thickness = 3f)
{
if (trail is null || trail.Points.Count < 2)
{
return;
}
for (int index = 0; index < trail.Points.Count - 1; index++)
{
PrimitiveDrawing.DrawLine(spriteBatch, pixel, trail.Points[index], trail.Points[index + 1], color, thickness);
}
}
}Open Source/Scenes/GameplayScene.cs. Add the following field to the GameplayScene class, below the _arenaRenderer field:
add-member Source/Scenes/GameplayScene.cs after=_arenaRenderer
csharp
private readonly TrailRenderer _trailRenderer = new();In the same file, the Draw method must draw the trail after the wall and before the player. A normal trail is yellow and 3 pixels thick. A slow trail is pale yellow and 5 pixels thick. Find this line in the Draw method:
find Source/Scenes/GameplayScene.cs
csharp
_playerRenderer.Draw(spriteBatch, _services.Pixel, session.Player, Color.Cyan);Add the following lines directly above it:
csharp
_trailRenderer.Draw(
spriteBatch,
_services.Pixel,
session.Player.CurrentTrail,
session.SlowDrawActive ? Color.LightYellow : Color.Yellow,
session.SlowDrawActive ? 5f : 3f);The key changes are:
- The trail is drawn after the wall and before the player, so the player dot sits on top.
- The colour and thickness depend on
SlowDrawActive.
Running the tests
In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 40. The 40 tests are the 28 from earlier chapters and the 12 below.
| Test | Proves |
|---|---|
AddPoint_IgnoresPointsCloserThanHalfPixel | TRL-03 |
TryStart_DefaultsToFastDraw | TRL-08 |
TryStart_LatchesSlowDrawOntoTrail | TRL-08 |
StartTrail_FromWallPath_AnchorsToPath | TRL-01, TRL-02 |
CanAdvance_BlocksReversal_OntoActiveTrail | TRL-04 |
CanAdvance_RefusesClaimedTile | TRL-05 |
UpdateSlowDraw_ReleasingTheInputDemotesTheTrailPermanently | TRL-08 |
CanCompleteOnPath_RequiresMinimumLength | TRL-06 |
CompleteTrail_OnPathReconnect_SnapsWithoutGap | TRL-06, WAL-05 |
SelfIntersection_IsDetected_AtLoopClosure | TRL-07 |
Cancel_MarksTrailCancelled | TRL-09 |
Tick_DrawingOutAndBackToWall_CompletesTheTrail | TRL-01, TRL-06 |
Running the game
From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen. The player starts at the top-left corner.
Hold Down until the dot is partway down the left wall, then release it. Hold Right. A yellow trail follows the dot into the arena, as in Figure 07-1. Hold Down to turn, then Left to head back to the wall. When the dot touches the wall, the trail disappears and the dot sits on the wall. Nothing is claimed, because Chapter 09 adds that. The test counts prove the trail rules. Only the window shows the yellow trail and its thickness.
Start another trail, and hold Space while you do. The trail is thicker and paler, and the dot moves at half speed. Release Space mid-trail. The trail turns thin and yellow, and the dot speeds up. Press Space again: it stays fast. While drawing, press the direction opposite to the one you are moving in. The dot does not move. Close the window with its close button.
The next section is optional. It replaces your files with the chapter 07 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 07 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/07-The-Trail-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/07-The-Trail-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: 40.
Common mistakes
- The player cannot leave the wall.
TickOnWalldid not start a trail. Check that the target tile is unclaimed and thatTryStartis reached afterTryMoveAlongPathfails. - The player can back up along the trail.
player.CurrentDirectionis set outside the accepted branch, so a refused reversal overwrites it. - A slow trail turns fast at once.
UpdateSlowDrawis called with the wrong flag. It needsinput.IsSlowDrawHeld. - The trail never completes at the wall. The trail is shorter than
MinimumTrailLength, orTestConfigFactorydoes not set it to 4. - A loop never closes.
TryGetSelfIntersectionneeds at least 4 points. A trail of three points cannot close a loop, because the only way back to its first segment is a reversal. - The build says
TrailStartedis not found. The records were added to the wrong file. They belong inSource/Simulation/GameEvent.cs.
Conclusion
In this chapter, you accomplished the following:
- Learned why the trail is a separate representation from the wall and the grid.
- Built
Trail, which stores its points and its own length. - Built
TrailSystemone operation at a time: start, advance, slow draw, complete, loop and cancel. - Learned the no-backtrack rule and why the direction is recorded only on an accepted move.
- Found where two segments cross with a determinant test.
- Added the drawing branch to the simulation's tick, and raised the first two events.
The tests now prove TRL-01 to TRL-09. A completed trail only ends, because Chapter 09 adds the claim. In the next chapter, Chapter 08: The Fuse Service, a fuse starts burning along the trail and forces the player to finish it.
Test Your Knowledge
Why is the move direction recorded only when a move is accepted?
Answer
Recording a refused reversal would make the next frame compare against the wrong direction. The reversal would then look like a normal move, and the player could back up.
Why does a trail need 4 points before a self-intersection can count?
Answer
The new segment starts at the last point, and the check skips the segment that ends there, because two segments that share an end point always touch. With three points, the first segment is the only one left. The new segment could reach it only by turning straight back, which the no-backtracking rule refuses. So 4 is a safe floor below which no loop can enclose anything.
Why is slow draw lost for good on release, instead of following the key?
Answer
Otherwise a player could tap slow draw at the end of a fast trail and earn the bonus with none of the risk.
Why does the crossing test check that the point is on both segments?
Answer
Two lines that are not parallel always meet somewhere. The meeting point may lie beyond the end of one segment, where no loop has been closed.
Extensions
- Change
MinimumTrailLengthinGameConfigto 200 and run the game. Try to complete a short trail. What does the player do when the trail touches the wall? - Write a test that calls
TryStarttwice and checks that the second call returnsfalseand leaves the first trail in place.

