Appearance
Chapter 08: The Fuse Service
In Chapter 07: The Trail Service, you let the player leave the wall and draw a trail through open space. The trail is dangerous but nothing yet forces the player to hurry. A player could stop in the middle of the arena and think for as long as they like.
In this chapter, you build the fuse. When the player stops mid-trail, a spark starts at the beginning of the trail and burns towards them. Stopping becomes a risk, and that risk is the pressure the whole game runs on.
| Figure 08-1: The chapter 08 window. The player has drawn a trail and stopped, and a red spark is burning along it. This is a drawn illustration, not a screenshot. |
Time: [TODO Simon: time estimate for chapter 08]
In this chapter, you will:
- Learn why the fuse turns time into distance along the trail.
- Find a point at any distance along a trail by walking its segments.
- Build
FuseSystemas a small state machine with three states: idle, warning and burning. - Learn why the fuse watches what the player did, and not which key the player pressed.
- Add steps 3, 8a and 9a to the tick of
GameplaySimulation.
Requirements in this chapter
| ID | Short name |
|---|---|
| TRL-10 | A point at any distance along the trail |
| FUS-01 | Warn after a short stop |
| FUS-02 | Ignite at the start of the trail |
| FUS-03 | Burn along the trail at a fixed speed |
| FUS-04 | Pause while the player moves |
| FUS-05 | Kill when the burn reaches the end of the trail |
| FUS-06 | Put out when the trail ends |
| FUS-07 | Movement measured by position, not input |
Pressure as space
A countdown on its own is easy to ignore. A number in the corner of the screen asks the player to watch it. The fuse works differently. It turns the time the player has stopped into a distance along the line the player drew. The spark is a thing in the arena, on the exact path of the danger, and it moves where the player can see it.
The spark starts at the first point of the trail, the point on the wall where the trail began. It then burns along the trail towards the player. When the spark reaches the end of the trail, it has caught up with the player. A short trail is burnt quickly and a long trail gives the player more time, which is a fair trade for the risk of drawing it.
The timeline
The fuse has three numbers, and GameConfig holds them. FuseWarningDelaySeconds is 1.0. FuseTriggerDelaySeconds is 2.0. FuseBurnSpeed is 60 pixels per second. Figure 08-2 shows what happens as the player stands still.
| Figure 08-2: The fuse timeline. One second of stillness warns, two seconds ignite the spark, and the spark then burns at 60 pixels per second |
After one second without movement, the fuse is warning. The player has a second to move before anything burns. After two seconds, the fuse ignites: the spark appears at the first point of the trail. From then on, each frame moves the spark forward by FuseBurnSpeed * deltaTime pixels. A trail 180 pixels long burns for 3 seconds after ignition, because 180 divided by 60 is 3.
Pause, not reset
When the player moves again, what should the fuse do? There are two choices. It could go back to the start, so the spark vanishes and the whole delay begins again. Or it could stay where it is and wait.
This game pauses a spark that is already burning. Moving holds the spark where it is, and stopping again lets it continue. A reset would let the player escape a nearly finished burn with one step, and the pressure would vanish. A pause keeps the danger, and still rewards the player for moving.
Before ignition, there is nothing burning yet, so moving only restarts the stopped timer from zero. The warning must be earned again. The timeline in Figure 08-2 shows both cases in its green notes.
Displacement, not keys
The fuse needs to know whether the player is moving. The easy answer is to look at the keys. If an arrow key is held, the player is moving. This is wrong, and the reason is the trail itself.
A trail cannot reverse and it cannot enter claimed ground. A player who holds a key towards a blocked direction moves nowhere. If held keys counted as movement, the player could hold such a key and freeze the fuse for ever. So the fuse watches displacement: how far the player actually travelled since the previous frame. Holding a blocked key moves nothing, so the fuse keeps burning.
The simulation measures this at the start of every tick, in step 3. It compares the player's position with the position stored on the previous frame. A change of more than a tiny threshold counts as movement.
A tiny state machine
A state machine is a thing that is always in exactly one of a few named states, and moves between them for named reasons. FuseSystem has three states, shown in Figure 08-3. It stores them in two numbers and one flag, and not in an enum. _stoppedSeconds counts how long the player has stood still. _burnDistance counts how far the spark has travelled. The IsActive flag says whether the spark is lit.
| Figure 08-3: The three states of the fuse |
|---|
The state is worked out from those values. The fuse is warning when it is not lit and the stopped time has reached the warning delay. It is burning when the flag is set. Otherwise it is idle. The warning state exists only before ignition, so IsWarning becomes false the moment the spark is lit.
Walking along a trail
The spark needs a position. The fuse knows how far it has burnt, say 14 pixels, and it must turn that distance into a point on the screen. A trail is a list of points joined by straight segments, so the answer is found by walking the segments. This is called finding a point by arc length, which means by distance along the line.
Take a trail with three points: (0, 0), (10, 0) and (10, 10). The first segment is 10 pixels long. To find the point at distance 14, subtract the first segment's length, which leaves 4. The remaining 4 pixels fall inside the second segment. That segment runs from (10, 0) to (10, 10), so the point is 4 pixels along it, at (10, 4). Figure 08-4 shows the walk.
text
distance 14, points (0,0) (10,0) (10,10)
segment 1: length 10. 14 is more than 10, so subtract: 4 remain.
segment 2: length 10. 4 is not more than 10, so stop here.
4 / 10 = 0.4 of the way from (10,0) to (10,10), which is (10,4).| Figure 08-4: Walking a trail by arc length |
|---|
Two edges need a rule. A negative distance has no meaning, so the answer is the first point. A distance longer than the whole trail runs off the end, so the answer is the last point. An empty trail has no points at all, so it answers zero.
Building the point finder
You start in Trail, because the fuse depends on it. Here is the card.
Trail.GetPointAtDistance(distance) : Vector2
- Takes: a distance in pixels, measured along the trail from its first point.
- Gives: the point at that distance.
- Promises: the point is interpolated along the segment that contains the distance. A distance below zero gives the first point, and a distance past the end gives the last point.
- Refuses: an empty trail returns
Vector2.Zero.- Requirements: TRL-10.
Open Source/Entities/Trail.cs. Add the following method to the Trail class, above the DistanceSquaredToSegment method. It is a stub:
add-member Source/Entities/Trail.cs before=DistanceSquaredToSegment
csharp
public Vector2 GetPointAtDistance(float distance)
{
throw new NotImplementedException();
}Open Tests/Systems/TrailTests.cs. Add the following three tests to the TrailTests class, below the AddPoint_IgnoresPointsCloserThanHalfPixel test. The first walks the example from Figure 08-4. The second checks both ends. The third checks the empty trail.
add-member Tests/Systems/TrailTests.cs after=AddPoint_IgnoresPointsCloserThanHalfPixel
csharp
[Fact]
public void GetPointAtDistance_InterpolatesAlongSegment()
{
Trail trail = new();
trail.AddPoint(new Vector2(0f, 0f));
trail.AddPoint(new Vector2(10f, 0f));
trail.AddPoint(new Vector2(10f, 10f));
Vector2 midFirstSegment = trail.GetPointAtDistance(5f);
Vector2 intoSecondSegment = trail.GetPointAtDistance(14f);
Assert.Equal(new Vector2(5f, 0f), midFirstSegment);
Assert.Equal(new Vector2(10f, 4f), intoSecondSegment);
}
[Fact]
public void GetPointAtDistance_ClampsToTrailEndpoints()
{
Trail trail = new();
trail.AddPoint(new Vector2(0f, 0f));
trail.AddPoint(new Vector2(10f, 0f));
Assert.Equal(new Vector2(0f, 0f), trail.GetPointAtDistance(-5f));
Assert.Equal(new Vector2(10f, 0f), trail.GetPointAtDistance(999f));
}
[Fact]
public void GetPointAtDistance_ReturnsZero_WhenTrailIsEmpty()
{
Trail trail = new();
Assert.Equal(Vector2.Zero, trail.GetPointAtDistance(5f));
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 3 and Passed: 40. The 40 passes are the tests from earlier chapters. The 3 failures are your new tests, which hit the stub.
Open Source/Entities/Trail.cs. Find the GetPointAtDistance method and replace the whole method with the following:
replace-method Source/Entities/Trail.cs GetPointAtDistance
csharp
public Vector2 GetPointAtDistance(float distance)
{
if (_points.Count == 0)
{
return Vector2.Zero;
}
if (_points.Count == 1 || distance <= 0f)
{
return _points[0];
}
float remaining = distance;
for (int index = 0; index < _points.Count - 1; index++)
{
Vector2 start = _points[index];
Vector2 end = _points[index + 1];
float segmentLength = Vector2.Distance(start, end);
if (remaining <= segmentLength)
{
float t = segmentLength <= float.Epsilon ? 0f : remaining / segmentLength;
return Vector2.Lerp(start, end, t);
}
remaining -= segmentLength;
}
return _points[^1];
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 43.
The key things to note are:
- The empty trail is checked first, because every other line reads
_points[0]. - A trail with one point, or a distance of zero or less, returns the first point. This is the lower clamp.
- The loop keeps a
remainingdistance and subtracts one segment length each time round. This is the walk in Figure 08-4. Vector2.Lerp(start, end, t)blends between two points. Atof 0.4 gives the point 40 per cent of the way along. Thetisremaining / segmentLength.- The
float.Epsiloncheck stops a division by zero on a segment of no length. - If the loop ends without returning, the distance is longer than the trail.
_points[^1]is the last point, which is the upper clamp.
Setting up the fuse numbers
The three fuse numbers live in GameConfig, with the other tuning values. Open Source/Data/GameConfig.cs. Add the following property to the GameConfig class, below the MinimumTrailLength property:
add-member Source/Data/GameConfig.cs after=MinimumTrailLength
csharp
public float FuseWarningDelaySeconds { get; init; } = 1.0f;Add the following property below the FuseWarningDelaySeconds property:
add-member Source/Data/GameConfig.cs after=FuseWarningDelaySeconds
csharp
public float FuseTriggerDelaySeconds { get; init; } = 2.0f;Add the following property below the FuseTriggerDelaySeconds property:
add-member Source/Data/GameConfig.cs after=FuseTriggerDelaySeconds
csharp
public float FuseBurnSpeed { get; init; } = 60f;Building the fuse service
FuseSystem takes its three numbers as plain values in its constructor. It does not take a GameConfig, so a test can build a fuse with any timing it likes. Here are the cards.
FuseSystem.Update(activeTrail, isPlayerMoving, deltaTime) : bool
- Takes: the trail in progress, or
null, whether the player moved since the last frame, and the frame time in seconds.- Gives:
truewhen the spark has reached the end of the trail, which means the player is burnt.- Promises: it warns at the warning delay, ignites at the trigger delay and burns at the burn speed. Movement holds the spark where it is.
- Refuses: with no trail, or a trail that is not in progress, it puts itself out and returns
false.- Requirements: FUS-01, FUS-02, FUS-03, FUS-04, FUS-05, FUS-06, FUS-07.
FuseSystem.Reset() : void
- Takes: nothing.
- Gives: nothing. The fuse changes.
- Promises: every timer is cleared, the spark is out and
Positionis zero.- Refuses: nothing. Resetting a fuse that is already idle changes nothing.
- Requirements: FUS-06.
FuseSystem.IsWarning,IsActiveandPositionare read-only state.IsWarningis false once the spark is lit. Requirements: FUS-01.
In the Source/Systems folder, create a new file named FuseSystem.cs and add the following code. It is the shell of the service. The constructor and the three properties are complete, because a test needs a built fuse before it can ask a question. Update and Reset are stubs.
new-file Source/Systems/FuseSystem.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
namespace LastPerimeter.Systems;
public sealed class FuseSystem
{
private readonly float _warningDelaySeconds;
private readonly float _triggerDelaySeconds;
private readonly float _burnSpeed;
private float _stoppedSeconds;
private float _burnDistance;
public FuseSystem(float warningDelaySeconds, float triggerDelaySeconds, float burnSpeed)
{
_warningDelaySeconds = warningDelaySeconds;
_triggerDelaySeconds = triggerDelaySeconds;
_burnSpeed = burnSpeed;
}
public bool IsWarning => !IsActive && _stoppedSeconds >= _warningDelaySeconds;
public bool IsActive { get; private set; }
public Vector2 Position { get; private set; }
public bool Update(Trail? activeTrail, bool isPlayerMoving, float deltaTime)
{
throw new NotImplementedException();
}
public void Reset()
{
throw new NotImplementedException();
}
}The key things to note are:
- The three timing values are
readonlyfields. A fuse never changes its own timing. _stoppedSecondsand_burnDistanceare the only moving parts.IsActivecan be read from outside but set only inside the class.IsWarningis calculated and not stored. It cannot drift out of step with the numbers it comes from.UpdatetakesTrail?, so the caller can passnullwhen no trail is being drawn.
From the LastPerimeter folder, run dotnet build. The build should succeed, which proves the stubs compile. Expect warnings about unused fields until the bodies are written.
You now write the three tests that describe the timeline. In the Tests/Systems folder, create a new file named FuseSystemTests.cs and add the following code. It starts with the test for the main promise: stand still, and the spark ignites and then burns to the end. The loop runs at most 25 steps of 0.1 seconds. The fuse ignites after about 10 of them, and the 100 pixel trail burns away at 100 pixels per second in about 10 more.
new-file Tests/Systems/FuseSystemTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
using LastPerimeter.Systems;
namespace LastPerimeter.Tests.Systems;
public sealed class FuseSystemTests
{
[Fact]
public void FuseTriggersAfterDelay_AndReachesPlayer()
{
Trail trail = new();
trail.AddPoint(new Vector2(0, 0));
trail.AddPoint(new Vector2(100, 0));
FuseSystem fuseSystem = new(0.5f, 1f, 100f);
bool killed = false;
for (int index = 0; index < 25 && !killed; index++)
{
killed = fuseSystem.Update(trail, false, 0.1f);
}
Assert.True(fuseSystem.IsActive);
Assert.True(killed);
}
}Add the following test to the FuseSystemTests class, below the FuseTriggersAfterDelay_AndReachesPlayer test. It proves the pause. The burn speed is 10 pixels per second. One second of stillness ignites the spark and moves it 10 pixels. Five seconds of movement must leave it at 10. One more second of stillness moves it to 20.
add-member Tests/Systems/FuseSystemTests.cs after=FuseTriggersAfterDelay_AndReachesPlayer
csharp
[Fact]
public void FusePausesWhenPlayerMoves_AndResumesOnStop()
{
Trail trail = new();
trail.AddPoint(new Vector2(0, 0));
trail.AddPoint(new Vector2(100, 0));
FuseSystem fuseSystem = new(0.5f, 1f, 10f);
fuseSystem.Update(trail, false, 1f);
Assert.True(fuseSystem.IsActive);
Assert.Equal(new Vector2(10f, 0f), fuseSystem.Position);
fuseSystem.Update(trail, true, 5f);
Assert.True(fuseSystem.IsActive);
Assert.Equal(new Vector2(10f, 0f), fuseSystem.Position);
fuseSystem.Update(trail, false, 1f);
Assert.Equal(new Vector2(20f, 0f), fuseSystem.Position);
}Add the following test below the FusePausesWhenPlayerMoves_AndResumesOnStop test. It proves the warning, the hand-over from warning to burning, and the put-out. The trail is marked Completed, and the next update must clear everything.
add-member Tests/Systems/FuseSystemTests.cs after=FusePausesWhenPlayerMoves_AndResumesOnStop
csharp
[Fact]
public void Fuse_WarnsBeforeIgnition_AndIsExtinguishedWhenTheTrailEnds()
{
Trail trail = new();
trail.AddPoint(new Vector2(0, 0));
trail.AddPoint(new Vector2(100, 0));
FuseSystem fuseSystem = new(0.5f, 1f, 10f);
fuseSystem.Update(trail, false, 0.6f);
Assert.True(fuseSystem.IsWarning);
Assert.False(fuseSystem.IsActive);
fuseSystem.Update(trail, false, 0.5f);
Assert.True(fuseSystem.IsActive);
Assert.False(fuseSystem.IsWarning);
trail.State = TrailState.Completed;
fuseSystem.Update(trail, false, 0.1f);
Assert.False(fuseSystem.IsActive);
Assert.False(fuseSystem.IsWarning);
Assert.Equal(Vector2.Zero, fuseSystem.Position);
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 3 and Passed: 43. The three new tests fail on the stubs.
Open Source/Systems/FuseSystem.cs. Find the Update method and replace the whole method with the following. It has four stages, and the notes below take them one at a time.
replace-method Source/Systems/FuseSystem.cs Update
csharp
public bool Update(Trail? activeTrail, bool isPlayerMoving, float deltaTime)
{
if (activeTrail is null || activeTrail.State != TrailState.InProgress)
{
Reset();
return false;
}
if (isPlayerMoving)
{
_stoppedSeconds = 0f;
return false;
}
_stoppedSeconds += deltaTime;
if (!IsActive && _stoppedSeconds >= _triggerDelaySeconds)
{
IsActive = true;
_burnDistance = 0f;
Position = activeTrail.Points[0];
}
if (!IsActive)
{
return false;
}
_burnDistance += _burnSpeed * deltaTime;
Position = activeTrail.GetPointAtDistance(_burnDistance);
return _burnDistance >= Math.Max(0f, activeTrail.TotalLength - 1f);
}Find the Reset method and replace the whole method with the following:
replace-method Source/Systems/FuseSystem.cs Reset
csharp
public void Reset()
{
_stoppedSeconds = 0f;
_burnDistance = 0f;
IsActive = false;
Position = Vector2.Zero;
}Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 46.
The key things to note are:
- Stage 1 is the guard. With no trail, or a trail that is
CompletedorCancelled, the fuse puts itself out and returnsfalse. This is how the fuse goes out when the player reconnects to the wall. - Stage 2 is the pause. A moving player zeroes
_stoppedSecondsand returns at once. It does not touch_burnDistanceorIsActive, so a lit spark stays exactly where it is. - Stage 3 is the ignition. Stillness adds
deltaTimeto_stoppedSeconds. When the total reaches the trigger delay, the fuse lights, starts its burn distance at zero and places the spark on the first point of the trail. The!IsActivecheck makes this happen once. - Stage 4 is the burn. The spark advances by
_burnSpeed * deltaTimeand its position comes fromGetPointAtDistance. The method returnstruewhen the burn has reachedTotalLength - 1. - The kill uses
TotalLength - 1and notTotalLength. A frame step is a fraction of a pixel, and floating-point sums may never land exactly on the end. The margin of one pixel makes the kill certain.Math.Maxstops a trail shorter than one pixel from giving a negative target. ResetsetsPositionto zero so a stale position is never drawn.Updatedoes not callResetafter a kill. The simulation does that, as you see in the next section.
Wiring it into the game
GameplaySimulation now owns a fuse and runs it from the tick. The change has three parts. You first add the fuse and its state. You then write the two scenario tests that fail without the wiring. You finish by replacing the tick methods.
Open Source/Simulation/GameplaySimulation.cs. Add a constant above the _baseConfig field at the top of the GameplaySimulation class. It is the smallest squared distance that counts as movement. The square avoids a square root every frame. Find this line:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
private readonly GameConfig _baseConfig;Replace it with the following. The first line is the new constant, and the last line is the field, unchanged:
csharp
private const float MovedThresholdSquared = 0.0001f;
private readonly GameConfig _baseConfig;Add the following field below the _trails field:
add-member Source/Simulation/GameplaySimulation.cs after=_trails
csharp
private readonly FuseSystem _fuse;Add the following field below the _arena field. It holds the player's position from the previous frame.
add-member Source/Simulation/GameplaySimulation.cs after=_arena
csharp
private Vector2 _lastPlayerPosition;In the same file, the constructor must build the fuse. Find this line in the GameplaySimulation constructor:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
_trails = new TrailSystem(baseConfig.MinimumTrailLength);Add the following line directly after it:
csharp
_fuse = new FuseSystem(baseConfig.FuseWarningDelaySeconds, baseConfig.FuseTriggerDelaySeconds, baseConfig.FuseBurnSpeed);Add the following property to the GameplaySimulation class, below the Session property. The scenario tests, and later the scene, read the fuse through it.
add-member Source/Simulation/GameplaySimulation.cs after=Session
csharp
// The fuse of the current level. Chapter 14 moves it into LevelServices.
public FuseSystem Fuse => _fuse;NOTE
From this chapter to Chapter 13, GameplaySimulation exposes a few small public properties such as Fuse, so tests can reach the services of the level. Chapter 14 deletes them when LevelServices arrives.
The two scenario tests drive the whole simulation with scripted key presses. Each frame lasts 0.05 seconds. Both tests draw a short trail from the top wall, by holding Right for 4 frames and then Down for 3, and then hold Up. Up is the opposite of Down, and a trail may not reverse, so the player cannot move. This is the case from the section on displacement.
In the Tests/Simulation folder, create a new file named FuseScenarioTests.cs and add the following code. The test holds the blocked key for 45 frames, which is 2.25 seconds. The fuse ignites at 2 seconds, and the player must not have moved.
new-file Tests/Simulation/FuseScenarioTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Simulation;
using LastPerimeter.Tests.TestHelpers;
namespace LastPerimeter.Tests.Simulation;
public sealed class FuseScenarioTests
{
[Fact]
public void Tick_HoldingBlockedDirection_LetsFuseBurn()
{
GameplaySimulation sim = SimulationBuilder.Create();
ScriptedInput.Run(sim, ScriptedInput.Right, 4);
ScriptedInput.Run(sim, ScriptedInput.Down, 3);
Vector2 before = sim.Session.Player.Position;
// Up is a reversal, so the player cannot move and the fuse keeps burning.
ScriptedInput.Run(sim, ScriptedInput.Up, 45);
Assert.Equal(before, sim.Session.Player.Position);
Assert.True(sim.Fuse.IsActive);
}
}Add the following test below the Tick_HoldingBlockedDirection_LetsFuseBurn test. It holds the blocked key for 60 frames, which is 3 seconds. The burn must finish, the trail must be gone and the player must be back on the wall.
add-member Tests/Simulation/FuseScenarioTests.cs after=Tick_HoldingBlockedDirection_LetsFuseBurn
csharp
[Fact]
public void Tick_FuseReachingPlayer_CancelsTheTrail()
{
GameplaySimulation sim = SimulationBuilder.Create();
ScriptedInput.Run(sim, ScriptedInput.Right, 4);
ScriptedInput.Run(sim, ScriptedInput.Down, 3);
ScriptedInput.Run(sim, ScriptedInput.Up, 60);
Assert.Null(sim.Session.Player.CurrentTrail);
Assert.False(sim.Fuse.IsActive);
Assert.Equal(new Vector2(20, 0), sim.Session.Player.Position);
}In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 2 and Passed: 46. Nothing calls the fuse yet, so the spark never lights and the trail never goes.
Now wire the fuse into the tick. In 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();
Player player = _session.Player;
// 3. The fuse must react to actual displacement, not input: holding a blocked
// direction leaves the player stationary and the fuse must keep burning.
bool playerMovedLastFrame = Vector2.DistanceSquared(player.Position, _lastPlayerPosition) > MovedThresholdSquared;
_lastPlayerPosition = player.Position;
// 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(player.Position, direction, speed, deltaTime);
if (activeTrail is not null)
{
TickWhileDrawing(activeTrail, direction, intendedPosition, playerMovedLastFrame, deltaTime, input);
}
else
{
TickOnWall(direction, intendedPosition, speed, deltaTime, input);
}
return _events;
}Find the TickWhileDrawing method and replace the whole method with the following:
replace-method Source/Simulation/GameplaySimulation.cs TickWhileDrawing
csharp
private void TickWhileDrawing(Trail activeTrail, Direction direction, Vector2 intendedPosition, bool playerMovedLastFrame, float deltaTime, InputState input)
{
Player player = _session.Player;
// 8a. Fuse.
bool killedByFuse = _fuse.Update(activeTrail, playerMovedLastFrame, deltaTime);
if (killedByFuse)
{
CancelTrail(activeTrail);
return;
}
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;
}
}In the TickOnWall method, a player on the wall has no trail, so the fuse must be put out. Find this comment line:
find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
// 9b. Move along the wall.Replace it with the following. The last line is the comment you found, unchanged:
csharp
// 9a. Put out the fuse.
_fuse.Reset();
// 9b. Move along the wall.Add the following method to the GameplaySimulation class, above the CompleteTrail method. It is the temporary kill rule.
add-member Source/Simulation/GameplaySimulation.cs before=CompleteTrail
csharp
// Temporary rule until chapter 11 adds lives: cancel the trail and go back to its first point.
private void CancelTrail(Trail trail)
{
_trails.Cancel();
_fuse.Reset();
_session.Player.CurrentTrail = null;
_session.Player.Position = trail.Points[0];
}IMPORTANT
The kill rule here is temporary. The game has no lives yet, so a fuse that reaches the player only cancels the trail and puts the player back where the trail began. Chapter 11 replaces CancelTrail with a real hit that costs a life.
The key changes are:
- Step 3 is new, at the top of
Tick. It compares the player's position with_lastPlayerPosition, stores the new position, and keeps the answer inplayerMovedLastFrame. It runs before any movement, so it measures what happened in the previous frame. Ticknow passesactiveTrail,playerMovedLastFrameanddeltaTimetoTickWhileDrawing. These three are the only inputs the fuse needs.- Step 8a is the first thing
TickWhileDrawingdoes. If the fuse kills, the trail is cancelled and the method returns, so the player cannot reconnect on the same frame that they burn. - Step 9a is the first thing
TickOnWalldoes. A player on the wall has no trail, so the fuse is put out. This step has no test of its own in this chapter. It guards against a fuse that survives into wall movement. CancelTrailcancels the trail inTrailSystem, puts the fuse out, clears the trail on the player and moves the player toPoints[0], the first point of the trail.TickOnWallgains only the two 9a lines, which you added above._lastPlayerPositionneeds no reset inStartLevel. The first tick after a level starts can only count as movement while the player is on the wall, and the fuse does nothing there.- The step numbers in the comments are explained in the order of one tick.
Open Source/Scenes/GameplayScene.cs. The Draw method must now draw a red dot at the spark's position while the fuse is lit. It is drawn after the trail and before the player, so the player stays on top. In the Draw method, find this line:
find Source/Scenes/GameplayScene.cs
csharp
_playerRenderer.Draw(spriteBatch, _services.Pixel, session.Player, Color.Cyan);Replace it with the following. The last line is the line you found, unchanged:
csharp
if (_simulation.Fuse.IsActive)
{
PrimitiveDrawing.DrawFilledCircle(spriteBatch, _services.Pixel, _simulation.Fuse.Position, 4f, Color.Red);
}
_playerRenderer.Draw(spriteBatch, _services.Pixel, session.Player, Color.Cyan);The key change is the if block. The warning flash that tells the player the fuse is about to light arrives with the themes in Chapter 20. Until then, the player sees only the lit spark.
Running the tests
In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 48. The 48 tests are the 40 from earlier chapters and the 8 you wrote in this chapter.
| Test | Proves |
|---|---|
GetPointAtDistance_InterpolatesAlongSegment | TRL-10 |
GetPointAtDistance_ClampsToTrailEndpoints | TRL-10 |
GetPointAtDistance_ReturnsZero_WhenTrailIsEmpty | TRL-10 |
Fuse_WarnsBeforeIgnition_AndIsExtinguishedWhenTheTrailEnds | FUS-01, FUS-06 |
FuseTriggersAfterDelay_AndReachesPlayer | FUS-02, FUS-03, FUS-05 |
FusePausesWhenPlayerMoves_AndResumesOnStop | FUS-04 |
Tick_HoldingBlockedDirection_LetsFuseBurn | FUS-07 |
Tick_FuseReachingPlayer_CancelsTheTrail | FUS-05 in the simulation, rewritten in Chapter 11 |
Running the game
From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen. The cyan dot sits at the top-left corner of the arena.
Hold the Right arrow for about a second, so the dot slides along the top wall. Release it, then hold the Down arrow. The dot leaves the wall and a yellow trail follows it. Release every key and wait.
After about 2 seconds, a small red dot appears at the start of the trail, on the wall. It runs along the trail towards the cyan dot, as in Figure 08-1. Now hold the Right arrow. The red dot stops while you move. Stop again, and it resumes.
Let it reach the cyan dot. The yellow trail vanishes and the cyan dot jumps back to the place on the wall where the trail began. Close the window with its close button. The tests prove the fuse timings and the kill rule. Only the window shows the red spark and its movement.
TIP
Try the displacement rule yourself. Draw a trail downwards, then hold the Up arrow. The dot cannot reverse, so it does not move, and the red dot still appears and burns. Holding the key does not save you.
The next section is optional. It replaces your files with the chapter 08 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 08 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/08-The-Fuse-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/08-The-Fuse-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: 48.
Common mistakes
- A
NotImplementedExceptionin the final test run. You left a stub inTrail.csorFuseSystem.cs. Search both files forthrow new NotImplementedException();and replace that method. - The spark never appears, and the scenario tests fail.
_fuse.Updateis not called fromTickWhileDrawing, or step 3 is missing andplayerMovedLastFrameis alwaysfalseor alwaystrue. - The spark never stops when you move. Step 3 compares the position with itself. Check that
_lastPlayerPosition = player.Position;comes after the comparison and not before it. - The fuse burns through a gap and never kills. The final line of
Updatecompares withTotalLengthand notTotalLength - 1, and floating-point error leaves the burn a fraction short. - The red dot is hidden behind the trail. In
Draw, the fuse block must come after the trail and before the player. - The build says
Fuseis not found onGameplaySimulation. TheFuseproperty is missing, or you added it to a different class.
Conclusion
In this chapter, you accomplished the following:
- Learned why the fuse turns time into distance along the trail.
- Built
Trail.GetPointAtDistanceand learned how to walk a trail by arc length. - Built
FuseSystemas a small state machine with a warning, an ignition and a burn. - Learned why the fuse watches displacement and not the keys.
- Added steps 3, 8a and 9a to the tick, in the simulation wiring.
The tests now prove TRL-10 and FUS-01 to FUS-07. In the next chapter, Chapter 09: The Capture Service, you build the solver that decides which part of the arena the player has won when a trail closes.
Test Your Knowledge
Why does the fuse start at the first point of the trail and not at the player?
Answer
The spark chases the player along the line the player drew. If it started at the player, it would be at the end of the trail already and would kill at once.
A player holds Right into a claimed block in the middle of a trail. Why must the fuse keep burning?
Answer
The player is not moving, because the block refuses the move. The fuse measures displacement. If held keys counted, a player could hold a blocked key and freeze the fuse for ever.
Why does
Updatekill atTotalLength - 1and not at exactlyTotalLength?Answer
The burn grows in small floating-point steps and may never land exactly on the end. A margin of one pixel makes the kill reliable.
What is the difference between what happens when the player moves before ignition and after it?
Answer
Before ignition, moving sets the stopped timer back to zero, so the warning must be earned again. After ignition, moving leaves the spark where it is, and it resumes when the player stops.
Extensions
- Change
FuseTriggerDelaySecondsinGameConfigto 1.0 and rundotnet test. Which tests still pass, and why do the fuse tests not depend on the config? - Add a test that draws a trail of 3 pixels and checks that
Updatekills it soon after ignition. This exercises theMath.Maxguard for very short trails.

