Skip to content

Chapter 15: Powerups ​

In Chapter 14: Levels and Difficulty, you turned one level into a sequence with bonuses. The only reward so far is territory. Nothing tempts the player to leave a safe route.

In this chapter, you add pickups that appear on the wall for a short time. Each one changes exactly one piece of game state, and all five effects live in one place.

Figure 15-1: The chapter 15 window, with two powerups on the wall and the DOUBLE PTS label in the status area
Figure 15-1: The chapter 15 window, with two powerups on the wall and the DOUBLE PTS label in the status area. This is a drawn illustration, not a screenshot.

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

In this chapter, you will:

  • Learn the five effect shapes: a charge, a timer, a counter, a reset and a multiplier.
  • Build PowerupSystem, which times the spawns, picks a place, expires powerups and collects them.
  • Build PowerupEffects, one case per type, with a test that each type changes only its own state.
  • Add the new timers and the powerup step to the tick, and Double Points to the capture score.
  • Draw powerups with a small renderer of their own.

Requirements in this chapter ​

IDShort name
PWR-01At most 2 powerups at once
PWR-02The first spawn waits 6 seconds each level
PWR-03Later spawns wait 7 to 11 seconds
PWR-04Placement on a wall node, random type
PWR-05A powerup expires after 8 seconds
PWR-06Collection by touching
PWR-07The five effects
SCO-04Double Points
FUS-06Fuse Reset puts out the fuse
ENM-10Freeze, now reachable in play

Five effect shapes ​

The five powerups look different, but each one fits one of five shapes. A charge is a stored count that a later event spends. A timer is a value that counts down to zero. A counter is a number that changes once. A reset puts a running thing back to its start. A multiplier scales a rule while a timer runs. Figure 15-2 lays them out.

Figure 15-2: The five effect shapes. Shield is a charge, Freeze a timer, Extra Life a counter, Fuse Reset a reset and Double Points a timed multiplier
Figure 15-2: The five effect shapes. Shield is a charge, Freeze a timer, Extra Life a counter, Fuse Reset a reset and Double Points a timed multiplier

Each effect changes one field and nothing else. Shield adds to ShieldCharges. Freeze sets FreezeEnemiesRemaining to 2 seconds. Extra Life adds to the player's lives. Fuse Reset calls Reset on the fuse. Double Points sets DoublePointsRemaining to 10 seconds. The simulation counts the two timers down in step 1 of every tick, beside the grace timer.

Why the wall ​

Powerups spawn on wall nodes, which are the corners of the playable wall path. The wall is the safe ground. The pickup itself costs nothing, because the player stands on the wall when they take it. The risk is the detour. A player who wants the Freeze at the far corner walks past the place where the enemies are heading.

This also keeps the rule simple. A node is always reachable on foot, because the wall path is rebuilt after every capture and every node is on it.

One place for the effects ​

PowerupEffects.Apply is one static method with one case for each type. Adding a type means adding one enum value and one case. The test for the method runs once for each type and checks every field that an effect could touch. A bug that lets Freeze change the lives is caught by the Freeze row of that test.

A class for each powerup would be more machinery than five one-line effects need. It would pay off only if an effect had its own state or behaviour over time.

Adding the data ​

You start with the type and the entity. Open Source/Data/Enums.cs and replace the whole file with the following. The new PowerupType goes at the end. DifficultyPreset also moves above EnemyVariant. The order of the enums does not change how the game behaves, but moving an enum is easiest by replacing the file, so the whole file is shown:

replace-file Source/Data/Enums.cs
csharp
namespace LastPerimeter.Data;

public enum Direction
{
    None,
    Up,
    Down,
    Left,
    Right,
}

public static class DirectionExtensions
{
    public static Direction Opposite(this Direction direction) => direction switch
    {
        Direction.Up => Direction.Down,
        Direction.Down => Direction.Up,
        Direction.Left => Direction.Right,
        Direction.Right => Direction.Left,
        _ => Direction.None,
    };

    public static Microsoft.Xna.Framework.Vector2 ToVector(this Direction direction) => direction switch
    {
        Direction.Up => new Microsoft.Xna.Framework.Vector2(0f, -1f),
        Direction.Down => new Microsoft.Xna.Framework.Vector2(0f, 1f),
        Direction.Left => new Microsoft.Xna.Framework.Vector2(-1f, 0f),
        Direction.Right => new Microsoft.Xna.Framework.Vector2(1f, 0f),
        _ => Microsoft.Xna.Framework.Vector2.Zero,
    };
}

public enum TrailState
{
    InProgress,
    Completed,
    Cancelled,
}

public enum TileState
{
    Unclaimed,
    ClaimedByPlayer,
    Boundary,
}

public enum DifficultyPreset
{
    Chill,
    Classic,
    Hardcore,
}

public enum EnemyVariant
{
    Wanderer,
    Hunter,
    Splitter,
}

public enum PowerupType
{
    Shield,
    Freeze,
    ExtraLife,
    FuseReset,
    DoublePoints,
}

In the Source/Entities folder, create a new file named Powerup.cs and add the following code. The required keyword means that code creating a powerup must set the type and the position:

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

namespace LastPerimeter.Entities;

public sealed class Powerup
{
    private const float DefaultLifetimeSeconds = 8f;

    public required PowerupType Type { get; init; }
    public required Vector2 Position { get; init; }
    public float Radius { get; init; } = 7f;
    public float RemainingLifetimeSeconds { get; set; } = DefaultLifetimeSeconds;
}

The key things to note are:

  • A powerup lives for 8 seconds unless it is collected. RemainingLifetimeSeconds counts down.
  • Radius is 7 pixels. Collection compares it with the player's radius.
  • Type and Position use init, so a powerup never changes type or moves.

Open Source/Data/GameSession.cs. Add the following property to the GameSession class, below the CaptureHistory property. The session holds the live powerups:

add-member Source/Data/GameSession.cs after=CaptureHistory
csharp
    public List<Powerup> Powerups { get; init; } = [];

Add the following property below the FreezeEnemiesRemaining property. It is the second timer that step 1 of the tick counts down. The steps are numbered in the table in Chapter 05: Scenes and the Gameplay Simulation:

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

Building the powerup service ​

PowerupSystem decides when a powerup appears, where, and when it goes. Like EnemySystem, it takes an optional Random. A test passes a seeded one and gets the same powerups every time.

Your first listing is the shell of the service. The constants, the field and the constructor are written in full. Every operation throws for now. In the Source/Systems folder, create a new file named PowerupSystem.cs and add the following code:

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

namespace LastPerimeter.Systems;

public sealed class PowerupSystem
{
    public const int MaxActivePowerups = 2;
    public const float FreezeDurationSeconds = 2f;
    public const float DoublePointsDurationSeconds = 10f;

    private const float FirstSpawnDelaySeconds = 6f;
    private const float MinimumSpawnIntervalSeconds = 7f;
    private const float SpawnIntervalVarianceSeconds = 4f;

    private readonly Random _random;
    private float _spawnTimerSeconds = FirstSpawnDelaySeconds;

    // Pass a seeded Random to make spawns repeatable (tests, seeded runs).
    public PowerupSystem(Random? random = null)
    {
        _random = random ?? new Random();
    }

    public void UpdateSpawnTimer(float deltaTime)
    {
        throw new NotImplementedException();
    }

    public bool CanSpawn => throw new NotImplementedException();

    public void ResetForLevel()
    {
        throw new NotImplementedException();
    }

    public void ResetSpawnTimer(float minimum = MinimumSpawnIntervalSeconds, float variance = SpawnIntervalVarianceSeconds)
    {
        throw new NotImplementedException();
    }

    public Powerup Spawn(PlayableWallPath wallPath)
    {
        throw new NotImplementedException();
    }

    public void UpdatePowerups(List<Powerup> powerups, float deltaTime)
    {
        throw new NotImplementedException();
    }

    public Powerup? TryCollect(List<Powerup> powerups, Vector2 playerPosition, float pickupRadius)
    {
        throw new NotImplementedException();
    }
}

The key things to note are:

  • The constants hold every number of this chapter: 2 powerups at most, a 6 second first delay, and 7 seconds plus up to 4 more between spawns.
  • The three public constants are used by other code. The effects table reads the two durations, and the simulation reads the maximum.
  • _spawnTimerSeconds starts at the first delay, so a new service waits 6 seconds before its first spawn.
  • If you run dotnet build now, expect a warning such as CS0414 about a private field that is assigned and never used. The stub bodies read nothing yet. The warning goes away when the bodies are written, so it is not a mistake.

Timing the spawns ​

Four small operations manage the spawn timer. Here are their cards.

PowerupSystem.UpdateSpawnTimer(deltaTime) and CanSpawn

  • Takes: the frame time.
  • Gives: CanSpawn is true once the timer reaches zero.
  • Promises: the timer counts down and stops at zero. It never goes negative.
  • Refuses: nothing.
  • Requirements: PWR-03.

PowerupSystem.ResetForLevel()

  • Takes: nothing.
  • Gives: nothing.
  • Promises: the next spawn waits the full 6 seconds.
  • Refuses: nothing.
  • Requirements: PWR-02.

PowerupSystem.ResetSpawnTimer(minimum, variance) sets the timer to the minimum plus a random part of the variance. The defaults are 7 and 4 seconds, so the wait is 7 to 11 seconds. Requirements: PWR-03.

The service lives for the whole run, but each level has its own rhythm. Without ResetForLevel, a timer left over from the last level could spawn a powerup on the first frame of the next one.

In the Tests/Systems folder, create a new file named PowerupSystemTests.cs and add the following code. The test runs the timer to zero, resets it for a level, and checks that a spawn is not allowed at 5.9 seconds but is at 6.1:

new-file Tests/Systems/PowerupSystemTests.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 PowerupSystemTests
{
    [Fact]
    public void ResetForLevel_RestoresTheFirstSpawnDelay()
    {
        PowerupSystem system = new();
        system.UpdateSpawnTimer(100f);
        Assert.True(system.CanSpawn);

        system.ResetForLevel();
        system.UpdateSpawnTimer(5.9f);

        Assert.False(system.CanSpawn);
        system.UpdateSpawnTimer(0.2f);
        Assert.True(system.CanSpawn);
    }
}

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

Open Source/Systems/PowerupSystem.cs. Find the UpdateSpawnTimer method and replace the whole method with the following:

replace-method Source/Systems/PowerupSystem.cs UpdateSpawnTimer
csharp
    public void UpdateSpawnTimer(float deltaTime)
    {
        _spawnTimerSeconds = Math.Max(0f, _spawnTimerSeconds - deltaTime);
    }

Find the CanSpawn property and replace the whole property with the following:

replace-method Source/Systems/PowerupSystem.cs CanSpawn
csharp
    public bool CanSpawn => _spawnTimerSeconds <= 0f;

Find the ResetForLevel method and replace the whole method with the following:

replace-method Source/Systems/PowerupSystem.cs ResetForLevel
csharp
    // Call at the start of every level so its first powerup waits the full delay.
    public void ResetForLevel()
    {
        _spawnTimerSeconds = FirstSpawnDelaySeconds;
    }

Find the ResetSpawnTimer method and replace the whole method with the following:

replace-method Source/Systems/PowerupSystem.cs ResetSpawnTimer
csharp
    public void ResetSpawnTimer(float minimum = MinimumSpawnIntervalSeconds, float variance = SpawnIntervalVarianceSeconds)
    {
        _spawnTimerSeconds = minimum + (_random.NextSingle() * variance);
    }

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

The key things to note are:

  • Math.Max(0f, ...) stops the timer at zero, so CanSpawn stays true until something resets it.
  • CanSpawn is a property with an expression body, so it reads like a field and has no parentheses.
  • ResetSpawnTimer has default arguments, so a caller can pass different numbers and a test can use a short wait.
  • NextSingle gives a number from 0 up to but not including 1. Multiplied by 4 and added to 7, it gives 7 to just under 11.

Spawning a powerup ​

PowerupSystem.Spawn(wallPath) : Powerup

  • Takes: the playable wall path.
  • Gives: a new powerup of a random type on a random wall node.
  • Promises: the position is one of the path's nodes. The same seed picks the same type and node. The spawn timer is re-armed for 7 to 11 seconds.
  • Refuses: nothing. The caller checks CanSpawn first.
  • Requirements: PWR-03, PWR-04.

Open Tests/Systems/PowerupSystemTests.cs. Add the following test to the PowerupSystemTests class, above the ResetForLevel_RestoresTheFirstSpawnDelay test. It builds a real wall path and checks that the powerup sits on one of its nodes:

add-member Tests/Systems/PowerupSystemTests.cs before=ResetForLevel_RestoresTheFirstSpawnDelay
csharp
    [Fact]
    public void Spawn_UsesWallNodesForPlacement()
    {
        ArenaSystem arena = new(TestConfigFactory.Create());
        WallSystemV2 wallSystem = new();
        PlayableWallPath path = wallSystem.RebuildPlayablePath(arena);
        PowerupSystem system = new();

        Powerup powerup = system.Spawn(path);

        Assert.Contains(path.Nodes, node => node == powerup.Position);
    }

Add the following test below the Spawn_UsesWallNodesForPlacement test. It spawns from two services with the same seed and compares the results:

add-member Tests/Systems/PowerupSystemTests.cs after=Spawn_UsesWallNodesForPlacement
csharp
    [Fact]
    public void Spawn_WithSameSeed_PicksSameTypeAndNode()
    {
        ArenaSystem arena = new(TestConfigFactory.Create());
        PlayableWallPath path = new WallSystemV2().RebuildPlayablePath(arena);
        PowerupSystem first = new(new Random(7));
        PowerupSystem second = new(new Random(7));

        Powerup a = first.Spawn(path);
        Powerup b = second.Spawn(path);

        Assert.Equal(a.Type, b.Type);
        Assert.Equal(a.Position, b.Position);
    }

Add the following test below the ResetForLevel_RestoresTheFirstSpawnDelay test. It spawns once and checks that the timer was re-armed between 7 and 11 seconds:

add-member Tests/Systems/PowerupSystemTests.cs after=ResetForLevel_RestoresTheFirstSpawnDelay
csharp
    [Fact]
    public void Spawn_RearmsTimerBetweenSevenAndElevenSeconds()
    {
        PowerupSystem system = new(new Random(3));
        PlayableWallPath path = new(new[] { new PathSegment(new Vector2(0, 0), new Vector2(20, 0)) });
        system.UpdateSpawnTimer(10f);
        Assert.True(system.CanSpawn);

        system.Spawn(path);

        Assert.False(system.CanSpawn);
        system.UpdateSpawnTimer(6.9f);
        Assert.False(system.CanSpawn);
        system.UpdateSpawnTimer(4.2f);
        Assert.True(system.CanSpawn);
    }

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

Open Source/Systems/PowerupSystem.cs. Find the Spawn method and replace the whole method with the following:

replace-method Source/Systems/PowerupSystem.cs Spawn
csharp
    public Powerup Spawn(PlayableWallPath wallPath)
    {
        IReadOnlyList<Vector2> candidates = wallPath.Nodes;
        Vector2 position = candidates[_random.Next(candidates.Count)];
        PowerupType type = (PowerupType)_random.Next(Enum.GetValues<PowerupType>().Length);
        ResetSpawnTimer();
        return new Powerup
        {
            Type = type,
            Position = position,
        };
    }

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

The key things to note are:

  • The node and the type both come from the one Random, so a seeded service is repeatable.
  • Enum.GetValues<PowerupType>().Length counts the types, so a sixth type is spawned without a change here.
  • Spawn calls ResetSpawnTimer itself. A caller cannot spawn and forget to re-arm.

Expiring and collecting ​

PowerupSystem.UpdatePowerups(powerups, deltaTime) : void

  • Takes: the live powerups and the frame time.
  • Gives: nothing. The list changes.
  • Promises: each powerup's lifetime counts down, and one that reaches zero is removed.
  • Refuses: nothing.
  • Requirements: PWR-05.

PowerupSystem.TryCollect(powerups, playerPosition, pickupRadius) : Powerup?

  • Takes: the live powerups, the player position and the player radius.
  • Gives: the first powerup that touches the player, or null.
  • Promises: the powerup is removed from the list. Touching means the two circles overlap.
  • Refuses: with nothing in range, the list is untouched and the result is null.
  • Requirements: PWR-06.

Open Tests/Systems/PowerupSystemTests.cs. Add the following test to the PowerupSystemTests class, above the Spawn_UsesWallNodesForPlacement test. The player is 2 pixels from the powerup, inside the combined radius of 13:

add-member Tests/Systems/PowerupSystemTests.cs before=Spawn_UsesWallNodesForPlacement
csharp
    [Fact]
    public void TryCollect_RemovesPowerupWhenPlayerIsInRange()
    {
        PowerupSystem system = new();
        List<Powerup> powerups =
        [
            new Powerup
            {
                Type = PowerupType.Shield,
                Position = new Vector2(10f, 10f),
            },
        ];

        Powerup? collected = system.TryCollect(powerups, new Vector2(12f, 10f), 6f);

        Assert.NotNull(collected);
        Assert.Empty(powerups);
    }

Add the following test to the end of the class. It makes one fresh powerup and one with a second left, then lets 2 seconds pass:

add-member Tests/Systems/PowerupSystemTests.cs at=end
csharp
    [Fact]
    public void UpdatePowerups_RemovesExpiredPowerups()
    {
        PowerupSystem system = new();
        List<Powerup> powerups =
        [
            new Powerup { Type = PowerupType.Shield, Position = Vector2.Zero },
            new Powerup { Type = PowerupType.Freeze, Position = Vector2.One, RemainingLifetimeSeconds = 1f },
        ];

        system.UpdatePowerups(powerups, 2f);

        Assert.Single(powerups);
        Assert.Equal(PowerupType.Shield, powerups[0].Type);
    }

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

Open Source/Systems/PowerupSystem.cs. Find the UpdatePowerups method and replace the whole method with the following:

replace-method Source/Systems/PowerupSystem.cs UpdatePowerups
csharp
    public void UpdatePowerups(List<Powerup> powerups, float deltaTime)
    {
        for (int index = powerups.Count - 1; index >= 0; index--)
        {
            powerups[index].RemainingLifetimeSeconds -= deltaTime;
            if (powerups[index].RemainingLifetimeSeconds <= 0f)
            {
                powerups.RemoveAt(index);
            }
        }
    }

Find the TryCollect method and replace the whole method with the following:

replace-method Source/Systems/PowerupSystem.cs TryCollect
csharp
    public Powerup? TryCollect(List<Powerup> powerups, Vector2 playerPosition, float pickupRadius)
    {
        for (int index = 0; index < powerups.Count; index++)
        {
            Powerup powerup = powerups[index];
            float radius = powerup.Radius + pickupRadius;
            if (Vector2.DistanceSquared(powerup.Position, playerPosition) > radius * radius)
            {
                continue;
            }

            powerups.RemoveAt(index);
            return powerup;
        }

        return null;
    }

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

The key things to note are:

  • UpdatePowerups walks the list backwards, so RemoveAt never skips an entry.
  • TryCollect compares squared distances against the squared sum of the radii. That avoids a square root and gives the same answer.
  • continue skips a powerup that is too far away. The first one in range is removed and returned, and the loop stops.

Building the effects ​

PowerupEffects.Apply(type, session, fuse) : void

  • Takes: a powerup type, the session and the level's fuse.
  • Gives: nothing. One piece of state changes.
  • Promises: Shield adds a charge. Freeze sets the freeze timer to 2 seconds. Extra Life adds a life. Fuse Reset puts out the fuse. Double Points sets its timer to 10 seconds. Nothing else changes.
  • Refuses: nothing.
  • Requirements: PWR-07, FUS-06.

In the Source/Systems folder, create a new file named PowerupEffects.cs and add the following code. It is a static class, because the method keeps no state of its own:

new-file Source/Systems/PowerupEffects.cs
csharp
using LastPerimeter.Data;

namespace LastPerimeter.Systems;

public static class PowerupEffects
{
    public static void Apply(PowerupType type, GameSession session, FuseSystem fuse)
    {
        throw new NotImplementedException();
    }
}

In the Tests/Systems folder, create a new file named PowerupEffectsTests.cs and add the following code. This is a [Theory] with one [InlineData] row for each type, so the runner reports 5 tests. The test lights the fuse first, applies one type, and then checks every field. Each field must be unchanged, except the one that the type owns:

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

namespace LastPerimeter.Tests.Systems;

public sealed class PowerupEffectsTests
{
    [Theory]
    [InlineData(PowerupType.Shield)]
    [InlineData(PowerupType.Freeze)]
    [InlineData(PowerupType.ExtraLife)]
    [InlineData(PowerupType.FuseReset)]
    [InlineData(PowerupType.DoublePoints)]
    public void Apply_EachTypeChangesOnlyItsOwnState(PowerupType type)
    {
        GameplaySimulation sim = SimulationBuilder.Create();
        GameSession session = sim.Session;
        FuseSystem fuse = sim.Level.Fuse;
        Trail trail = new();
        trail.AddPoint(new Vector2(0, 0));
        trail.AddPoint(new Vector2(100, 0));
        fuse.Update(trail, false, 5f);
        Assert.True(fuse.IsActive);

        PowerupEffects.Apply(type, session, fuse);

        Assert.Equal(type == PowerupType.Shield ? 1 : 0, session.ShieldCharges);
        Assert.Equal(type == PowerupType.Freeze ? PowerupSystem.FreezeDurationSeconds : 0f, session.FreezeEnemiesRemaining);
        Assert.Equal(type == PowerupType.ExtraLife ? 4 : 3, session.Player.Lives);
        Assert.Equal(type == PowerupType.DoublePoints ? PowerupSystem.DoublePointsDurationSeconds : 0f, session.DoublePointsRemaining);
        Assert.Equal(type != PowerupType.FuseReset, fuse.IsActive);
    }
}

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

Open Source/Systems/PowerupEffects.cs. Find the Apply method and replace the whole method with the following:

replace-method Source/Systems/PowerupEffects.cs Apply
csharp
    // Each type changes only its own state.
    public static void Apply(PowerupType type, GameSession session, FuseSystem fuse)
    {
        switch (type)
        {
            case PowerupType.Shield:
                session.ShieldCharges++;
                break;
            case PowerupType.Freeze:
                session.FreezeEnemiesRemaining = PowerupSystem.FreezeDurationSeconds;
                break;
            case PowerupType.ExtraLife:
                session.Player.Lives++;
                break;
            case PowerupType.FuseReset:
                fuse.Reset();
                break;
            case PowerupType.DoublePoints:
                session.DoublePointsRemaining = PowerupSystem.DoublePointsDurationSeconds;
                break;
        }
    }

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

The key things to note are:

  • Each case changes one thing and ends with break. There is no fall-through.
  • The assertions compare every field with its expected value for the row. Freeze expects FreezeEnemiesRemaining to be 2 and every other row expects 0.
  • The fuse check is the Fuse Reset proof. The test lights the fuse, and only the Fuse Reset row expects IsActive to be false afterwards. That proves FUS-06 for a powerup.
  • The method has a fuse parameter and no other service. An effect can only touch what it is given.
  • Freeze only sets the timer. The enemies already stop while the timer runs, because UpdateEnemies passes frozen since Chapter 14. The Chapter 10 test Update_WhenFrozen_DoesNotMove proves the stop, which is ENM-10.

Wiring it into the game ​

Four parts remain: a new event, the two scenario tests, the simulation, and the drawing.

A new event and its status line ​

Collecting a powerup raises an event, and the scene plays a tone for it. Open Source/Simulation/GameEvent.cs. At the top of the file, add the following line above the namespace line. The event carries a PowerupType, which lives in the data namespace:

add-using Source/Simulation/GameEvent.cs
csharp
using LastPerimeter.Data;

Add the following record below the RunLost record:

add-type Source/Simulation/GameEvent.cs after=RunLost
csharp
public sealed record PowerupCollected(PowerupType Type) : GameEvent;

The status line must name each powerup. Open Tests/Scenes/StatusTextTests.cs. At the top of the file, add the following line above the other using lines:

add-using Tests/Scenes/StatusTextTests.cs before=LastPerimeter.Scenes
csharp
using LastPerimeter.Data;

In the StatusText_MapsEveryEventToALine test, find this line:

find Tests/Scenes/StatusTextTests.cs
csharp
        Assert.Equal(string.Empty, StatusText.For(new RunLost()));

Add the following lines directly below it. They add one line for each type:

csharp
        Assert.Equal("SHIELD READY", StatusText.For(new PowerupCollected(PowerupType.Shield)));
        Assert.Equal("ENEMIES FROZEN", StatusText.For(new PowerupCollected(PowerupType.Freeze)));
        Assert.Equal("EXTRA LIFE", StatusText.For(new PowerupCollected(PowerupType.ExtraLife)));
        Assert.Equal("FUSE RESET", StatusText.For(new PowerupCollected(PowerupType.FuseReset)));
        Assert.Equal("DOUBLE POINTS", StatusText.For(new PowerupCollected(PowerupType.DoublePoints)));

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

Open Source/Scenes/StatusText.cs. At the top of the file, add the following line above the other using lines:

add-using Source/Scenes/StatusText.cs before=LastPerimeter.Simulation
csharp
using LastPerimeter.Data;

Add the following method to the StatusText class, below the For method. It maps each type to its line:

add-member Source/Scenes/StatusText.cs after=For
csharp
    private static string ForPowerup(PowerupType type)
    {
        return type switch
        {
            PowerupType.Shield => "SHIELD READY",
            PowerupType.Freeze => "ENEMIES FROZEN",
            PowerupType.ExtraLife => "EXTRA LIFE",
            PowerupType.FuseReset => "FUSE RESET",
            PowerupType.DoublePoints => "DOUBLE POINTS",
            _ => string.Empty,
        };
    }

In the For method, find this line:

find Source/Scenes/StatusText.cs
csharp
            RunLost => string.Empty,

Add the following line directly below it. It hands a PowerupCollected event to ForPowerup:

csharp
            PowerupCollected powerup => ForPowerup(powerup.Type),

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

Two scenario tests first ​

Two rules cannot be tested on a service alone, because they live in the tick. At most 2 powerups may exist, and a capture during Double Points must score double. In the Tests/Simulation folder, create a new file named PowerupScenarioTests.cs and add the following code. The first test runs 3,000 frames with no input and records the most powerups ever alive. The second captures the same rectangle in two simulations and compares the points:

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

namespace LastPerimeter.Tests.Simulation;

public sealed class PowerupScenarioTests
{
    [Fact]
    public void Tick_NeverSpawnsAThirdPowerup()
    {
        GameplaySimulation sim = SimulationBuilder.Create(seed: 5);
        int highest = 0;

        for (int frame = 0; frame < 3000; frame++)
        {
            sim.Tick(ScriptedInput.Frame, ScriptedInput.Idle);
            highest = Math.Max(highest, sim.Session.Powerups.Count);
        }

        Assert.InRange(highest, 1, PowerupSystem.MaxActivePowerups);
    }

    [Fact]
    public void Capture_DuringDoublePoints_ScoresDouble()
    {
        GameplaySimulation normal = SimulationBuilder.Create();
        GameplaySimulation doubled = SimulationBuilder.Create();
        doubled.Session.DoublePointsRemaining = 100f;

        CaptureCompleted normalCapture = ScriptedInput.DrawRectangleFromTopWall(normal).OfType<CaptureCompleted>().Single();
        CaptureCompleted doubledCapture = ScriptedInput.DrawRectangleFromTopWall(doubled).OfType<CaptureCompleted>().Single();

        Assert.Equal(normalCapture.Points * 2, doubledCapture.Points);
    }
}

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 2 and Passed: 113. The simulation spawns nothing yet, and the doubled capture scores the normal amount.

The simulation ​

The tick needs two new steps, numbered as in the order of one tick in Chapter 05. Step 1 counts down Double Points, and step 2 runs the powerups. ResolveCapture doubles the score while Double Points lasts, and EnterLevel clears the powerups and resets the spawn timer. This chapter also tidies a few comments and local names in the file. Open Source/Simulation/GameplaySimulation.cs and replace the whole file with the following. Several methods change and two move, so a whole-file replacement is clearer than a method for each:

replace-file Source/Simulation/GameplaySimulation.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Data;
using LastPerimeter.Entities;
using LastPerimeter.Input;
using LastPerimeter.Systems;

namespace LastPerimeter.Simulation;

// The headless heart of the game. It owns the session, the per-level services and
// the services that live for the whole run. It reports what happened as events.
// It never plays a sound, writes the profile, builds text or touches the screen.
public sealed class GameplaySimulation
{
    private const float MovedThresholdSquared = 0.0001f;

    private readonly GameConfig _baseConfig;
    private readonly GameSession _session;
    private readonly MovementSystem _movement = new();
    private readonly EnemySystem _enemies;
    private readonly CollisionSystem _collision = new();
    private readonly ScoringSystem _scoring = new();
    private readonly PowerupSystem _powerups;
    private readonly LivesSystem _lives = new();
    private readonly LevelProgressionSystem _levels = new();
    private readonly List<GameEvent> _events = [];
    private readonly List<Vector2> _enemyPositions = [];
    private readonly List<Enemy> _spawnedClones = [];
    private readonly List<int> _eliminated = [];
    private LevelServices _level;
    private Vector2 _lastPlayerPosition;
    private bool _fuseWarned;

    public GameplaySimulation(GameConfig baseConfig, GameSession session, Random random)
    {
        _baseConfig = baseConfig;
        _session = session;
        _enemies = new EnemySystem(random);

        // Chapter 19 gives the powerups a random stream of their own.
        _powerups = new PowerupSystem(random);
        _level = BuildLevel(session.Level);
        EnterLevel();
    }

    public SimulationState State { get; private set; }
    public GameSession Session => _session;
    public LevelServices Level => _level;

    // The events raised by the latest StartLevel or Tick call.
    public IReadOnlyList<GameEvent> Events => _events;

    // Builds a new LevelServices and resets the level state. Keeps score, lives and shields.
    public IReadOnlyList<GameEvent> StartLevel(int levelNumber)
    {
        _level = BuildLevel(levelNumber);
        EnterLevel();
        return _events;
    }

    // One frame of rules in a fixed order. Does nothing unless the state is Running.
    public IReadOnlyList<GameEvent> Tick(float deltaTime, InputState input)
    {
        _events.Clear();
        if (State != SimulationState.Running)
        {
            return _events;
        }

        Player player = _session.Player;

        // 1. Timers.
        player.IsInvulnerable = _session.RespawnGraceRemaining > 0f;
        _session.RespawnGraceRemaining = Math.Max(0f, _session.RespawnGraceRemaining - deltaTime);
        _session.FreezeEnemiesRemaining = Math.Max(0f, _session.FreezeEnemiesRemaining - deltaTime);
        _session.DoublePointsRemaining = Math.Max(0f, _session.DoublePointsRemaining - deltaTime);

        // 2. Powerups.
        UpdatePowerups(deltaTime);

        // 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.
        Direction direction = _movement.DetermineDirection(input);
        float currentSpeed = _baseConfig.PlayerSpeed * (_session.SlowDrawActive ? TrailSystem.SlowDrawSpeedFactor : 1f);

        // 5. Enemies.
        UpdateEnemies(deltaTime);

        // 6. Nothing more to do with no input and no trail.
        Trail? activeTrail = _level.Trails.ActiveTrail;
        if (direction == Direction.None && activeTrail is null)
        {
            return _events;
        }

        Vector2 intendedPosition = _movement.CalculateNextPosition(player.Position, direction, currentSpeed, deltaTime);

        if (activeTrail is not null)
        {
            TickWhileDrawing(activeTrail, direction, intendedPosition, playerMovedLastFrame, deltaTime, input);
        }
        else
        {
            TickOnWall(direction, intendedPosition, currentSpeed, deltaTime, input);
        }

        return _events;
    }

    private LevelServices BuildLevel(int levelNumber)
    {
        LevelDefinition definition = _levels.CreateLevel(levelNumber, _session.Difficulty);
        _session.Level = levelNumber;
        _session.CurrentLevelDefinition = definition;
        return LevelServices.Create(_baseConfig, definition);
    }

    private void EnterLevel()
    {
        Player player = _session.Player;
        PlayableWallPath path = _level.Walls.RebuildPlayablePath(_level.Arena);
        _session.PlayableWallPath = path;
        _session.CaptureHistory.Clear();
        _session.Powerups.Clear();
        _powerups.ResetForLevel();
        _session.ClaimedAreaPercentage = _level.Arena.GetClaimedPercentage();
        _session.FreezeEnemiesRemaining = 0f;
        _session.DoublePointsRemaining = 0f;
        _fuseWarned = false;

        player.Position = SelectStartNode(path);
        player.CurrentDirection = Direction.None;
        player.CurrentTrail = null;
        player.IsInvulnerable = false;
        _session.RespawnGraceRemaining = 0f;
        _session.Enemies.Clear();
        _session.Enemies.AddRange(_enemies.CreateRoster(_level.Definition, _level.Arena.Bounds, _level.Config.EnemySpeed));

        State = SimulationState.Running;
        _events.Clear();
        _events.Add(new LevelStarted(_session.Level));
    }

    // The top-left node: the lowest X, then the lowest Y.
    private static Vector2 SelectStartNode(PlayableWallPath path)
    {
        IReadOnlyList<Vector2> nodes = path.Nodes;
        Vector2 start = nodes[0];
        for (int index = 1; index < nodes.Count; index++)
        {
            Vector2 node = nodes[index];
            if (node.X < start.X || (node.X == start.X && node.Y < start.Y))
            {
                start = node;
            }
        }

        return start;
    }

    private void UpdatePowerups(float deltaTime)
    {
        _powerups.UpdateSpawnTimer(deltaTime);
        _powerups.UpdatePowerups(_session.Powerups, deltaTime);
        if (_powerups.CanSpawn && _session.Powerups.Count < PowerupSystem.MaxActivePowerups)
        {
            _session.Powerups.Add(_powerups.Spawn(_session.PlayableWallPath));
        }

        Powerup? collected = _powerups.TryCollect(_session.Powerups, _session.Player.Position, _session.Player.Radius);
        if (collected is null)
        {
            return;
        }

        PowerupEffects.Apply(collected.Type, _session, _level.Fuse);
        if (collected.Type == PowerupType.FuseReset)
        {
            _fuseWarned = false;
        }

        _events.Add(new PowerupCollected(collected.Type));
    }

    private void UpdateEnemies(float deltaTime)
    {
        bool frozen = _session.FreezeEnemiesRemaining > 0f;
        Vector2? pressureTarget = _level.Trails.HasActiveTrail ? _session.Player.Position : null;
        _spawnedClones.Clear();
        for (int index = _session.Enemies.Count - 1; index >= 0; index--)
        {
            Enemy enemy = _session.Enemies[index];
            bool alive = _enemies.Update(enemy, _level.Arena, deltaTime, _level.Config.EnemyRetargetIntervalSeconds, pressureTarget, speedMultiplier: 1f, frozen: frozen);
            if (!alive)
            {
                _session.Enemies.RemoveAt(index);
                continue;
            }

            Enemy? clone = _enemies.TrySpawnSplitterClone(enemy, deltaTime, frozen);
            if (clone is not null)
            {
                _spawnedClones.Add(clone);
            }
        }

        _session.Enemies.AddRange(_spawnedClones);
    }

    private void TickWhileDrawing(Trail activeTrail, Direction direction, Vector2 intendedPosition, bool playerMovedLastFrame, float deltaTime, InputState input)
    {
        Player player = _session.Player;
        TrailSystem trails = _level.Trails;

        // 8a. Fuse.
        bool killedByFuse = _level.Fuse.Update(activeTrail, playerMovedLastFrame, deltaTime);
        if (_level.Fuse.IsWarning && !_fuseWarned)
        {
            _events.Add(new FuseWarning());
            _fuseWarned = true;
        }

        if (killedByFuse)
        {
            ResolveHit();
            return;
        }

        // 8b. Enemy contact, unless the player is invulnerable.
        if (!player.IsInvulnerable && IsPlayerOrTrailHit(player, activeTrail))
        {
            ResolveHit();
            return;
        }

        if (trails.CanCompleteOnPath(intendedPosition, _session.PlayableWallPath))
        {
            // 8c. Reconnect to the wall.
            ResolveCapture(_session.PlayableWallPath.Snap(intendedPosition), snappedToPath: true);
        }
        else if (trails.TryGetSelfIntersection(intendedPosition, out Vector2 loopIntersection))
        {
            // 8d. Cross own trail.
            ResolveCapture(loopIntersection, snappedToPath: false);
        }
        else if (trails.CanAdvance(intendedPosition, _level.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;
        }
    }

    private bool IsPlayerOrTrailHit(Player player, Trail activeTrail)
    {
        for (int index = 0; index < _session.Enemies.Count; index++)
        {
            Enemy enemy = _session.Enemies[index];
            if (_collision.IsPlayerHitByEnemy(player, enemy, true) || _collision.IsTrailHitByEnemy(activeTrail, enemy))
            {
                return true;
            }
        }

        return false;
    }

    private void TickOnWall(Direction direction, Vector2 intendedPosition, float currentSpeed, float deltaTime, InputState input)
    {
        Player player = _session.Player;

        // 9a. Put out the fuse.
        _level.Fuse.Reset();
        _fuseWarned = false;

        // 9b. Move along the wall.
        if (_movement.TryMoveAlongPath(_session.PlayableWallPath, player.Position, direction, currentSpeed, deltaTime, out Vector2 nextOnPath))
        {
            player.Position = nextOnPath;
            player.CurrentDirection = direction;
            return;
        }

        // 9c. Otherwise try to start a trail.
        if (_session.RespawnGraceRemaining <= 0f
            && _session.PlayableWallPath.Contains(player.Position)
            && _level.Arena.IsUnclaimedWorld(intendedPosition)
            && _level.Trails.TryStart(_session.PlayableWallPath.Snap(player.Position), intendedPosition, input.IsSlowDrawHeld))
        {
            player.Position = intendedPosition;
            player.CurrentTrail = _level.Trails.ActiveTrail;
            player.CurrentDirection = direction;
            _events.Add(new TrailStarted(_session.SlowDrawActive));
        }
    }

    private void ResolveHit()
    {
        HitOutcome outcome = _lives.ResolveHit(_session, _level);
        _fuseWarned = false;
        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;
        }
    }

    private void ResolveCapture(Vector2 endPoint, bool snappedToPath)
    {
        LevelServices level = _level;
        Player player = _session.Player;

        // 1. Complete the trail and put out the fuse.
        Trail completedTrail = level.Trails.Complete(endPoint);
        player.Position = endPoint;
        player.CurrentTrail = null;
        level.Fuse.Reset();
        _fuseWarned = false;

        // 2. Ask the solver, passing the enemy positions.
        _enemyPositions.Clear();
        for (int index = 0; index < _session.Enemies.Count; index++)
        {
            _enemyPositions.Add(_session.Enemies[index].Position);
        }

        ClaimResult? claimResult = level.Claims.ProcessCompletedTrail(completedTrail, _enemyPositions);

        // 3. Nothing enclosed. A loop endpoint can sit mid-arena, so return the
        // player to the wall anchor where the trail began.
        if (claimResult is null)
        {
            if (!snappedToPath)
            {
                player.Position = completedTrail.Points[0];
            }

            _events.Add(new CaptureRejected());
            return;
        }

        // 4 and 5. Apply the result and update the percentage.
        level.Arena.ApplyClaimResult(claimResult, completedTrail.IsSlowDraw);
        _session.ClaimedAreaPercentage = level.Arena.GetClaimedPercentage();

        // 6. Score the region and trail tiles, doubled while Double Points lasts.
        float totalScoreMultiplier = _session.DoublePointsRemaining > 0f ? 2f : 1f;
        int tiles = claimResult.CapturedRegion.TileCount + claimResult.TrailTiles.Count;
        int points = _scoring.ScoreClaim(tiles, completedTrail.IsSlowDraw, totalScoreMultiplier);
        _session.Score += points;

        // 7. History.
        _session.CaptureHistory.Add(new CapturedZone(_session.CaptureHistory.Count + 1, claimResult.CapturedRegion.Tiles, completedTrail.IsSlowDraw));

        // 8. Rebuild the wall path and snap the player onto it.
        _session.PlayableWallPath = level.Walls.RebuildPlayablePath(level.Arena);
        player.Position = _session.PlayableWallPath.Snap(player.Position);

        // 9. Remove eliminated enemies, highest index first.
        int eliminatedCount = RemoveEliminatedEnemies(claimResult.EliminatedEnemyIndexes);

        // 10. Report the capture.
        _events.Add(new CaptureCompleted(tiles, points, completedTrail.IsSlowDraw, !snappedToPath, eliminatedCount));

        // 11. Clear the level when the target is reached.
        if (_session.ClaimedAreaPercentage >= level.Config.WinClaimPercentage)
        {
            int bonus = _scoring.CalculateLevelBonus(_session.Level) + _scoring.CalculateThresholdBonus(_session.ClaimedAreaPercentage, level.Config.WinClaimPercentage);
            _session.Score += bonus;
            State = SimulationState.LevelCleared;
            _events.Add(new LevelCleared(bonus));
        }
    }

    private int RemoveEliminatedEnemies(IReadOnlyList<int>? eliminatedIndexes)
    {
        if (eliminatedIndexes is null || eliminatedIndexes.Count == 0)
        {
            return 0;
        }

        _eliminated.Clear();
        for (int index = 0; index < eliminatedIndexes.Count; index++)
        {
            _eliminated.Add(eliminatedIndexes[index]);
        }

        _eliminated.Sort();
        int removed = 0;
        for (int index = _eliminated.Count - 1; index >= 0; index--)
        {
            int enemyIndex = _eliminated[index];
            if (enemyIndex >= 0 && enemyIndex < _session.Enemies.Count)
            {
                _session.Enemies.RemoveAt(enemyIndex);
                removed++;
            }
        }

        return removed;
    }
}

The key changes are:

  • _powerups is a new field, created in the constructor with the same Random as the enemies. A comment notes that Chapter 19 gives it a stream of its own.
  • In Tick, step 1 counts down DoublePointsRemaining, and step 2 calls UpdatePowerups.
  • UpdatePowerups counts the spawn timer, expires powerups, spawns one when CanSpawn is true and fewer than 2 exist, and then tries to collect one.
  • A collected powerup goes through PowerupEffects.Apply. A Fuse Reset also clears the warned flag, so the next burn can warn again.
  • In ResolveCapture, stage 6 passes totalScoreMultiplier to ScoreClaim, which is 2 while Double Points runs and 1 otherwise.
  • EnterLevel clears Powerups, calls ResetForLevel and sets DoublePointsRemaining to 0, so a new level starts clean.
  • The frozen flag in step 5 is not new. It has been there since Chapter 10.
  • The remaining edits are cosmetic: shorter comments, a local trails and level, and BuildLevel, EnterLevel and SelectStartNode moved above UpdateEnemies.

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

Drawing the powerups ​

In the Source/Rendering folder, create a new file named PowerupRenderer.cs and add the following code. One method draws each powerup as a filled circle, and one method holds the colour for each type:

new-file Source/Rendering/PowerupRenderer.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Data;
using LastPerimeter.Entities;

namespace LastPerimeter.Rendering;

public sealed class PowerupRenderer
{
    public void Draw(SpriteBatch spriteBatch, Texture2D pixel, IReadOnlyList<Powerup> powerups)
    {
        for (int index = 0; index < powerups.Count; index++)
        {
            Powerup powerup = powerups[index];
            PrimitiveDrawing.DrawFilledCircle(spriteBatch, pixel, powerup.Position, powerup.Radius, ColorFor(powerup.Type));
        }
    }

    // One colour per powerup type.
    public static Color ColorFor(PowerupType type)
    {
        return type switch
        {
            PowerupType.Shield => Color.Gold,
            PowerupType.Freeze => Color.LightBlue,
            PowerupType.ExtraLife => Color.LimeGreen,
            PowerupType.FuseReset => Color.OrangeRed,
            PowerupType.DoublePoints => Color.Gold,
            _ => Color.White,
        };
    }
}

The key things to note are:

  • ColorFor is a switch expression with one colour for each type. New to switch expressions? See the C# primer. Shield and Double Points are both gold, so the status line and the HUD tell them apart.
  • The renderer reads the powerups and changes nothing.

Open Source/Rendering/HudRenderer.cs. In the Draw method, find this line:

find Source/Rendering/HudRenderer.cs
csharp
        if (!string.IsNullOrWhiteSpace(statusMessage))

Replace it with the following lines. The new block draws DOUBLE PTS in gold while the timer runs, and the last line is the one you found:

csharp
        if (session.DoublePointsRemaining > 0f)
        {
            _textRenderer.DrawString(spriteBatch, pixel, "DOUBLE PTS", new Vector2(config.ArenaMargin + 420, config.ScreenHeight - 64), Color.Gold, scale);
        }

        if (!string.IsNullOrWhiteSpace(statusMessage))

Open Source/Scenes/GameplayScene.cs. Add the following field to the GameplayScene class, below the _enemyRenderer field:

add-member Source/Scenes/GameplayScene.cs after=_enemyRenderer
csharp
    private readonly PowerupRenderer _powerupRenderer = new();

In the Draw method, find this line:

find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
            session.SlowDrawActive ? 5f : 3f);

Add the following line directly below it. The powerups are drawn after the trail, so the trail never hides one:

csharp
        _powerupRenderer.Draw(spriteBatch, _services.Pixel, session.Powerups);

In the React method, find this line:

find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
            case LevelCleared cleared:

Add the following lines directly above it. The new case plays a tone for a collected powerup:

csharp
            case PowerupCollected:
                _services.Audio.PlayPowerup();
                break;

Running the tests ​

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 115. The 115 are the 102 from earlier chapters and 13 new results. Eight are single tests, and 5 are the rows of one theory.

TestProves
ResetForLevel_RestoresTheFirstSpawnDelayPWR-02
Spawn_RearmsTimerBetweenSevenAndElevenSecondsPWR-03
Spawn_UsesWallNodesForPlacementPWR-04
Spawn_WithSameSeed_PicksSameTypeAndNodePWR-04
UpdatePowerups_RemovesExpiredPowerupsPWR-05
TryCollect_RemovesPowerupWhenPlayerIsInRangePWR-06
Apply_EachTypeChangesOnlyItsOwnState (5 rows)PWR-07, FUS-06
Tick_NeverSpawnsAThirdPowerupPWR-01
Capture_DuringDoublePoints_ScoresDoubleSCO-04

ENM-10 was proved in Chapter 10. Here it only becomes reachable, because Freeze now sets the timer in play.

Running the game ​

From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen. Stand still for about 6 seconds. A coloured dot appears on a corner of the wall, as in Figure 15-1. Walk the wall to it with the arrow keys. A tone plays and the status line names the powerup.

The dots, the tones and the DOUBLE PTS label need a window and speakers. The test counts confirm the spawn, collection and effect rules without either.

Collect a light blue dot to see the enemies stop for 2 seconds. Collect a gold dot and capture an area to see the score rise twice as fast. DOUBLE PTS appears at the bottom while it lasts. Leave one alone for 8 seconds, and it vanishes. At most two are on the wall at once.

The smoke run from Chapter 13: Proving the Level still applies. From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK -- --smoke-test-seconds 3 and check that the exit code is 0. The scene change in this chapter keeps the capture count and the seed from Chapter 14, so the scripted capture still completes.

TIP

Open Source/Systems/PowerupSystem.cs and change FirstSpawnDelaySeconds from 6f to 1f. Powerups then appear almost at once, which helps you try each type. Change it back to 6f and run dotnet test before you go on.

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 15 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/15-Powerups"
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/15-Powerups"
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: 115.

Common mistakes ​

  • A NotImplementedException in the final test run. A stub is still in PowerupSystem.cs or PowerupEffects.cs. Search the file for throw new NotImplementedException(); and replace that method.
  • Tick_NeverSpawnsAThirdPowerup fails with a highest count of 0. UpdatePowerups in the simulation never ran, or CanSpawn never became true. Check that Tick calls UpdatePowerups in step 2.
  • A powerup appears on the first frame of every level. EnterLevel does not call _powerups.ResetForLevel().
  • The Fuse Reset row fails. Apply handles FuseReset with the wrong member. It must call fuse.Reset().
  • No tone plays when you collect a powerup. The PowerupCollected case is missing from React in GameplayScene.cs.

Conclusion ​

In this chapter, you accomplished the following:

The tests now prove PWR-01 to PWR-07, SCO-04 and FUS-06, and Freeze is reachable in play. In the next chapter, Chapter 16: Profiles, Settings and Saving, you save the player's progress and settings to disk.

Test Your Knowledge ​

  1. Why does a new level reset the spawn timer?

    Answer

    The powerup service lives for the whole run. Without ResetForLevel, a timer left over from the last level could spawn a powerup on the first frame of the next one.

  2. What does "changes only its own state" mean for Freeze, and why test it?

    Answer

    Freeze sets the freeze timer and nothing else. The test checks every other field on each row. It would catch an effect that leaked into, say, the lives.

  3. When would you replace the switch in PowerupEffects with a class for each powerup?

    Answer

    When effects need their own state or behaviour over time, beyond one field. With five one-line effects, one method with five cases is clearer.

  4. Why do powerups spawn on wall nodes and not anywhere in the arena?

    Answer

    The wall is safe ground, so taking the pickup costs nothing. The risk is the walk to it. A node is also always reachable, because every node lies on the wall path.

Extensions ​

  • Add a sixth type to PowerupType and a case in Apply. Which test do you extend first, and which spawn code needs no change?
  • Change MaxActivePowerups to 1 and run the tests. Which test fails, and why does its range need a matching change?