Skip to content

Chapter 11: Lives, Shields and Respawn ​

In Chapter 10: Enemies and Collision, an enemy that touched your trail cancelled it and sent you back to where it began. You marked that rule as temporary. A game with no cost for a hit has no tension, and a game with only one chance has no room to learn.

In this chapter, you replace the temporary rule with lives, shields and a fair respawn. You build LivesSystem, which decides what a hit costs and where the player returns.

Figure 11-1: The chapter 11 window after a hit. The player has reappeared at the far corner and is drawn paler while it is protected. This is a drawn illustration, not a screenshot.
Figure 11-1: The chapter 11 window after a hit. The player has reappeared at the far corner and is drawn paler while it is protected. This is a drawn illustration, not a screenshot.

Time: [TODO Simon: time estimate for chapter 11]

In this chapter, you will:

  • Learn what makes a respawn fair, and turn that into a score for each wall node.
  • Build LivesSystem with four operations and one that combines them.
  • Learn why one entry point, ResolveHit, is safer than two call sites that each remember the shield.
  • Add the respawn grace, and make hits and trail starts wait for it.
  • Raise the first events that end things: ShieldBlocked, LifeLost and RunLost.
  • Strengthen two existing scenario tests, and learn why a test changes when a rule changes.

Requirements in this chapter ​

IDShort name
LIV-02Shield is tried first
LIV-03Shield block returns the player to the wall with grace
LIV-04A hit loses a life and cancels the trail and fuse
LIV-05The last life ends the run
LIV-06Respawn node chosen by score
LIV-07Respawn starts the grace time
COL-03No hits during grace
TRL-01No trail starts during grace

What a fair respawn is ​

When a hit costs a life, the game has to put the player somewhere. A careless choice makes the player lose again at once, and that feels like cheating. A fair respawn has two properties. It is far from the enemies, and it has more than one way out.

The player returns to a node of the wall path from Chapter 06: The Wall Path Service. A node is a point where wall segments meet. Each node gets a score, and the highest score wins. The score is the squared distance to the nearest enemy, plus 500 for each wall segment that meets at the node.

Squared distance avoids a square root, and it still orders the nodes correctly. The 500 per segment is a tie-breaker. A junction offers more directions to leave in, so between two nodes at nearly the same distance, the junction wins. Across a real arena, squared distances run into the hundreds of thousands. A weight of 500 therefore only matters when two distances are close. Figure 11-2 scores the four corners of the small test arena against one enemy in its top-left corner.

Figure 11-2: Four wall nodes scored against one enemy. The far corner scores highest and wins
Figure 11-2: Four wall nodes scored against one enemy. The far corner scores highest and wins

When two nodes score the same, the first one in the path wins. With no enemies at all, every node has a distance of 0, and the connected segments decide. In the test arena they are equal, so the first node wins.

Shields before lives ​

A shield absorbs one hit. When the player is hit, the game must try the shield first, and only if there is none must it take a life. The order matters, and it must be the same everywhere a hit can happen. In this game a hit can come from two places: the fuse, and an enemy touching the trail.

If each of those places remembered the order itself, one of them would eventually forget. The player would lose a life with a shield in hand. So LivesSystem offers one operation, ResolveHit, that does the whole sequence: shield, then life, then respawn. Both places call it and nothing else. The three smaller operations stay public so that a test can check each one alone, but the simulation never calls them directly.

Grace ​

After a hit, the player is protected for 1.2 seconds. This is the respawn grace. While it lasts, nothing can hit the player, and the player cannot start a trail. The first part is plain mercy: the player needs a moment to see where they are. The second part closes a loophole. If a protected player could draw a trail, they could draw straight through an enemy at no cost. So grace pauses both hits and trail starts.

The player is drawn paler while protected, so the player can see it. The simulation sets a flag on the player for this. The renderer reads it.

A service that holds nothing ​

LivesSystem has no fields that change. It receives the session, the trail service and the fuse service in each call, and it changes them. This makes every operation easy to test. A test builds a simulation, gets those objects from it, calls one operation and reads the result. There is nothing to construct inside the service and nothing to reset afterwards.

Setting up the data ​

A few new values must exist before the service can be written. Open a terminal in the LastPerimeter folder. No new folders are needed. This section adds one setting, four properties and two readers on the simulation.

Open Source/Data/GameConfig.cs. Add the following property to the GameConfig record, below the EnemyRetargetIntervalSeconds property. It is the length of the grace.

add-member Source/Data/GameConfig.cs after=EnemyRetargetIntervalSeconds
csharp
    public float RespawnGraceSeconds { get; init; } = 1.2f;

Open Source/Data/GameSession.cs. Add the following property to the GameSession class, below the ClaimedAreaPercentage property. It counts the grace down.

add-member Source/Data/GameSession.cs after=ClaimedAreaPercentage
csharp
    public float RespawnGraceRemaining { get; set; }

Add the following property below the FreezeEnemiesRemaining property. It holds the number of shield charges. Nothing awards a charge yet. Chapter 15 adds the powerup that does.

add-member Source/Data/GameSession.cs after=FreezeEnemiesRemaining
csharp
    public int ShieldCharges { get; set; }

Open Source/Entities/Player.cs. Add the following property to the Player class, below the Radius property:

add-member Source/Entities/Player.cs after=Radius
csharp
    public int Lives { get; set; } = 3;

Add the following property below the CurrentTrail property. The simulation sets it while the grace runs.

add-member Source/Entities/Player.cs after=CurrentTrail
csharp
    public bool IsInvulnerable { get; set; }

Open Source/Simulation/GameplaySimulation.cs. Add the following field to the GameplaySimulation class, below the _fuse field:

add-member Source/Simulation/GameplaySimulation.cs after=_fuse
csharp
    private readonly LivesSystem _lives = new();

Add the following property below the Session property. The tests use it to read the grace time.

add-member Source/Simulation/GameplaySimulation.cs after=Session
csharp
    // The services and numbers of the current level. Chapter 14 moves them into LevelServices.
    public GameConfig Config => _baseConfig;

Add the following property below the Config property. The tests use it to hand the trail service to LivesSystem.

add-member Source/Simulation/GameplaySimulation.cs after=Config
csharp
    public TrailSystem Trails => _trails;

Building the lives service ​

The first listing is the shell of LivesSystem. It declares the HitOutcome enum, which names the three results of a hit, and every operation. All five operations throw until you write them. The constant is the 500 point weight from Figure 11-2.

In the Source/Systems folder, create a new file named LivesSystem.cs and add the following code:

new-file Source/Systems/LivesSystem.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;

namespace LastPerimeter.Systems;

public enum HitOutcome
{
    Blocked,
    LifeLost,
    RunOver,
}

// Hits, shields and respawn. Stateless: it changes the session and the services it is
// given. Chapter 14 bundles the services into LevelServices.
public sealed class LivesSystem
{
    private const float ScorePerConnectedSegment = 500f;

    public HitOutcome ResolveHit(GameSession session, TrailSystem trails, FuseSystem fuse, float graceSeconds)
    {
        throw new NotImplementedException();
    }

    public bool TryBlockWithShield(GameSession session, TrailSystem trails, FuseSystem fuse, float graceSeconds)
    {
        throw new NotImplementedException();
    }

    public int LoseLife(GameSession session, TrailSystem trails, FuseSystem fuse)
    {
        throw new NotImplementedException();
    }

    public Vector2 SelectRespawnNode(PlayableWallPath path, IReadOnlyList<Enemy> enemies)
    {
        throw new NotImplementedException();
    }

    public void Respawn(GameSession session, float graceSeconds)
    {
        throw new NotImplementedException();
    }
}

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 66. The run proves that the new data compiles and that nothing from Chapter 10 broke.

The key things to note are:

  • HitOutcome has three values. Blocked means a shield took the hit. LifeLost means a life went and the player respawned. RunOver means the last life went.
  • LivesSystem has no constructor and no fields, apart from the constant.
  • The trail and fuse are parameters, because this chapter does not yet have one object that bundles the level's services. Chapter 14 adds it and changes these signatures.

You build the operations in the order that each one needs the last. The shield comes first, then the life, then the respawn node, then the respawn, and last the one that combines them.

Blocking a hit with a shield ​

LivesSystem.TryBlockWithShield(session, trails, fuse, graceSeconds) : bool

  • Takes: the session, the trail service, the fuse service and the grace length.
  • Gives: true when a shield charge was spent.
  • Promises: one charge is spent, the trail is cancelled, the fuse is put out, the player is snapped to the wall, and grace starts.
  • Refuses: with no charges it gives false and changes nothing.
  • Requirements: LIV-02, LIV-03.

In the Tests/Systems folder, create a new file named LivesSystemTests.cs and add the following code. The helper DrawingSimulation builds a simulation, moves the player right and then down, and checks that a trail has started. Every test in this file starts from it. The first test checks the refusal first: with no charges, nothing changes. It then gives the session two charges and checks that one is spent and no life is lost.

new-file Tests/Systems/LivesSystemTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Entities;
using LastPerimeter.Simulation;
using LastPerimeter.Systems;
using LastPerimeter.Tests.TestHelpers;

namespace LastPerimeter.Tests.Systems;

public sealed class LivesSystemTests
{
    private static GameplaySimulation DrawingSimulation()
    {
        GameplaySimulation sim = SimulationBuilder.Create();
        ScriptedInput.Run(sim, ScriptedInput.Right, 4);
        ScriptedInput.Run(sim, ScriptedInput.Down, 3);
        Assert.NotNull(sim.Session.Player.CurrentTrail);
        return sim;
    }

    [Fact]
    public void TryBlockWithShield_SpendsOneChargeInsteadOfALife()
    {
        GameplaySimulation sim = DrawingSimulation();
        LivesSystem lives = new();

        Assert.False(lives.TryBlockWithShield(sim.Session, sim.Trails, sim.Fuse, sim.Config.RespawnGraceSeconds));
        Assert.Equal(0f, sim.Session.RespawnGraceRemaining);
        Assert.NotNull(sim.Session.Player.CurrentTrail);

        sim.Session.ShieldCharges = 2;
        Assert.True(lives.TryBlockWithShield(sim.Session, sim.Trails, sim.Fuse, sim.Config.RespawnGraceSeconds));

        Assert.Equal(1, sim.Session.ShieldCharges);
        Assert.Equal(3, sim.Session.Player.Lives);
    }
}

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 66.

Open Source/Systems/LivesSystem.cs. Find the TryBlockWithShield method and replace the whole method with the following:

replace-method Source/Systems/LivesSystem.cs TryBlockWithShield
csharp
    public bool TryBlockWithShield(GameSession session, TrailSystem trails, FuseSystem fuse, float graceSeconds)
    {
        if (session.ShieldCharges <= 0)
        {
            return false;
        }

        session.ShieldCharges--;
        trails.Cancel();
        fuse.Reset();
        session.Player.CurrentTrail = null;
        session.Player.Position = session.PlayableWallPath.Snap(session.Player.Position);
        session.RespawnGraceRemaining = graceSeconds;
        return true;
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 67.

The key things to note are:

  • The check for no charges comes first and returns before anything changes. This is the refusal on the card.
  • session.PlayableWallPath.Snap moves the player from the middle of the arena back onto the nearest point of the wall.
  • A block does not move the player to a far node. The player stays near where the trail began, because a shield is a lighter penalty than a life.
  • Grace starts on a block as well, so the same enemy cannot hit again in the next frame.

Losing a life ​

LivesSystem.LoseLife(session, trails, fuse) : int

  • Takes: the session, the trail service and the fuse service.
  • Gives: the number of lives left.
  • Promises: one life is lost, the trail is cancelled and the fuse is put out.
  • Refuses: lives never go below 0.
  • Requirements: LIV-04.

Open Tests/Systems/LivesSystemTests.cs. Add the following test to the LivesSystemTests class, below the TryBlockWithShield_SpendsOneChargeInsteadOfALife test. The test idles for 30 frames so that the fuse starts burning, and then it loses a life. The fuse must be out and the trail must be gone.

add-member Tests/Systems/LivesSystemTests.cs after=TryBlockWithShield_SpendsOneChargeInsteadOfALife
csharp
    [Fact]
    public void LoseLife_CancelsTrailAndFuse()
    {
        GameplaySimulation sim = DrawingSimulation();
        ScriptedInput.Run(sim, ScriptedInput.Idle, 30);
        Assert.True(sim.Fuse.IsWarning || sim.Fuse.IsActive);

        int left = new LivesSystem().LoseLife(sim.Session, sim.Trails, sim.Fuse);

        Assert.Equal(2, left);
        Assert.Null(sim.Session.Player.CurrentTrail);
        Assert.False(sim.Fuse.IsActive);
        Assert.False(sim.Fuse.IsWarning);
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 67.

Open Source/Systems/LivesSystem.cs. Find the LoseLife method and replace the whole method with the following:

replace-method Source/Systems/LivesSystem.cs LoseLife
csharp
    public int LoseLife(GameSession session, TrailSystem trails, FuseSystem fuse)
    {
        session.Player.Lives = Math.Max(0, session.Player.Lives - 1);
        session.Player.CurrentTrail = null;
        trails.Cancel();
        fuse.Reset();
        return session.Player.Lives;
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 68.

The key things to note are:

  • Math.Max(0, ...) holds the count at 0, so a second call after the last life cannot give a negative number.
  • The method returns the count, so the caller can decide whether the run is over without a second look at the session.
  • LoseLife does not move the player. Where the player goes is the job of Respawn.

Choosing a respawn node ​

LivesSystem.SelectRespawnNode(path, enemies) : Vector2

  • Takes: the wall path and the list of enemies.
  • Gives: the position of the best node.
  • Promises: the node with the highest score wins. The score is the squared distance to the nearest enemy plus 500 per connected segment. Ties go to the first node.
  • Refuses: nothing. With no enemies, the distance part is 0 for every node.
  • Requirements: LIV-06.

Open Tests/Systems/LivesSystemTests.cs. Add the following test to the LivesSystemTests class, below the LoseLife_CancelsTrailAndFuse test. It asks for a node with an enemy in the top-left corner, which must give the opposite corner, as in Figure 11-2. It then asks with no enemies, which must give the first node.

add-member Tests/Systems/LivesSystemTests.cs after=LoseLife_CancelsTrailAndFuse
csharp
    [Fact]
    public void SelectRespawnNode_PrefersNodesFarFromEnemies()
    {
        GameplaySimulation sim = SimulationBuilder.Create();
        LivesSystem lives = new();
        PlayableWallPath path = sim.Session.PlayableWallPath;
        List<Enemy> enemies = [new Enemy { Position = new Vector2(0, 0) }];

        Vector2 withEnemy = lives.SelectRespawnNode(path, enemies);
        Vector2 withoutEnemies = lives.SelectRespawnNode(path, []);

        Assert.Equal(new Vector2(80, 80), withEnemy);
        Assert.Equal(path.Nodes[0], withoutEnemies);
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 68.

Open Source/Systems/LivesSystem.cs. Find the SelectRespawnNode method and replace the whole method with the following:

replace-method Source/Systems/LivesSystem.cs SelectRespawnNode
csharp
    // The node with the highest score wins: squared distance to the nearest enemy
    // plus a bonus per connected segment. Ties go to the first node.
    public Vector2 SelectRespawnNode(PlayableWallPath path, IReadOnlyList<Enemy> enemies)
    {
        Vector2 best = Vector2.Zero;
        float bestScore = float.NegativeInfinity;
        IReadOnlyList<Vector2> nodes = path.Nodes;
        for (int index = 0; index < nodes.Count; index++)
        {
            Vector2 node = nodes[index];
            float nearest = 0f;
            if (enemies.Count > 0)
            {
                nearest = float.MaxValue;
                for (int enemyIndex = 0; enemyIndex < enemies.Count; enemyIndex++)
                {
                    nearest = Math.Min(nearest, Vector2.DistanceSquared(node, enemies[enemyIndex].Position));
                }
            }

            float score = nearest + (path.GetConnectedSegmentCount(node) * ScorePerConnectedSegment);
            if (score > bestScore)
            {
                bestScore = score;
                best = node;
            }
        }

        return best;
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 69.

The key things to note are:

  • The best score starts at negative infinity, so the first node always beats it.
  • The comparison is > and not >=, so a later node with an equal score does not replace the first. That is the tie rule.
  • With no enemies, nearest stays at 0 and the segment bonus alone decides.
  • float.MaxValue is the starting value of the nearest distance, so any real distance is smaller and replaces it.

Respawning ​

LivesSystem.Respawn(session, graceSeconds) : void

  • Takes: the session and the grace length.
  • Gives: nothing. The session changes.
  • Promises: the player is placed on the chosen node and grace starts.
  • Refuses: nothing.
  • Requirements: LIV-07.

Open Tests/Systems/LivesSystemTests.cs. Add the following test to the LivesSystemTests class, below the SelectRespawnNode_PrefersNodesFarFromEnemies test:

add-member Tests/Systems/LivesSystemTests.cs after=SelectRespawnNode_PrefersNodesFarFromEnemies
csharp
    [Fact]
    public void Respawn_StartsGraceFromConfig()
    {
        GameplaySimulation sim = SimulationBuilder.Create();

        new LivesSystem().Respawn(sim.Session, sim.Config.RespawnGraceSeconds);

        Assert.True(sim.Config.RespawnGraceSeconds > 0f);
        Assert.Equal(sim.Config.RespawnGraceSeconds, sim.Session.RespawnGraceRemaining);
        Assert.True(sim.Session.PlayableWallPath.Contains(sim.Session.Player.Position));
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 69.

Open Source/Systems/LivesSystem.cs. Find the Respawn method and replace the whole method with the following:

replace-method Source/Systems/LivesSystem.cs Respawn
csharp
    public void Respawn(GameSession session, float graceSeconds)
    {
        session.Player.Position = SelectRespawnNode(session.PlayableWallPath, session.Enemies);
        session.RespawnGraceRemaining = graceSeconds;
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 70.

The key things to note are:

  • Respawn is two lines, because the hard part lives in SelectRespawnNode.
  • The test checks that the grace is positive. A configuration of 0 would let the test pass without proving anything.

Resolving a hit ​

LivesSystem.ResolveHit(session, trails, fuse, graceSeconds) : HitOutcome

  • Takes: the session, the trail service, the fuse service and the grace length.
  • Gives: Blocked, LifeLost or RunOver.
  • Promises: it tries the shield first, then loses a life, then respawns if lives remain.
  • Refuses: nothing. After the last life it gives RunOver and does not respawn.
  • Requirements: LIV-02 to LIV-07.

Two tests cover it. Open Tests/Systems/LivesSystemTests.cs. Add the following test to the LivesSystemTests class, below the TryBlockWithShield_SpendsOneChargeInsteadOfALife test. It gives the player one charge, resolves a hit and checks that the player is back on the wall with grace and no trail.

add-member Tests/Systems/LivesSystemTests.cs after=TryBlockWithShield_SpendsOneChargeInsteadOfALife
csharp
    [Fact]
    public void ShieldBlock_ReturnsPlayerToWallWithGrace()
    {
        GameplaySimulation sim = DrawingSimulation();
        sim.Session.ShieldCharges = 1;

        HitOutcome outcome = new LivesSystem().ResolveHit(sim.Session, sim.Trails, sim.Fuse, sim.Config.RespawnGraceSeconds);

        Assert.Equal(HitOutcome.Blocked, outcome);
        Assert.True(sim.Session.PlayableWallPath.Contains(sim.Session.Player.Position));
        Assert.Equal(sim.Config.RespawnGraceSeconds, sim.Session.RespawnGraceRemaining);
        Assert.Null(sim.Session.Player.CurrentTrail);
    }

Add the following test below the LoseLife_CancelsTrailAndFuse test. It sets the player to one life and resolves a hit. The outcome must be RunOver and the lives must be 0. A second call to LoseLife must still give 0.

add-member Tests/Systems/LivesSystemTests.cs after=LoseLife_CancelsTrailAndFuse
csharp
    [Fact]
    public void LoseLife_OnLastLife_EndsTheRun()
    {
        GameplaySimulation sim = DrawingSimulation();
        sim.Session.Player.Lives = 1;
        LivesSystem lives = new();

        HitOutcome outcome = lives.ResolveHit(sim.Session, sim.Trails, sim.Fuse, sim.Config.RespawnGraceSeconds);

        Assert.Equal(HitOutcome.RunOver, outcome);
        Assert.Equal(0, sim.Session.Player.Lives);
        Assert.Equal(0, lives.LoseLife(sim.Session, sim.Trails, sim.Fuse));
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 2 and Passed: 70.

Open Source/Systems/LivesSystem.cs. Find the ResolveHit method and replace the whole method with the following:

replace-method Source/Systems/LivesSystem.cs ResolveHit
csharp
    public HitOutcome ResolveHit(GameSession session, TrailSystem trails, FuseSystem fuse, float graceSeconds)
    {
        if (TryBlockWithShield(session, trails, fuse, graceSeconds))
        {
            return HitOutcome.Blocked;
        }

        if (LoseLife(session, trails, fuse) <= 0)
        {
            return HitOutcome.RunOver;
        }

        Respawn(session, graceSeconds);
        return HitOutcome.LifeLost;
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 72.

The key things to note are:

  • The three steps are in the order of the rules: shield, life, respawn. This is the only place that order is written down.
  • A hit that ends the run returns before Respawn. A player with no lives has nowhere to go.
  • LifeLost and Blocked are separate results, so the simulation can raise a different event for each.

Changing the simulation ​

The service is finished. Now the simulation must use it. This section adds the events and the state, strengthens two tests, adds two new ones, and then rewrites the parts of GameplaySimulation that handle a hit.

Events and state ​

Open Source/Simulation/GameEvent.cs. Add the following records at the end of the file. A record is a small class that compares by its values. ShieldBlocked and RunLost carry no data. LifeLost carries the lives that remain, so a later HUD can show the number.

add-type Source/Simulation/GameEvent.cs
csharp
public sealed record ShieldBlocked : GameEvent;

public sealed record LifeLost(int LivesLeft) : GameEvent;

public sealed record RunLost : GameEvent;

Open Source/Simulation/SimulationState.cs. Add a second value to the SimulationState enum. RunLost marks a simulation whose run has ended. Find this line:

find Source/Simulation/SimulationState.cs
csharp
    Running,

Add the following line directly after it:

csharp
    RunLost,

Open Tests/TestHelpers/ScriptedInput.cs. Add the following method to the ScriptedInput class, below the Run method. It runs frames until an event of one type appears, or until a frame limit, and it returns every event it saw. A test uses it to wait for a fuse that takes an unknown number of frames to arrive. New to generic constraints? See the C# primer.

add-member Tests/TestHelpers/ScriptedInput.cs after=Run
csharp
    // Runs until an event of the given type is raised, or the frame limit is reached.
    public static List<GameEvent> RunUntil<TEvent>(GameplaySimulation simulation, InputState input, int maxFrames)
        where TEvent : GameEvent
    {
        List<GameEvent> raised = [];
        for (int frame = 0; frame < maxFrames; frame++)
        {
            raised.AddRange(simulation.Tick(Frame, input));
            if (raised.OfType<TEvent>().Any())
            {
                break;
            }
        }

        return raised;
    }

Why two tests change ​

Two tests that already pass describe the old rule. Tick_FuseReachingPlayer_CancelsTheTrail from Chapter 08: The Fuse Service and Tick_EnemyTouchingTrail_CancelsTheTrail from Chapter 10 both end with the same check: the player is back at the point where the trail began. Under the new rule, a hit sends the player to a respawn node, so that check would fail even though the game is working as designed.

A test changes for one of two reasons. A rule changed, and the test describes the old rule. Or the code is wrong, and the test caught it. The first is expected. The test is a record of what the game promised, so when the promise changes the record changes too, in the same step. The second is a warning, and the test must stay as it is.

Both tests keep their names. The trail is still cancelled, so the name is still true. What changes is the body: it now checks that a life was lost, which is the new part of the promise.

Open Tests/Simulation/FuseScenarioTests.cs. Find the Tick_FuseReachingPlayer_CancelsTheTrail test and replace the whole test with the following. It waits for a LifeLost event with two lives left.

replace-method Tests/Simulation/FuseScenarioTests.cs Tick_FuseReachingPlayer_CancelsTheTrail
csharp
    [Fact]
    public void Tick_FuseReachingPlayer_CancelsTheTrail()
    {
        GameplaySimulation sim = SimulationBuilder.Create();
        ScriptedInput.Run(sim, ScriptedInput.Right, 4);
        ScriptedInput.Run(sim, ScriptedInput.Down, 3);

        List<GameEvent> events = ScriptedInput.RunUntil<LifeLost>(sim, ScriptedInput.Up, 100);

        Assert.Contains(events, e => e is LifeLost { LivesLeft: 2 });
        Assert.Null(sim.Session.Player.CurrentTrail);
        Assert.False(sim.Fuse.IsActive);
    }

Open Tests/Simulation/EnemyScenarioTests.cs. Find the Tick_EnemyTouchingTrail_CancelsTheTrail test and replace the whole test with the following:

replace-method Tests/Simulation/EnemyScenarioTests.cs Tick_EnemyTouchingTrail_CancelsTheTrail
csharp
    [Fact]
    public void Tick_EnemyTouchingTrail_CancelsTheTrail()
    {
        GameplaySimulation sim = SimulationBuilder.Create();
        ScriptedInput.Run(sim, ScriptedInput.Right, 4);
        ScriptedInput.Run(sim, ScriptedInput.Down, 3);
        sim.WithFrozenEnemyAt(20, 8);

        List<GameEvent> events = ScriptedInput.Run(sim, ScriptedInput.Down, 1);

        Assert.Contains(events, e => e is LifeLost);
        Assert.Null(sim.Session.Player.CurrentTrail);
        Assert.Equal(2, sim.Session.Player.Lives);
    }

The key changes in both tests are:

  • The position check is gone, because the respawn node is not the point where the trail began.
  • A check for LifeLost is new. The enemy test also checks that two lives remain.

Two grace scenarios ​

In the Tests/Simulation folder, create a new file named GraceScenarioTests.cs and add the following code. The first test starts a trail, puts a frozen enemy on the player and sets a grace of 5 seconds. Two more frames must raise no LifeLost or ShieldBlocked, and the player must keep three lives.

new-file Tests/Simulation/GraceScenarioTests.cs
csharp
using LastPerimeter.Simulation;
using LastPerimeter.Tests.TestHelpers;

namespace LastPerimeter.Tests.Simulation;

public sealed class GraceScenarioTests
{
    [Fact]
    public void Tick_IgnoresHitsDuringGrace()
    {
        GameplaySimulation sim = SimulationBuilder.Create();
        ScriptedInput.Run(sim, ScriptedInput.Right, 4);
        ScriptedInput.Run(sim, ScriptedInput.Down, 3);
        sim.WithFrozenEnemyAt(sim.Session.Player.Position.X, sim.Session.Player.Position.Y);
        sim.Session.RespawnGraceRemaining = 5f;

        List<GameEvent> events = ScriptedInput.Run(sim, ScriptedInput.Down, 2);

        Assert.DoesNotContain(events, e => e is LifeLost or ShieldBlocked);
        Assert.Equal(3, sim.Session.Player.Lives);
    }
}

Open Tests/Simulation/GraceScenarioTests.cs. Add the following test to the GraceScenarioTests class, below the Tick_IgnoresHitsDuringGrace test. The player moves right along the wall, grace is set, and the player then pushes down into open space. No trail may start.

add-member Tests/Simulation/GraceScenarioTests.cs after=Tick_IgnoresHitsDuringGrace
csharp
    [Fact]
    public void Tick_DoesNotStartTrailDuringGrace()
    {
        GameplaySimulation sim = SimulationBuilder.Create();
        ScriptedInput.Run(sim, ScriptedInput.Right, 4);
        sim.Session.RespawnGraceRemaining = 5f;

        List<GameEvent> events = ScriptedInput.Run(sim, ScriptedInput.Down, 3);

        Assert.DoesNotContain(events, e => e is TrailStarted);
        Assert.Null(sim.Session.Player.CurrentTrail);
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 3 and Passed: 71. The two strengthened tests fail, because the simulation still cancels the trail without costing a life. The trail test fails, because nothing waits for grace. Tick_IgnoresHitsDuringGrace passes for now. The old rule raises no LifeLost either, so the test cannot tell the two rules apart yet.

Using the service in the tick ​

Open Source/Simulation/GameplaySimulation.cs. A new level clears the grace and the protection flag. In the StartLevel method, find this line:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
        _session.Player.Position = SelectStartNode(_session.PlayableWallPath);

Add the following lines directly after it:

csharp
        _session.Player.IsInvulnerable = false;
        _session.RespawnGraceRemaining = 0f;

In the Tick method, the new lines are in step 1. The flag follows the grace timer, and the timer counts down. The step numbers are explained in the order of one tick. Find this comment line:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
        // 1. Timers.

Add the following lines directly after it:

csharp
        player.IsInvulnerable = _session.RespawnGraceRemaining > 0f;
        _session.RespawnGraceRemaining = Math.Max(0f, _session.RespawnGraceRemaining - deltaTime);

In the TickWhileDrawing method, both hit sources must call ResolveHit where they called CancelTrail. Find these lines in step 8a:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
        if (killedByFuse)
        {
            CancelTrail(activeTrail);

Replace them with:

csharp
        if (killedByFuse)
        {
            ResolveHit();

Find these lines in step 8b:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
        if (IsPlayerOrTrailHit(player, activeTrail))
        {
            CancelTrail(activeTrail);

Replace them with:

csharp
        if (!player.IsInvulnerable && IsPlayerOrTrailHit(player, activeTrail))
        {
            ResolveHit();

The key changes are:

  • Step 8a calls ResolveHit where it called CancelTrail.
  • Step 8b calls ResolveHit too, and only when the player is not invulnerable.

In the TickOnWall method, a trail cannot start while grace remains, so the first condition of step 9c is new. Find this line:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
        if (_session.PlayableWallPath.Contains(player.Position)

Replace it with:

csharp
        if (_session.RespawnGraceRemaining <= 0f
            && _session.PlayableWallPath.Contains(player.Position)

Add the following method to the GameplaySimulation class, below the TickOnWall method. It asks LivesSystem what happened, and raises the matching events. For a hit that ends the run, it raises LifeLost and then RunLost, and it changes the state.

add-member Source/Simulation/GameplaySimulation.cs after=TickOnWall
csharp
    private void ResolveHit()
    {
        HitOutcome outcome = _lives.ResolveHit(_session, _trails, _fuse, _baseConfig.RespawnGraceSeconds);
        switch (outcome)
        {
            case HitOutcome.Blocked:
                _events.Add(new ShieldBlocked());
                break;
            case HitOutcome.LifeLost:
                _events.Add(new LifeLost(_session.Player.Lives));
                break;
            case HitOutcome.RunOver:
                _events.Add(new LifeLost(_session.Player.Lives));
                _events.Add(new RunLost());
                State = SimulationState.RunLost;
                break;
        }
    }

Nothing calls CancelTrail now. Delete the CancelTrail method from Source/Simulation/GameplaySimulation.cs. Chapter 10 added the call in step 8b, and Chapter 08 added the call in step 8a. Both have moved into LivesSystem.

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 74.

The key things to note are:

  • The timer step sets the flag before it counts down. A grace of 1.2 seconds therefore covers the full 1.2 seconds, including the frame in which it reaches 0.
  • Both hit sources go through the single ResolveHit method. The order of shield, life and respawn is written only in LivesSystem.
  • ResolveHit returns after the call in both places, so no later step in the same frame runs on a trail that no longer exists.
  • The switch has one case per outcome. RunOver raises two events, in the order that a listener expects: the life first, and then the end.

Wiring it into the game ​

Two small changes remain: the scene and the renderer. Open Source/Scenes/GameplayScene.cs. In the Update method, when a RunLost event arrives, the scene changes to the title scene and stops reading events. This is a stand-in. Chapter 18 shows a run summary at this point. Find these lines:

find Source/Scenes/GameplayScene.cs
csharp
                _claimedArea?.MarkDirty();
            }

Add the following lines directly after them. The return after the scene change matters, because the scene is finished and must not read any more events:

csharp
            else if (events[index] is RunLost)
            {
                // Chapter 18 shows a run summary here instead.
                Scenes.Change(new TitleScene(_services));
                return;
            }

Open Source/Rendering/PlayerRenderer.cs. A protected player is drawn 45 per cent of the way towards white. In the Draw method, find this line:

find Source/Rendering/PlayerRenderer.cs
csharp
        PrimitiveDrawing.DrawFilledCircle(spriteBatch, pixel, player.Position, player.Radius, color);

Replace it with:

csharp
        Color drawColor = player.IsInvulnerable ? Color.Lerp(color, Color.White, 0.45f) : color;
        PrimitiveDrawing.DrawFilledCircle(spriteBatch, pixel, player.Position, player.Radius, drawColor);

Running the tests ​

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 74. The 74 tests are the 66 from earlier chapters and the 8 new ones.

TestProves
TryBlockWithShield_SpendsOneChargeInsteadOfALifeLIV-02
ShieldBlock_ReturnsPlayerToWallWithGraceLIV-03
LoseLife_CancelsTrailAndFuseLIV-04
LoseLife_OnLastLife_EndsTheRunLIV-05
SelectRespawnNode_PrefersNodesFarFromEnemiesLIV-06
Respawn_StartsGraceFromConfigLIV-07
Tick_IgnoresHitsDuringGraceCOL-03
Tick_DoesNotStartTrailDuringGraceTRL-01

Running the game ​

From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen. Hold the Down arrow to leave the wall and start a trail, and wait for the enemy to touch it. Your dot jumps to a wall node far from the enemy and turns paler, as in Figure 11-1. Hold the Down arrow again at once. For about a second, no trail starts. After that, the dot returns to its normal colour and you can draw again.

The screen does not show your lives yet. Chapter 12 adds the heads-up display. Let the enemy hit you three times. The third hit ends the run, and the window returns to the title screen. Press Enter to start again. Close the window with its close button when you have seen enough. The test counts prove the shield, life and respawn rules. Only the window shows the paler dot and the return to the title screen.

TIP

No powerup awards a shield yet, so you cannot see one work in play. To try one, open Source/Simulation/GameplaySimulation.cs, find StartLevel and add _session.ShieldCharges = 1; below the line _session.RespawnGraceRemaining = 0f;. Run the game and let an enemy hit you once. You return to the wall near where you left it, and no life is lost. Then delete the line, so that your files match the 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 11 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/11-Lives-Shields-And-Respawn"
Remove-Item -Recurse -Force Source, Tests
Copy-Item -Recurse "$snapshot/Source" Source
Copy-Item -Recurse "$snapshot/Tests" Tests

In 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/11-Lives-Shields-And-Respawn"
rm -rf Source Tests
cp -r "$snapshot/Source" Source
cp -r "$snapshot/Tests" Tests

Then run dotnet test from the LastPerimeter folder and check for Passed: 74.

Common mistakes ​

  • The player loses a life with a shield in hand. One of the two hit sources still calls LoseLife or the old cancel code instead of ResolveHit.
  • The fuse scenario never reports LifeLost. Step 8a still calls the old cancel code. Check that TickWhileDrawing calls ResolveHit.
  • A trail starts straight after a respawn. The grace condition is missing from step 9c in TickOnWall.
  • The player is hit during grace. Step 8b lacks !player.IsInvulnerable, or the flag is set after the contact check and not in step 1.
  • The build says CancelTrail does not exist. A call to it remains. Both calls in TickWhileDrawing must now call ResolveHit.
  • SelectRespawnNode_PrefersNodesFarFromEnemies picks the first node. The comparison uses >=, or the distance is measured to the player and not to the enemies.
  • The window does not return to the title after the last life. The RunLost branch in GameplayScene.Update is missing, or it comes before the CaptureCompleted check and breaks that branch.

Conclusion ​

In this chapter, you accomplished the following:

The tests now prove LIV-02 to LIV-07, COL-03 and TRL-01. In the next chapter, Chapter 12: Events, Score and Feedback, you turn these events into points, a heads-up display and sound.

Test Your Knowledge ​

  1. Why does ResolveHit exist when the three operations it calls are already public?

    Answer

    So that one place decides the order: shield, then life, then respawn. Two call sites would each have to remember the order, and one of them would eventually forget.

  2. Why add 500 per connected segment to a squared distance?

    Answer

    A junction offers more ways to leave. The weight only breaks near-ties, because squared distances across a real arena run to hundreds of thousands.

  3. Why can a trail not start during grace?

    Answer

    A protected player who could draw a trail could pass through an enemy for free. Grace pauses both hits and trail starts.

  4. You change a rule and a test fails. How do you tell whether to change the test?

    Answer

    Read what the test promises. If it describes the old rule, such as returning to the trail start, the test changes with the rule. If it describes something you meant to keep, the code is wrong and the test stays.

Extensions ​

  • Add a test that gives the player two shield charges and resolves two hits in a row. What outcome does each give, and how many lives remain?
  • Change ScorePerConnectedSegment to 0 and run the tests. Which test fails, and what does that show about the weight?