Skip to content

Chapter 12: Events, Score and Feedback ​

In Chapter 11: Lives, Shields and Respawn, you gave the player lives and made a hit cost one. The simulation raises an event for each of these moments, but nothing yet listens. A capture, a lost life and a burning fuse all pass in silence, and the only title text is a white bar.

In this chapter, you make the game talk back. Captures score points, every event gets a sound or a line of text, and a heads-up display shows the run at a glance. Two of these changes are rules, so they touch the simulation. The rest only react to events, so they touch no rule at all.

Figure 12-1: The chapter 12 window after a capture, with the HUD, a claimed area and the status line
Figure 12-1: The chapter 12 window after a capture, with the HUD, a claimed area and the status line. This is a drawn illustration, not a screenshot.

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

In this chapter, you will:

  • Build ScoringSystem and add scoring to the capture.
  • Raise a FuseWarning event once per stop, not once per frame.
  • Synthesise six tones into SoundEffect objects, and fall back to silence when there is no audio device.
  • Draw text with a bitmap font made of pixel rectangles.
  • Build the HUD from the session and the fuse state.
  • Map every event to a sound, a status line or both, in one place.

Requirements in this chapter ​

IDShort name
SCO-01 to SCO-03Points per tile, slow draw, run multiplier
FUS-08One warning per stop
HUD-01 to HUD-04The HUD, its flags, the status line, the font
REN-04Window title only on change
AUD-01 to AUD-03Six tones, silent fallback, volume
PLT-03No content files (sound)

Why score matters ​

Until now the only reward for a capture is a bigger blue area. Score gives the player a number to beat. It rewards risk, because a trail drawn slowly is worth double but leaves the player exposed for longer. It also gives a reason to play again, because a better run is a higher number.

Score is a rule, so it belongs in the simulation. The simulation adds the points to the session at the moment of the capture and reports them in the CaptureCompleted event. Nothing outside the simulation does any arithmetic on score.

One place for feedback ​

A sound or a line of text is not a rule. The player is hit whether or not a tone plays. If the simulation played the tone, a test of the hit rule would need an audio device, and the rules would no longer run without a window.

Chapter 05 solved this with events. The simulation returns a list of GameEvent values from each Tick. It never plays a sound, builds text or writes a file. The scene reads the list and decides what each event means. In this chapter the decision lives in one method, GameplayScene.React, which has a switch over the event types. Text for the status line comes from a second place, StatusText.For, a pure function with no screen or sound in it, so a test can check it.

Figure 12-2: Events flow from the simulation to the scene, which plays a tone, sets a status line or changes scene. The dashed arrow is added in Chapter 16.

The payoff is that this chapter touches the simulation twice and for rules only. Scoring changes the capture. The fuse warning changes what Tick reports. Sound, text and the HUD are added to the scene, the services and the host. The rules do not change for any of them.

Raising a warning once ​

The fuse already knows when it is warning. FuseSystem.IsWarning is true for every frame from one second after the player stops until the fuse starts to burn. If the scene played a tone whenever IsWarning was true, it would replay the tone every frame, which is about sixty times a second.

An event means "this just happened". So the simulation keeps one bool, _fuseWarned. When the fuse is warning and the flag is false, it raises FuseWarning and sets the flag. The flag is cleared whenever the fuse is put out, the player loses a life or a capture ends the trail. The next stop then warns again.

Synthesising a tone ​

A sound effect is a block of numbers that the audio device plays back as air pressure. A tone is the simplest one. It is a sine wave, which rises and falls smoothly at a fixed frequency, measured in hertz, meaning cycles per second. The game never loads an audio file, so the course needs no content pipeline for sound.

The code builds each tone sample by sample. The sample rate is 44,100 samples per second. A tone of 0.10 seconds therefore has 4,410 samples. Sample number i happens at time i / 44100 seconds, and its value is sin(2 * pi * frequency * time). The sine gives a number from -1 to 1, which is scaled to the range of a 16-bit whole number and by a per-tone volume.

A 16-bit sample takes two bytes. MonoGame wants the low byte first, then the high byte. The loop therefore writes sample & 0xFF and then (sample >> 8) & 0xFF. The finished byte array becomes a mono SoundEffect. Each cue has its own frequency, length and volume.

CueUsed forFrequencyLength
Claima capture880 Hz0.10 s
Warningthe fuse warning440 Hz0.08 s
Deatha lost life180 Hz0.25 s
Menua menu move, from Chapter 17660 Hz0.06 s
Powerupa powerup, from Chapter 15990 Hz0.15 s
Level completea cleared level, from Chapter 14520 Hz0.25 s

Failing soft ​

A machine may have no audio device, for example a build server or a virtual machine. Creating a SoundEffect there throws NoAudioHardwareException. A game that crashed for this reason could never run in a continuous integration job. So the constructor catches the exception and sets all six cues to null. It also sets IsSilent to true. A play operation does nothing for a null cue.

To test this without owning a machine that has no sound, the constructor has a second form. It takes a function that makes the tones. The test passes a function that throws, which simulates the missing device. The public constructor passes the real tone builder.

A bitmap font ​

MonoGame normally draws text from a sprite font, a file that the content pipeline compiles. This course has no content files, so the font is data in the code. Each character is a grid of 5 columns and 7 rows. A row is a string such as 01110, and each 1 is a lit pixel. Figure 12-3 shows the letter A.

To draw a character, the renderer loops over the rows and columns. For each 1 it draws one rectangle of scale by scale pixels from the single white pixel texture. At scale 2, a glyph is 10 by 14 pixels. The cursor then moves right by 6 * scale, which leaves a one pixel gap between glyphs.

The table holds only upper case letters, digits and a few signs. The renderer upper-cases each character as it draws it. Calling ToUpperInvariant on the whole string would allocate a new string every call, and the HUD draws about fifteen strings a frame. Upper-casing one char allocates nothing.

Figure 12-3: A 5 by 7 glyph becomes scale by scale rectangles drawn from the pixel texture
Figure 12-3: A 5 by 7 glyph becomes scale by scale rectangles drawn from the pixel texture

HUD layout ​

The HUD is the text and shapes that report the run. It fits in the two reserved bands from Chapter 03: The Service Pattern and the Arena. The top 72 pixels hold the claim bar, score, best score, level, claim and goal, and a dot for each life. The bottom 44 pixels hold the flags and the status line. Figure 12-4 shows every element and where it sits.

The high score shows 0 for now. Chapter 16 loads it from the player profile. The HighScore property exists in this chapter only because the HUD needs something to read.

Figure 12-4: Where each HUD element sits in the top and bottom reserves
Figure 12-4: Where each HUD element sits in the top and bottom reserves

Setting up the data ​

Three small data changes come first, because the later code refers to them. The first is the claim percentage a player needs to win a level, which the HUD shows as the goal. The second is the best score. The third is the new event type.

Open Source/Data/GameConfig.cs. Add the following property to the GameConfig class, below the FuseBurnSpeed property:

add-member Source/Data/GameConfig.cs after=FuseBurnSpeed
csharp
    public float WinClaimPercentage { get; init; } = 75f;

Open Source/Data/GameSession.cs. Add the following property to the GameSession class, below the Score property:

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

Open Source/Simulation/GameEvent.cs. Add the following record below the SlowDrawLost record:

add-type Source/Simulation/GameEvent.cs after=SlowDrawLost
csharp
public sealed record FuseWarning : GameEvent;

Building the scoring service ​

ScoringSystem turns a number of claimed tiles into points. It holds no state, so it needs no constructor and no dependency. This is the smallest service in the course. Its two constants are the rules of the game, so they have names and live in one place.

ScoringSystem.ScoreClaim(claimedTileCount, slowDrawActive, runMultiplier) : int

  • Takes: the tiles claimed, whether the trail was drawn slowly, and a run multiplier that defaults to 1.
  • Gives: the points, as a whole number.
  • Promises: 10 points per tile, doubled for slow draw, multiplied by the run multiplier, then rounded.
  • Refuses: nothing. Zero tiles score zero.
  • Requirements: SCO-01, SCO-02, SCO-03.

In the Source/Systems folder, create a new file named ScoringSystem.cs and add the following code. The two constants are written in full. The body of ScoreClaim throws, so the project compiles and the tests can fail for the right reason.

new-file Source/Systems/ScoringSystem.cs
csharp
namespace LastPerimeter.Systems;

public sealed class ScoringSystem
{
    private const int PointsPerTile = 10;
    private const float SlowDrawScoreMultiplier = 2f;

    public int ScoreClaim(int claimedTileCount, bool slowDrawActive = false, float runMultiplier = 1f)
    {
        throw new NotImplementedException();
    }
}

In the Tests/Systems folder, create a new file named ScoringSystemTests.cs and add the following code. The first test checks 12 tiles at the base rate. The second combines slow draw with a multiplier of 1.25, so 12 tiles give 12 x 10 x 2 x 1.25, which is 300.

new-file Tests/Systems/ScoringSystemTests.cs
csharp
using LastPerimeter.Systems;

namespace LastPerimeter.Tests.Systems;

public sealed class ScoringSystemTests
{
    [Fact]
    public void ScoreClaim_UsesTileCount()
    {
        ScoringSystem scoringSystem = new();

        Assert.Equal(120, scoringSystem.ScoreClaim(12));
    }

    [Fact]
    public void ScoreClaim_AppliesSlowDrawAndRunMultipliers()
    {
        ScoringSystem scoringSystem = new();

        Assert.Equal(300, scoringSystem.ScoreClaim(12, slowDrawActive: true, runMultiplier: 1.25f));
    }
}

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 2 and Passed: 74. The 74 passes are the tests from earlier chapters. The two failures are your new tests, which hit the stub.

Open Source/Systems/ScoringSystem.cs, find the ScoreClaim method and replace the whole method with the following:

replace-method Source/Systems/ScoringSystem.cs ScoreClaim
csharp
    public int ScoreClaim(int claimedTileCount, bool slowDrawActive = false, float runMultiplier = 1f)
    {
        float multiplier = slowDrawActive ? SlowDrawScoreMultiplier : 1f;
        return (int)MathF.Round(claimedTileCount * PointsPerTile * multiplier * runMultiplier);
    }

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

The key things to note are:

  • The slow draw multiplier is chosen first, as 2 or 1. The three factors are then multiplied together in one expression.
  • MathF.Round rounds the result to the nearest whole number. A multiplier such as 1.25 can give a fraction, and a score must be whole.
  • Every number is a named constant, PointsPerTile and SlowDrawScoreMultiplier. A balance change is then one edit in one place.
  • The run multiplier has a default of 1. Chapter 18 passes a larger value when the player takes the Double Down upgrade, and Chapter 14 adds two level bonuses to this class.

Raising the fuse warning ​

GameplaySimulation.Tick now raises FuseWarning once per stop. The card below describes the promise. The warning is the first event that the simulation raises for a state it only watches. The fuse, not the player, decides when it starts.

GameplaySimulation.Tick(deltaTime, input) : IReadOnlyList<GameEvent> (changed)

  • Takes: the frame time and the input, as before.
  • Gives: the events of this frame, as before.
  • Promises: one FuseWarning is raised when the fuse starts warning. No further one is raised until the fuse has been put out, reset or has cost a life.
  • Refuses: nothing new.
  • Requirements: FUS-08.

Open Tests/Simulation/FuseScenarioTests.cs. Find the Tick_HoldingBlockedDirection_LetsFuseBurn test and replace the whole method with the following. It now collects the events, and it asserts that exactly one of them is a FuseWarning. Holding a blocked key for 45 frames lasts 2.25 seconds, long enough to warn and burn.

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

        // Up is a reversal, so the player cannot move and the fuse keeps burning.
        List<GameEvent> events = ScriptedInput.Run(sim, ScriptedInput.Up, 45);

        Assert.Equal(before, sim.Session.Player.Position);
        Assert.True(sim.Fuse.IsActive);
        Assert.Single(events.OfType<FuseWarning>());
    }

Add the following test to the FuseScenarioTests class, below the Tick_HoldingBlockedDirection_LetsFuseBurn test. It leaves the wall, stops, and waits 35 frames, which is 1.75 seconds. That is past the warning at 1 second and before the fuse at 2 seconds. Exactly one warning must appear.

add-member Tests/Simulation/FuseScenarioTests.cs at=end
csharp
    [Fact]
    public void Tick_RaisesFuseWarningOnce()
    {
        GameplaySimulation sim = SimulationBuilder.Create();
        ScriptedInput.Run(sim, ScriptedInput.Right, 4);
        ScriptedInput.Run(sim, ScriptedInput.Down, 3);

        List<GameEvent> events = ScriptedInput.Run(sim, ScriptedInput.Idle, 35);

        Assert.Single(events.OfType<FuseWarning>());
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 2 and Passed: 75. Both fuse tests fail, because nothing raises the event.

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

add-member Source/Simulation/GameplaySimulation.cs after=_lastPlayerPosition
csharp
    private bool _fuseWarned;

In the same file, the TickWhileDrawing method must raise the warning once. In step 8a, find this line:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
        bool killedByFuse = _fuse.Update(activeTrail, playerMovedLastFrame, deltaTime);

Add the following lines directly after it:

csharp
        if (_fuse.IsWarning && !_fuseWarned)
        {
            _events.Add(new FuseWarning());
            _fuseWarned = true;
        }

In the TickOnWall method, step 9a must also clear the flag. Find these lines:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
        // 9a. Put out the fuse.
        _fuse.Reset();

Add the following line directly after them:

csharp
        _fuseWarned = false;

In the ResolveHit method, the flag must be cleared too. Find this line:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
        HitOutcome outcome = _lives.ResolveHit(_session, _trails, _fuse, _baseConfig.RespawnGraceSeconds);

Add the following line directly after it:

csharp
        _fuseWarned = false;

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

The key changes are:

  • In TickWhileDrawing, step 8a raises FuseWarning when _fuse.IsWarning is true and _fuseWarned is false, then sets the flag.
  • In TickOnWall, step 9a clears the flag when it puts the fuse out. A player who reaches the wall and leaves again warns again.
  • In ResolveHit, the flag is cleared. A life lost to the fuse resets the fuse, so the next trail starts fresh.

Scoring a capture ​

Scoring happens in ResolveCapture, at step 6, after the arena has been updated and before the history is written. The capture's tile count is the region plus the trail tiles, which is the count CaptureCompleted already carried. The new code moves the sum above the scoring so both use it. The event, which carried a zero for Points, now carries the real value.

GameplaySimulation.ResolveCapture(endPoint, snappedToPath) (changed)

  • Takes: the end point of a completed trail, as before.
  • Gives: nothing. The session and the event list change.
  • Promises: the session score rises by ScoreClaim of the region and trail tiles. CaptureCompleted.Points carries the same value.
  • Refuses: a rejected capture scores nothing, because it returns before step 6.
  • Requirements: SCO-01.

Open Tests/Simulation/CaptureScenarioTests.cs. Add the following test to the CaptureScenarioTests class, at the end. It draws the standard rectangle, then checks that the points are ten per tile and that the session holds the same total.

add-member Tests/Simulation/CaptureScenarioTests.cs at=end
csharp
    [Fact]
    public void Capture_ScoresRegionAndTrailTiles()
    {
        GameplaySimulation sim = SimulationBuilder.Create();

        CaptureCompleted capture = ScriptedInput.DrawRectangleFromTopWall(sim).OfType<CaptureCompleted>().Single();

        Assert.True(capture.Tiles > 0);
        Assert.Equal(capture.Tiles * 10, capture.Points);
        Assert.Equal(capture.Points, sim.Session.Score);
        Assert.False(capture.WasLoop);
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 77. The capture still reports zero points.

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 ScoringSystem _scoring = new();

In the same file, the ResolveCapture method scores the capture. The step numbers are explained in the order of one tick. Make four edits. First, find the comment above the method:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
    // Turns a completed trail into territory. Scoring arrives in chapter 12 and the
    // level check in chapter 14.

Replace it with:

csharp
    // Turns a completed trail into territory. The level check arrives in chapter 14.

Second, find these lines in step 1 and the start of step 2:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
        _fuse.Reset();

        // 2. Ask the solver, passing the enemy positions.

Replace them with:

csharp
        _fuse.Reset();
        _fuseWarned = false;

        // 2. Ask the solver, passing the enemy positions.

Third, find this comment line, the start of step 7:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
        // 7. History.

Replace it with the following. Step 6 is new, and the last line is the comment you found:

csharp
        // 6. Score the region and trail tiles.
        int tiles = claimResult.CapturedRegion.TileCount + claimResult.TrailTiles.Count;
        int points = _scoring.ScoreClaim(tiles, completedTrail.IsSlowDraw);
        _session.Score += points;

        // 7. History.

Fourth, find these lines in step 10:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
        // 10. Report the capture. Points are zero until chapter 12.
        int tiles = claimResult.CapturedRegion.TileCount + claimResult.TrailTiles.Count;
        _events.Add(new CaptureCompleted(tiles, 0, completedTrail.IsSlowDraw, !snappedToPath, eliminatedCount));

Replace them with:

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

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

The key changes are:

  • A new _scoring field holds the stateless ScoringSystem.
  • Step 6 sums the region and trail tiles, asks ScoreClaim for the points and adds them to _session.Score.
  • completedTrail.IsSlowDraw is passed as the slow draw flag, so a slow trail scores double.
  • Step 10 reuses the same tiles and points values for the event, so the score on the session and the score in the event cannot disagree.
  • ResolveCapture also clears _fuseWarned, because a finished trail ends the stop.

Building the audio service ​

The rules half of the chapter is finished: the scoring service, the fuse warning event and the score in a capture. Before you start on sound and text, run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 78. If it does not, fix that first, because the rest of the chapter only adds presentation.

AudioCuePlayer owns the six tones. It is the first service that touches the outside world, so it is also the first that can fail for a reason the player cannot fix. The cards describe the three promises of this chapter.

AudioCuePlayer constructor

  • Takes: nothing. A second, internal form takes a function that makes a tone.
  • Gives: a player with six synthesised tones.
  • Promises: each tone is built from a frequency, a length and a volume, with no file.
  • Refuses: with no audio device the constructor does not throw. It sets IsSilent and keeps the six cues as null.
  • Requirements: AUD-01, AUD-02, PLT-03.

AudioCuePlayer.Configure(audioEnabled, masterVolume) : void

  • Takes: whether audio is on, and a master volume.
  • Gives: nothing. The player changes.
  • Promises: the volume is clamped to 0 to 1, and MasterVolume reports the clamped value.
  • Refuses: nothing. A volume of 2 becomes 1, and a volume of -0.5 becomes 0.
  • Requirements: AUD-03.

AudioCuePlayer.PlayClaim() and the other five Play operations

  • Takes: nothing.
  • Gives: nothing. A tone plays.
  • Promises: the tone plays at the master volume.
  • Refuses: nothing plays when the player is silent, when audio is off or when the volume is 0.
  • Requirements: AUD-01, AUD-02, AUD-03.

In the Source/Systems folder, create a new file named AudioCuePlayer.cs and add the following code. This stub is nearly the whole class. The two constructors, the Configure method, CreateTone and the private Play method are the parts that throw. The six public Play operations are one line each, and they call Play with their own cue. After you add the file, dotnet build may report warnings that some fields are never assigned. The warnings go away when you write the constructor.

new-file Source/Systems/AudioCuePlayer.cs
csharp
using Microsoft.Xna.Framework.Audio;

namespace LastPerimeter.Systems;

public sealed class AudioCuePlayer : IDisposable
{
    private readonly SoundEffect? _claim;
    private readonly SoundEffect? _warning;
    private readonly SoundEffect? _death;
    private readonly SoundEffect? _menu;
    private readonly SoundEffect? _powerup;
    private readonly SoundEffect? _levelComplete;
    private bool _audioEnabled = true;
    private float _masterVolume = 1f;

    public AudioCuePlayer()
        : this(CreateTone)
    {
    }

    // The factory lets a test simulate a machine with no audio device.
    internal AudioCuePlayer(Func<float, float, float, SoundEffect> toneFactory)
    {
        throw new NotImplementedException();
    }

    public bool IsSilent { get; }

    public float MasterVolume => _masterVolume;

    public void Configure(bool audioEnabled, float masterVolume)
    {
        throw new NotImplementedException();
    }

    public void PlayClaim() => Play(_claim);
    public void PlayWarning() => Play(_warning);
    public void PlayDeath() => Play(_death);
    public void PlayMenuSelect() => Play(_menu);
    public void PlayPowerup() => Play(_powerup);
    public void PlayLevelComplete() => Play(_levelComplete);

    public void Dispose()
    {
        _claim?.Dispose();
        _warning?.Dispose();
        _death?.Dispose();
        _menu?.Dispose();
        _powerup?.Dispose();
        _levelComplete?.Dispose();
    }

    private static SoundEffect CreateTone(float frequency, float durationSeconds, float volume)
    {
        throw new NotImplementedException();
    }

    private void Play(SoundEffect? soundEffect)
    {
        throw new NotImplementedException();
    }
}

In the Tests/Systems folder, create a new file named AudioCuePlayerTests.cs and add the following code. Both tests build a player whose tone factory throws NoAudioHardwareException, which is what a machine without a sound device does. The first test checks the silent fallback and calls all six Play operations and Dispose. The second checks the clamp at both ends and in the middle.

new-file Tests/Systems/AudioCuePlayerTests.cs
csharp
using Microsoft.Xna.Framework.Audio;
using LastPerimeter.Systems;

namespace LastPerimeter.Tests.Systems;

public sealed class AudioCuePlayerTests
{
    [Fact]
    public void Constructor_WithNoAudioDevice_RunsSilentAndPlayDoesNothing()
    {
        AudioCuePlayer player = new((_, _, _) => throw new NoAudioHardwareException("No audio hardware."));

        Assert.True(player.IsSilent);
        player.PlayClaim();
        player.PlayWarning();
        player.PlayDeath();
        player.PlayMenuSelect();
        player.PlayPowerup();
        player.PlayLevelComplete();
        player.Dispose();
    }

    [Fact]
    public void Configure_ClampsMasterVolume()
    {
        AudioCuePlayer player = new((_, _, _) => throw new NoAudioHardwareException("No audio hardware."));

        player.Configure(true, 2f);
        Assert.Equal(1f, player.MasterVolume);

        player.Configure(true, -0.5f);
        Assert.Equal(0f, player.MasterVolume);

        player.Configure(true, 0.4f);
        Assert.Equal(0.4f, player.MasterVolume, precision: 3);
    }
}

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

Now write the bodies. Open Source/Systems/AudioCuePlayer.cs. Find the constructor that takes toneFactory, the one marked internal, and replace the whole constructor with the following:

replace-method Source/Systems/AudioCuePlayer.cs AudioCuePlayer AudioCuePlayer(Func
csharp
    // The factory lets a test simulate a machine with no audio device.
    internal AudioCuePlayer(Func<float, float, float, SoundEffect> toneFactory)
    {
        try
        {
            _claim = toneFactory(880f, 0.10f, 0.20f);
            _warning = toneFactory(440f, 0.08f, 0.15f);
            _death = toneFactory(180f, 0.25f, 0.35f);
            _menu = toneFactory(660f, 0.06f, 0.16f);
            _powerup = toneFactory(990f, 0.15f, 0.18f);
            _levelComplete = toneFactory(520f, 0.25f, 0.2f);
        }
        catch (Exception exception) when (exception is NoAudioHardwareException or DllNotFoundException)
        {
            // No audio device (or no native audio library): run silent so the game still starts.
            _claim = null;
            _warning = null;
            _death = null;
            _menu = null;
            _powerup = null;
            _levelComplete = null;
            IsSilent = true;
        }
    }

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

replace-method Source/Systems/AudioCuePlayer.cs Configure
csharp
    public void Configure(bool audioEnabled, float masterVolume)
    {
        _audioEnabled = audioEnabled;
        _masterVolume = Math.Clamp(masterVolume, 0f, 1f);
    }

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

replace-method Source/Systems/AudioCuePlayer.cs CreateTone
csharp
    private static SoundEffect CreateTone(float frequency, float durationSeconds, float volume)
    {
        const int sampleRate = 44100;
        int samples = (int)(sampleRate * durationSeconds);
        byte[] buffer = new byte[samples * 2];

        for (int i = 0; i < samples; i++)
        {
            double time = i / (double)sampleRate;
            short sample = (short)(Math.Sin(2d * Math.PI * frequency * time) * short.MaxValue * volume);
            buffer[i * 2] = (byte)(sample & 0xFF);
            buffer[(i * 2) + 1] = (byte)((sample >> 8) & 0xFF);
        }

        return new SoundEffect(buffer, sampleRate, AudioChannels.Mono);
    }

Find the private Play method and replace the whole method with the following:

replace-method Source/Systems/AudioCuePlayer.cs Play Play(SoundEffect
csharp
    private void Play(SoundEffect? soundEffect)
    {
        if (soundEffect is null || !_audioEnabled || _masterVolume <= 0f)
        {
            return;
        }

        soundEffect.Play(_masterVolume, 0f, 0f);
    }

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

The key things to note are:

  • The public constructor passes CreateTone to the internal one. The real game and the test run the same constructor body, and only the tone builder differs.
  • The catch names two exception types. NoAudioHardwareException is MonoGame's report of no device. DllNotFoundException covers a machine where the native audio library is missing.
  • In the catch, every cue is set back to null, because a constructor that failed half way would leave some cues made and some not.
  • CreateTone writes the low byte then the high byte of each 16-bit sample. The last argument of the SoundEffect constructor, AudioChannels.Mono, says the buffer has one channel.
  • Play returns early for a null cue, for audio off and for a volume of 0. The three refusals on the card are one if.
  • No test plays a real tone, because a test machine may have no speakers. The tones are proved by ear in "Running the game".

Building the status text ​

StatusText.For turns an event into a line of text for the status line. Putting the strings in a pure function keeps wording out of the rules, and one test can check every event.

StatusText.For(gameEvent) : string

  • Takes: a game event.
  • Gives: the text for the status line.
  • Promises: each event that has a message gives its message. A trail gives DRAW TO CAPTURE or SLOW DRAW 2X, and a capture gives CAPTURE COMPLETE or LOOP CAPTURE.
  • Refuses: an event with no message gives an empty string, which means "leave the line as it is".
  • Requirements: HUD-03.

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

new-file Source/Scenes/StatusText.cs
csharp
using LastPerimeter.Simulation;

namespace LastPerimeter.Scenes;

public static class StatusText
{
    // The status line for an event. An empty string means the event leaves the line unchanged.
    public static string For(GameEvent gameEvent)
    {
        throw new NotImplementedException();
    }
}

In the Tests/Scenes folder, create a new file named StatusTextTests.cs and add the following code. One test walks through every event type, with both forms of the trail and the capture.

new-file Tests/Scenes/StatusTextTests.cs
csharp
using LastPerimeter.Scenes;
using LastPerimeter.Simulation;

namespace LastPerimeter.Tests.Scenes;

public sealed class StatusTextTests
{
    [Fact]
    public void StatusText_MapsEveryEventToALine()
    {
        Assert.Equal("DRAW TO CAPTURE", StatusText.For(new TrailStarted(false)));
        Assert.Equal("SLOW DRAW 2X", StatusText.For(new TrailStarted(true)));
        Assert.Equal("FAST DRAW", StatusText.For(new SlowDrawLost()));
        Assert.Equal(string.Empty, StatusText.For(new FuseWarning()));
        Assert.Equal("CAPTURE COMPLETE", StatusText.For(new CaptureCompleted(10, 100, false, false, 0)));
        Assert.Equal("LOOP CAPTURE", StatusText.For(new CaptureCompleted(10, 100, false, true, 0)));
        Assert.Equal("NO CAPTURE", StatusText.For(new CaptureRejected()));
        Assert.Equal("SHIELD BLOCK", StatusText.For(new ShieldBlocked()));
        Assert.Equal("RESPAWN", StatusText.For(new LifeLost(2)));
        Assert.Equal(string.Empty, StatusText.For(new RunLost()));
    }
}

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

Open Source/Scenes/StatusText.cs, find the For method and replace the whole method with the following:

replace-method Source/Scenes/StatusText.cs For
csharp
    // The status line for an event. An empty string means the event leaves the line unchanged.
    public static string For(GameEvent gameEvent)
    {
        return gameEvent switch
        {
            TrailStarted trail => trail.SlowDraw ? "SLOW DRAW 2X" : "DRAW TO CAPTURE",
            SlowDrawLost => "FAST DRAW",
            FuseWarning => string.Empty,
            CaptureCompleted capture => capture.WasLoop ? "LOOP CAPTURE" : "CAPTURE COMPLETE",
            CaptureRejected => "NO CAPTURE",
            ShieldBlocked => "SHIELD BLOCK",
            LifeLost => "RESPAWN",
            RunLost => string.Empty,
            _ => string.Empty,
        };
    }

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

The key things to note are:

  • The switch expression has one arm per event type. The final _ arm is the fallback, so a new event type that has no message does not break the build.
  • FuseWarning and RunLost return an empty string on purpose. The warning has its own HUD label and tone, and a lost run changes scene.
  • The test checks the wording only. The rules that raise each event are tested in the chapters that built them.

Drawing text and the HUD ​

The font and the HUD have no tests, because what they produce is pixels. Each renderer is a few lines of arithmetic, and "Running the game" checks the result by eye against Figure 12-1 and Figure 12-4. The glyph table and the tone builder are likewise checked by eye and by ear, not by a test. The extensions at the end of the chapter suggest two tests you can add.

In the Source/Rendering folder, create a new file named BitmapTextRenderer.cs and add the following code. The Glyphs table is long and regular. Type each row carefully, because one wrong digit draws a wrong pixel.

new-file Source/Rendering/BitmapTextRenderer.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace LastPerimeter.Rendering;

public sealed class BitmapTextRenderer
{
    private static readonly Dictionary<char, string[]> Glyphs = new()
    {
        ['A'] = new[] { "01110", "10001", "10001", "11111", "10001", "10001", "10001" },
        ['B'] = new[] { "11110", "10001", "10001", "11110", "10001", "10001", "11110" },
        ['C'] = new[] { "01111", "10000", "10000", "10000", "10000", "10000", "01111" },
        ['D'] = new[] { "11110", "10001", "10001", "10001", "10001", "10001", "11110" },
        ['E'] = new[] { "11111", "10000", "10000", "11110", "10000", "10000", "11111" },
        ['F'] = new[] { "11111", "10000", "10000", "11110", "10000", "10000", "10000" },
        ['G'] = new[] { "01111", "10000", "10000", "10011", "10001", "10001", "01110" },
        ['H'] = new[] { "10001", "10001", "10001", "11111", "10001", "10001", "10001" },
        ['I'] = new[] { "11111", "00100", "00100", "00100", "00100", "00100", "11111" },
        ['J'] = new[] { "00001", "00001", "00001", "00001", "10001", "10001", "01110" },
        ['K'] = new[] { "10001", "10010", "10100", "11000", "10100", "10010", "10001" },
        ['L'] = new[] { "10000", "10000", "10000", "10000", "10000", "10000", "11111" },
        ['M'] = new[] { "10001", "11011", "10101", "10101", "10001", "10001", "10001" },
        ['N'] = new[] { "10001", "11001", "10101", "10011", "10001", "10001", "10001" },
        ['O'] = new[] { "01110", "10001", "10001", "10001", "10001", "10001", "01110" },
        ['P'] = new[] { "11110", "10001", "10001", "11110", "10000", "10000", "10000" },
        ['Q'] = new[] { "01110", "10001", "10001", "10001", "10101", "10010", "01101" },
        ['R'] = new[] { "11110", "10001", "10001", "11110", "10100", "10010", "10001" },
        ['S'] = new[] { "01111", "10000", "10000", "01110", "00001", "00001", "11110" },
        ['T'] = new[] { "11111", "00100", "00100", "00100", "00100", "00100", "00100" },
        ['U'] = new[] { "10001", "10001", "10001", "10001", "10001", "10001", "01110" },
        ['V'] = new[] { "10001", "10001", "10001", "10001", "10001", "01010", "00100" },
        ['W'] = new[] { "10001", "10001", "10001", "10101", "10101", "10101", "01010" },
        ['X'] = new[] { "10001", "10001", "01010", "00100", "01010", "10001", "10001" },
        ['Y'] = new[] { "10001", "10001", "01010", "00100", "00100", "00100", "00100" },
        ['Z'] = new[] { "11111", "00001", "00010", "00100", "01000", "10000", "11111" },
        ['0'] = new[] { "01110", "10001", "10011", "10101", "11001", "10001", "01110" },
        ['1'] = new[] { "00100", "01100", "00100", "00100", "00100", "00100", "01110" },
        ['2'] = new[] { "01110", "10001", "00001", "00010", "00100", "01000", "11111" },
        ['3'] = new[] { "11110", "00001", "00001", "00110", "00001", "00001", "11110" },
        ['4'] = new[] { "00010", "00110", "01010", "10010", "11111", "00010", "00010" },
        ['5'] = new[] { "11111", "10000", "10000", "11110", "00001", "00001", "11110" },
        ['6'] = new[] { "01110", "10000", "10000", "11110", "10001", "10001", "01110" },
        ['7'] = new[] { "11111", "00001", "00010", "00100", "01000", "01000", "01000" },
        ['8'] = new[] { "01110", "10001", "10001", "01110", "10001", "10001", "01110" },
        ['9'] = new[] { "01110", "10001", "10001", "01111", "00001", "00001", "01110" },
        [':'] = new[] { "00000", "00100", "00100", "00000", "00100", "00100", "00000" },
        ['%'] = new[] { "11001", "11010", "00100", "01000", "10110", "00110", "00000" },
        ['.'] = new[] { "00000", "00000", "00000", "00000", "00000", "00110", "00110" },
        ['!'] = new[] { "00100", "00100", "00100", "00100", "00100", "00000", "00100" },
        ['-'] = new[] { "00000", "00000", "00000", "11111", "00000", "00000", "00000" },
        ['/'] = new[] { "00001", "00010", "00100", "01000", "10000", "00000", "00000" },
        [' '] = new[] { "00000", "00000", "00000", "00000", "00000", "00000", "00000" },
    };

    public void DrawString(SpriteBatch spriteBatch, Texture2D pixel, string text, Vector2 position, Color color, int scale = 2)
    {
        Vector2 cursor = position;
        // Upper-case one character at a time: text.ToUpperInvariant() would
        // allocate a new string on every call, many times per frame.
        foreach (char rawCharacter in text)
        {
            if (!Glyphs.TryGetValue(char.ToUpperInvariant(rawCharacter), out string[]? glyph))
            {
                cursor.X += 6 * scale;
                continue;
            }

            for (int row = 0; row < glyph.Length; row++)
            {
                string line = glyph[row];
                for (int column = 0; column < line.Length; column++)
                {
                    if (line[column] != '1')
                    {
                        continue;
                    }

                    spriteBatch.Draw(pixel, new Rectangle((int)cursor.X + (column * scale), (int)cursor.Y + (row * scale), scale, scale), color);
                }
            }

            cursor.X += 6 * scale;
        }
    }

    public Vector2 MeasureString(string text, int scale = 2)
    {
        return new Vector2(text.Length * 6 * scale, 7 * scale);
    }
}

The key things to note are:

  • Glyphs is static readonly, so the table is built once, and each lookup is a dictionary read.
  • DrawString takes the SpriteBatch and the white pixel as arguments. The renderer owns no graphics resource, so it needs no Dispose.
  • An unknown character skips ahead by one cell and draws nothing, so the text keeps its spacing.
  • MeasureString returns the size without drawing. The title scene uses it to centre text.

In the Source/Rendering folder, create a new file named HudRenderer.cs and add the following code. It reads the session and draws each element at the position shown in Figure 12-4.

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

namespace LastPerimeter.Rendering;

public sealed class HudRenderer
{
    private readonly BitmapTextRenderer _textRenderer;

    public HudRenderer(BitmapTextRenderer textRenderer)
    {
        _textRenderer = textRenderer;
    }

    // The high score shows 0 until chapter 16 loads it from the profile.
    public void Draw(SpriteBatch spriteBatch, Texture2D pixel, GameSession session, GameConfig config, string statusMessage, bool fuseWarning, bool fuseActive)
    {
        const int scale = 2;
        Rectangle barBackground = new(config.ArenaMargin, 16, 220, 12);
        spriteBatch.Draw(pixel, barBackground, Color.DarkSlateGray);

        int filledWidth = (int)(barBackground.Width * MathHelper.Clamp(session.ClaimedAreaPercentage / 100f, 0f, 1f));
        if (filledWidth > 0)
        {
            spriteBatch.Draw(pixel, new Rectangle(barBackground.X, barBackground.Y, filledWidth, barBackground.Height), Color.RoyalBlue);
        }

        for (int index = 0; index < session.Player.Lives; index++)
        {
            Vector2 center = new(config.ScreenWidth - config.ArenaMargin - 12 - (index * 18), 22);
            PrimitiveDrawing.DrawFilledCircle(spriteBatch, pixel, center, 5f, Color.Cyan);
        }

        _textRenderer.DrawString(spriteBatch, pixel, $"SCORE:{session.Score}", new Vector2(config.ArenaMargin, 34), Color.White, scale);
        _textRenderer.DrawString(spriteBatch, pixel, $"HI:{session.HighScore}", new Vector2(config.ArenaMargin + 220, 34), Color.Gold, scale);
        _textRenderer.DrawString(spriteBatch, pixel, $"LEVEL:{session.Level}", new Vector2(config.ArenaMargin + 420, 34), Color.White, scale);
        _textRenderer.DrawString(spriteBatch, pixel, $"CLAIM:{session.ClaimedAreaPercentage:0}%", new Vector2(config.ArenaMargin, 52), Color.White, scale);
        _textRenderer.DrawString(spriteBatch, pixel, $"GOAL:{config.WinClaimPercentage:0}%", new Vector2(config.ArenaMargin + 220, 52), Color.Gold, scale);
        _textRenderer.DrawString(spriteBatch, pixel, "LIVES", new Vector2(config.ScreenWidth - config.ArenaMargin - 70, 34), Color.White, scale);

        if (fuseWarning)
        {
            _textRenderer.DrawString(spriteBatch, pixel, fuseActive ? "FUSE" : "WARN", new Vector2(config.ScreenWidth / 2f - 24, 16), fuseActive ? Color.Red : Color.Orange, scale);
        }

        if (session.RespawnGraceRemaining > 0f)
        {
            _textRenderer.DrawString(spriteBatch, pixel, "SAFE", new Vector2((config.ScreenWidth / 2f) - 24f, 34f), Color.Cyan, scale);
        }

        if (session.SlowDrawActive)
        {
            _textRenderer.DrawString(spriteBatch, pixel, "SLOW DRAW 2X", new Vector2(config.ArenaMargin, config.ScreenHeight - 64), Color.Orange, scale);
        }

        if (session.ShieldCharges > 0)
        {
            _textRenderer.DrawString(spriteBatch, pixel, $"SHIELD:{session.ShieldCharges}", new Vector2(config.ArenaMargin + 220, config.ScreenHeight - 64), Color.Gold, scale);
        }

        if (!string.IsNullOrWhiteSpace(statusMessage))
        {
            _textRenderer.DrawString(spriteBatch, pixel, statusMessage, new Vector2(config.ArenaMargin, config.ScreenHeight - 36), Color.LightGray, scale);
        }
    }
}

The key things to note are:

  • Draw receives the fuse state as two booleans, fuseWarning and fuseActive. The HUD does not know what a fuse is. It shows WARN when only the first is true, and FUSE when the second is true too.
  • The claim bar is the claimed percentage turned into a width, clamped to the bar. A value above 100 cannot overflow.
  • PrimitiveDrawing.DrawFilledCircle draws one cyan dot for each life from the pixel texture. The dots start at the right edge and step left by 18 pixels.
  • Labels for shields and slow draw appear only while that state is active. The shield label has nothing to show until Chapter 15 adds powerups.

Wiring it into the game ​

Four files change. GameServices gains the text renderer, the audio player and the window title action. The host passes the action in. The title scene draws real text. The gameplay scene reacts to events and draws the HUD.

The services and the host ​

In Source/Game/GameServices.cs, add the following lines at the top of the file, below the other using lines:

add-using Source/Game/GameServices.cs
csharp
using LastPerimeter.Rendering;
using LastPerimeter.Systems;

The GameServices constructor must take an Action<string> that sets the window title, so the gameplay scene can set the title without holding the Game object. Find the constructor signature in Source/Game/GameServices.cs:

find Source/Game/GameServices.cs
csharp
    public GameServices(GameConfig config, GraphicsDevice graphicsDevice)

Replace it with:

csharp
    public GameServices(GameConfig config, GraphicsDevice graphicsDevice, Action<string> setWindowTitle)

Find this line in the constructor:

find Source/Game/GameServices.cs
csharp
        Input = new InputManager();

Add the following lines directly after it:

csharp
        Text = new BitmapTextRenderer();
        Audio = new AudioCuePlayer();
        SetWindowTitle = setWindowTitle;

Add the following property to the GameServices class, below the Input property:

add-member Source/Game/GameServices.cs after=Input
csharp
    public BitmapTextRenderer Text { get; }

Add the following property below the Text property:

add-member Source/Game/GameServices.cs after=Text
csharp
    public AudioCuePlayer Audio { get; }

Add the following property below the Audio property:

add-member Source/Game/GameServices.cs after=Audio
csharp
    public Action<string> SetWindowTitle { get; }

The audio player owns sound effects, which are native resources, so Dispose must release it. Find the start of the Dispose method:

find Source/Game/GameServices.cs
csharp
    public void Dispose()
    {

Add the following line directly after it:

csharp
        Audio.Dispose();

Open Source/Game/LastPerimeterApp.cs. The host must pass the lambda title => Window.Title = title. The host owns Window, so it is the only place that can set the title. In the LastPerimeterApp constructor, find this line:

find Source/Game/LastPerimeterApp.cs
csharp
        _services = new Lazy<GameServices>(() => new GameServices(_config, GraphicsDevice));

Replace it with:

csharp
        _services = new Lazy<GameServices>(() => new GameServices(_config, GraphicsDevice, title => Window.Title = title));

The key changes are:

  • GameServices has three new members: Text, Audio and SetWindowTitle.
  • The constructor builds BitmapTextRenderer and AudioCuePlayer in the same step as the rest, so there is never a half-built set.
  • Dispose releases Audio first.
  • The host's Lazy<GameServices> factory now passes a third argument. LoadContent is unchanged.

The title scene ​

In Source/Scenes/TitleScene.cs, find the Draw method and replace the whole method with the following. The old method drew a white bar where the title will be. The new one draws two lines of text.

replace-method Source/Scenes/TitleScene.cs Draw
csharp
    public override void Draw(SpriteBatch spriteBatch)
    {
        DrawCentered(spriteBatch, "LAST PERIMETER", 160, 4, Color.White);
        DrawCentered(spriteBatch, "PRESS ENTER", 280, 2, Color.LightGray);
    }

Add the following method to the TitleScene class, below the Draw method. It measures the text and puts it in the middle of the screen.

add-member Source/Scenes/TitleScene.cs after=Draw
csharp
    private void DrawCentered(SpriteBatch spriteBatch, string text, int y, int scale, Color color)
    {
        Vector2 size = _services.Text.MeasureString(text, scale);
        _services.Text.DrawString(spriteBatch, _services.Pixel, text, new Vector2((_services.Config.ScreenWidth - size.X) / 2f, y), color, scale);
    }

The gameplay scene ​

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 HudRenderer _hudRenderer;

Add the following field below the _claimedArea field. It holds the text on the status line.

add-member Source/Scenes/GameplayScene.cs after=_claimedArea
csharp
    private string _status = string.Empty;

Add the following field below the _status field. It remembers the values that the window title last showed. The type is a tuple, which groups four values, and it is nullable so that the first frame always sets the title. New to tuples? See the C# primer.

add-member Source/Scenes/GameplayScene.cs after=_status
csharp
    private (int Score, int Lives, int Level, float Claim)? _shownTitleValues;

In the GameplayScene constructor, the HUD renderer is built from the shared text renderer. Find this line:

find Source/Scenes/GameplayScene.cs
csharp
        _services = services;

Add the following line directly after it:

csharp
        _hudRenderer = new HudRenderer(services.Text);

In the Enter method, the scene must set the first window title. Find this line:

find Source/Scenes/GameplayScene.cs
csharp
        _simulation.StartLevel();

Add the following line directly after it:

csharp
        UpdateWindowTitle();

Find the Update method and replace the whole method with the following. The old method tested for two event types inline. The new one passes every event to React.

replace-method Source/Scenes/GameplayScene.cs Update
csharp
    public override void Update(float deltaTime, InputState input)
    {
        IReadOnlyList<GameEvent> events = _simulation.Tick(deltaTime, input);
        for (int index = 0; index < events.Count; index++)
        {
            React(events[index]);
        }

        UpdateWindowTitle();
    }

In the Draw method, the HUD is drawn on top of everything else. Find this line:

find Source/Scenes/GameplayScene.cs
csharp
        _playerRenderer.Draw(spriteBatch, _services.Pixel, session.Player, Color.Cyan);

Add the following line directly after it:

csharp
        _hudRenderer.Draw(spriteBatch, _services.Pixel, session, _services.Config, _status, _simulation.Fuse.IsWarning || _simulation.Fuse.IsActive, _simulation.Fuse.IsActive);

Add the following method to the GameplayScene class, below the Draw method. This is the one place that decides what each event means. It sets the status line from StatusText, then a switch plays the tone or changes scene.

add-member Source/Scenes/GameplayScene.cs after=Draw
csharp
    // One place that decides what each event means: a status line, a tone or another scene.
    private void React(GameEvent gameEvent)
    {
        string text = StatusText.For(gameEvent);
        if (text.Length > 0)
        {
            _status = text;
        }

        switch (gameEvent)
        {
            case FuseWarning:
                _services.Audio.PlayWarning();
                break;
            case CaptureCompleted:
                _claimedArea?.MarkDirty();
                _services.Audio.PlayClaim();
                break;
            case LifeLost:
                _services.Audio.PlayDeath();
                break;
            case RunLost:
                // Chapter 18 shows a run summary here instead.
                Scenes.Change(new TitleScene(_services));
                break;
        }
    }

Add the following method below the React method. Setting the window title is a call into the operating system, and building the text allocates a string. The method therefore compares the four values with the last ones shown and does nothing when they match.

add-member Source/Scenes/GameplayScene.cs after=React
csharp
    private void UpdateWindowTitle()
    {
        GameSession session = _simulation.Session;

        // Setting the window title is a native call and the text costs an allocation,
        // so only rebuild it when one of the shown values has changed.
        (int Score, int Lives, int Level, float Claim) values = (session.Score, session.Player.Lives, session.Level, session.ClaimedAreaPercentage);
        if (values == _shownTitleValues)
        {
            return;
        }

        _shownTitleValues = values;
        _services.SetWindowTitle($"Last Perimeter | Score {session.Score} | Lives {session.Player.Lives} | Level {session.Level} | Claim {session.ClaimedAreaPercentage:0.0}%");
    }

The key changes are:

  • Update hands every event to React and then calls UpdateWindowTitle. The scene no longer needs to know which events matter.
  • React first asks StatusText.For for a line, and keeps the old line when the answer is empty.
  • The switch plays the warning tone for FuseWarning, the claim tone and a redraw for CaptureCompleted, and the death tone for LifeLost. RunLost still returns to the title scene.
  • UpdateWindowTitle compares a tuple of four values with the previous tuple. On an idle frame the tuples are equal, so no string is built and no native call is made.
  • Draw passes the fuse state to the HUD as two booleans. _simulation.Fuse.IsWarning || _simulation.Fuse.IsActive is the "warning" flag, because a burning fuse is also past its warning.

Look at what did not change. The wall, trail, fuse, capture, enemy and lives services were not edited. The only rule changes in this chapter are the score and the warning event, both in GameplaySimulation. Sound, text and the HUD were added without touching a rule.

Running the tests ​

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

TestProves
ScoreClaim_UsesTileCountSCO-01
ScoreClaim_AppliesSlowDrawAndRunMultipliersSCO-02, SCO-03
Capture_ScoresRegionAndTrailTilesSCO-01 in the simulation
Tick_RaisesFuseWarningOnceFUS-08
Constructor_WithNoAudioDevice_RunsSilentAndPlayDoesNothingAUD-02
Configure_ClampsMasterVolumeAUD-03
StatusText_MapsEveryEventToALineHUD-03

The other requirements in this chapter are about what you see and hear. The next section checks HUD-01, HUD-02, HUD-04, REN-04, AUD-01 and PLT-03.

Running the game ​

From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. The title now shows LAST PERIMETER in large white letters, with PRESS ENTER below it. Press Enter. The window title bar reads Last Perimeter | Score 0 | Lives 3 | Level 1 | Claim 0.0%, and the HUD appears. Check each part in turn.

  1. The HUD. The top band shows a claim bar that is empty, SCORE:0, HI:0, LEVEL:1, CLAIM:0% and GOAL:75%, with three cyan dots at the right (HUD-01). HI stays 0 until Chapter 16.
  2. A capture. Hold the Right arrow for a moment to walk along the top wall, then release. Hold Down to leave the wall, then Right, then Up back to the wall. A short high tone plays (AUD-01). The score jumps, the claim bar grows, the status line at the bottom says CAPTURE COMPLETE, and the title bar shows the new score (REN-04).
  3. Slow draw. Start a second trail while you hold Space. SLOW DRAW 2X shows at the bottom left, and a capture scores double (HUD-02).
  4. The fuse. Leave the wall, then release every key. After one second a lower tone plays once and WARN appears at the top. After a second more the label changes to FUSE and the fuse burns along the trail towards you. When it arrives, a deep tone plays, the status line says RESPAWN and a life dot disappears (AUD-01, FUS-08).
  5. Safe time. Just after a respawn, SAFE shows at the top while the grace time lasts (HUD-02).
  6. No files. The Content/Assets folder has no new file, so every sound came from code (PLT-03).

TIP

To see the lower case rule, change the string "PRESS ENTER" in TitleScene.Draw to "press enter". It still draws in capitals, because DrawString upper-cases each character (HUD-04). Change it back afterwards.

The test counts prove the scoring, the events and the status wording. Checks 1 to 5 need a window, and checks 2 and 4 also need speakers or headphones. Close the window with its close button. The next section is optional. It replaces your files with the chapter 12 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 12 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/12-Events-Score-And-Feedback"
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/12-Events-Score-And-Feedback"
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: 81.

Common mistakes ​

  • The fuse tone plays every frame, or the test finds many warnings. _fuseWarned is never set, or it is cleared inside TickWhileDrawing. Only TickOnWall, ResolveHit and ResolveCapture clear it.
  • The capture score is zero. ResolveCapture still passes 0 to CaptureCompleted, or step 6 is missing. Check that you replaced the whole method.
  • The game crashes at start with NoAudioHardwareException. The catch in the internal constructor lists the wrong exception type, or the public constructor does not pass CreateTone.
  • Text draws as gaps or wrong shapes. A row in Glyphs has a typing error. Each row has exactly five characters, and there are seven rows per glyph.
  • The window title flickers or the game slows down. UpdateWindowTitle sets the title every frame because the tuple comparison was lost. Check the if (values == _shownTitleValues) test.
  • The build says GameServices has no constructor with three arguments. The host still calls new GameServices(_config, GraphicsDevice). Replace the constructor in LastPerimeterApp.

Conclusion ​

In this chapter, you accomplished the following:

The tests now prove SCO-01 to SCO-03, FUS-08, HUD-03, AUD-02 and AUD-03, and the run proves HUD-01, HUD-02, HUD-04, REN-04, AUD-01 and PLT-03. In the next chapter, Chapter 13: Proving the Level, you write scenario tests that play whole sequences, and you time the capture solver.

Test Your Knowledge ​

  1. Which files changed to add sound, and which did not?

    Answer

    GameplayScene, GameServices and the host changed, and the audio and text classes are new. No rule changed for sound, because the simulation already reported the events. The simulation changed only for scoring and the fuse warning, which are rules.

  2. Why does the simulation raise FuseWarning once instead of on every frame that the fuse warns?

    Answer

    An event means "this just happened". One per frame would replay the tone about sixty times a second. The _fuseWarned flag turns a state that lasts into a single event.

  3. Why does BitmapTextRenderer upper-case characters one at a time instead of calling ToUpperInvariant on the whole string?

    Answer

    The string call allocates a new string every time it runs, and the HUD draws about fifteen strings a frame. Upper-casing a single char allocates nothing.

  4. Why does AudioCuePlayer have a second constructor that takes a function?

    Answer

    A test can pass a function that throws NoAudioHardwareException. That simulates a machine with no sound device, so the silent fallback is tested on any machine.

Extensions ​

  • Add a seventh cue with a new frequency and a PlayX operation. Decide which event should play it, and add the case to GameplayScene.React.
  • Add a test that calls Configure(false, 1f) on a player built from a working tone factory and proves nothing plays. What does the test need to observe?
  • Add a data test for the glyph table. Check that every glyph has 7 rows of 5 characters each.
  • Add a buffer-size test for CreateTone. For a short tone, check that the sample buffer holds the expected number of bytes.
  • Change the points per tile to 5 and run dotnet test. Which tests fail, and which of the two numbers in each one needs to change?