Skip to content

Chapter 17: Menus and the Front End ​

In Chapter 16: Profiles, Settings and Saving, you made the game remember. The game still starts a run the moment you press Enter on the title screen, and it has no way to pause, change a setting or pick a level.

In this chapter, you build the front end: a main menu, a pause menu, an options screen, a level select screen and a five page tutorial. The decisions live in small classes that a test can drive. The scenes only pass input to those classes and draw the result.

Figure 17-1: The chapter 17 main menu, with five items and the first one selected
Figure 17-1: The chapter 17 main menu, with five items and the first one selected. This is a drawn illustration, not a screenshot.

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

In this chapter, you will:

  • Add Push and Pop to the scene manager, and draw overlay scenes on top of the scene below.
  • Build MenuList, the one selection model that every menu uses.
  • Keep decisions in models and drawing in scenes, so menus can be tested without a window.
  • Pause the game with an overlay, and make sure the pause key is not seen twice.
  • Build the options, level select and tutorial screens, and draw them all with MenuRenderer.

Requirements in this chapter ​

IDShort name
FE-01Title screen, then the main menu
FE-02The main menu items
FE-03Menus wrap and play a cue on each move
FE-04Pause is an overlay over the frozen game
FE-05Options return to the scene that opened them
FE-06Level select stops at the highest unlocked level
FE-07The tutorial, five pages
INP-05The pause press is consumed

A stack of scenes ​

Until now the scene manager held one scene at a time. A pause menu needs two. The game must stay on screen, frozen, with the menu drawn on top. When the player resumes, the game must carry on exactly where it was, so it cannot be thrown away and rebuilt.

A stack solves this. The manager keeps a list of scenes and treats the last one as the top. Push puts a new scene on top. Pop removes the top scene and uncovers the one below. Change still replaces the whole stack with one scene, which is how the game moves from the main menu to a run.

Only the top scene gets Update, so the scene underneath is frozen. Drawing is different. A scene that sets IsOverlay to true is drawn on top of the scene below it. The manager finds the highest scene that is not an overlay, and draws from there up to the top. Pause, level complete and the options screen opened from pause are overlays.

Figure 17-2 shows every scene and the moves between them. Look at the options screen. It has two arrows back, one to the pause menu and one to the main menu. The options scene does not know which one it will take. It pops itself, and the stack returns to whichever scene opened it.

Figure 17-2: Every scene in the game and the move between them. Each move names its trigger and the manager call that makes it

One key, one action ​

The same Escape key opens the pause menu and closes it. This invites a bug. If a freshly pushed pause menu updated in the same frame, it would see the Escape press that opened it, and close itself at once.

The manager prevents this by deferring. Push, Pop and Change only add the request to a queue. The queue is applied after the top scene finishes its Update. The new scene therefore first updates on the next frame, when the key press is over. You met this idea in Chapter 05: Scenes and the Gameplay Simulation. It now guards a real case, INP-05.

Models and scenes ​

A scene needs a graphics device, because it draws. A test cannot easily make one. If a scene also holds the rules of its menu, those rules cannot be tested. The course therefore splits the work. A small model class decides: which row is selected, what a key press means, which page of the tutorial comes next. The scene gives the model the input, acts on the answer and draws the result.

This split keeps the scenes thin and the tests plain. A test creates a model, hands it an InputState and checks the answer. The scenes themselves are not under test in this chapter. You check them by running the game.

Commands, not actions ​

A menu row has a label and a command. A command is a name for what the row does, for example StartRun or Quit. The menu model never runs a command. It reports that a row was confirmed. The scene looks up the row's command in the menu's table and carries it out.

Putting the table in data has two benefits. A test can check that each row maps to the command it should, without a window. And adding a menu item later is one new row in the table and one new case in the scene.

Adding Push and Pop to the scene manager ​

The manager gets two new operations and a change to how it draws. Here are the cards.

SceneManager.Push(scene) : void

  • Takes: a scene.
  • Gives: nothing. The scene goes on top after the current Update returns.
  • Promises: the scene below stays on the stack and keeps its state. The pushed scene first updates on the next frame.
  • Refuses: nothing.
  • Requirements: FE-04, INP-05.

SceneManager.Pop() : void

  • Takes: nothing.
  • Gives: nothing. The top scene is removed and disposed after the current Update returns.
  • Promises: the scene below becomes the top and receives updates again.
  • Refuses: popping an empty stack does nothing.
  • Requirements: FE-05.

SceneManager.Draw(spriteBatch) : void

  • Takes: an open sprite batch.
  • Gives: nothing. The scenes draw.
  • Promises: drawing starts at the highest scene that is not an overlay and continues up to the top. A scene below an opaque scene is not drawn.
  • Refuses: nothing.
  • Requirements: FE-04.

Open Source/Scenes/SceneManager.cs. Add the following method to the SceneManager class, below the Change method. It throws for now, so the tests can fail first.

add-member Source/Scenes/SceneManager.cs after=Change
csharp
    // Puts an overlay on top.
    public void Push(Scene scene)
    {
        throw new NotImplementedException();
    }

Add the following method below the Push method:

add-member Source/Scenes/SceneManager.cs after=Push
csharp
    // Removes the top scene and returns to the one below.
    public void Pop()
    {
        throw new NotImplementedException();
    }

The tests need a stub scene that can be an overlay, counts its draws and can ask the manager to push or pop. Open Tests/Scenes/SceneManagerTests.cs. Add the following property to the StubScene class, below the Updates property:

add-member Tests/Scenes/SceneManagerTests.cs after=Updates type=StubScene
csharp
        public int Draws { get; private set; }

Add the following property below the Draws property:

add-member Tests/Scenes/SceneManagerTests.cs after=Draws type=StubScene
csharp
        public bool Overlay { get; init; }

Add the following property above the AllowsSaving property. It passes the Overlay value to the manager.

add-member Tests/Scenes/SceneManagerTests.cs before=AllowsSaving type=StubScene
csharp
        public override bool IsOverlay => Overlay;

In the StubScene class, find the Draw method and replace the whole method with the following. It now counts each call.

replace-method Tests/Scenes/SceneManagerTests.cs Draw type=StubScene
csharp
        public override void Draw(SpriteBatch spriteBatch)
        {
            Draws++;
        }

Add the following method below the RequestChange method:

add-member Tests/Scenes/SceneManagerTests.cs after=RequestChange type=StubScene
csharp
        public void RequestPush(Scene scene) => Scenes.Push(scene);

Add the following method below the RequestPush method:

add-member Tests/Scenes/SceneManagerTests.cs after=RequestPush type=StubScene
csharp
        public void RequestPop() => Scenes.Pop();

Two of the existing tests should now use Push, because they describe an overlay on top of a scene. In the same file, find the SceneManager_UpdatesOnlyTheTopScene test and replace the whole method with the following. The top scene is now pushed, and it is an overlay.

replace-method Tests/Scenes/SceneManagerTests.cs SceneManager_UpdatesOnlyTheTopScene
csharp
    [Fact]
    public void SceneManager_UpdatesOnlyTheTopScene()
    {
        StubScene bottom = new();
        StubScene top = new() { Overlay = true };
        SceneManager manager = StartWith(bottom);
        manager.Push(top);
        manager.Update(0.016f, InputState.Empty);

        manager.Update(0.016f, InputState.Empty);
        manager.Update(0.016f, InputState.Empty);

        Assert.Equal(1, bottom.Updates);
        Assert.Equal(2, top.Updates);
    }

Find the SaveHook_NeverRunsDuringGameplay test and replace the whole method with the following. The scene that follows gameplay is now a pause overlay, pushed on top.

replace-method Tests/Scenes/SceneManagerTests.cs SaveHook_NeverRunsDuringGameplay
csharp
    [Fact]
    public void SaveHook_NeverRunsDuringGameplay()
    {
        StubScene gameplay = new() { Saving = false };
        StubScene pause = new() { Overlay = true };
        SceneManager manager = StartWith(gameplay);
        Assert.False(manager.CanSave);

        manager.Push(pause);
        manager.Update(0.016f, InputState.Empty);

        Assert.True(manager.CanSave);
    }

Add the following test to the SceneManagerTests class, below the SceneManager_UpdatesOnlyTheTopScene test. It pushes an overlay and checks that both scenes draw. It then pushes an opaque scene and checks that only the top one draws.

add-member Tests/Scenes/SceneManagerTests.cs after=SceneManager_UpdatesOnlyTheTopScene
csharp
    [Fact]
    public void SceneManager_PushedOverlay_DrawsTheSceneBelow()
    {
        StubScene bottom = new();
        StubScene overlay = new() { Overlay = true };
        StubScene opaque = new();
        SceneManager manager = StartWith(bottom);
        manager.Push(overlay);
        manager.Update(0.016f, InputState.Empty);

        manager.Draw(null!);
        Assert.Equal(1, bottom.Draws);
        Assert.Equal(1, overlay.Draws);

        manager.Push(opaque);
        manager.Update(0.016f, InputState.Empty);
        manager.Draw(null!);
        Assert.Equal(1, bottom.Draws);
        Assert.Equal(1, overlay.Draws);
        Assert.Equal(1, opaque.Draws);
    }

Add the following test below the SceneManager_PushedOverlay_DrawsTheSceneBelow test. The pushed scene pops itself on its first update, and the test checks that the scene below is on top again.

add-member Tests/Scenes/SceneManagerTests.cs after=SceneManager_PushedOverlay_DrawsTheSceneBelow
csharp
    [Fact]
    public void SceneManager_Pop_ReturnsToCaller()
    {
        StubScene bottom = new();
        StubScene top = new() { Overlay = true, OnUpdate = (scene, _) => scene.RequestPop() };
        SceneManager manager = StartWith(bottom);
        manager.Push(top);
        manager.Update(0.016f, InputState.Empty);

        manager.Update(0.016f, InputState.Empty);

        Assert.Same(bottom, manager.Top);
        Assert.Equal(1, manager.Count);
    }

Add the following test below the SceneManager_Pop_ReturnsToCaller test. It sends one pause press and checks that the pause scene is on top but has not yet updated, then sends an empty input and checks that it updates once.

add-member Tests/Scenes/SceneManagerTests.cs after=SceneManager_Pop_ReturnsToCaller
csharp
    [Fact]
    public void PausePress_OpensPauseAndIsConsumed()
    {
        StubScene pause = new() { Overlay = true };
        StubScene gameplay = new() { OnUpdate = (scene, input) => { if (input.IsPausePressed) { scene.RequestPush(pause); } } };
        SceneManager manager = StartWith(gameplay);
        InputState pausePress = new() { IsPausePressed = true };

        manager.Update(0.016f, pausePress);

        Assert.Same(pause, manager.Top);
        Assert.Equal(0, pause.Updates);

        manager.Update(0.016f, InputState.Empty);
        Assert.Equal(1, pause.Updates);
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 5 and Passed: 124. Two changed tests and three new tests call Push or Pop, which still throw.

The manager needs more than two new bodies. The queue must now hold the kind of request as well as the scene. The Prepare, Draw and ApplyPending methods change, and the class comment changes with them. You therefore replace the whole file. Open Source/Scenes/SceneManager.cs and replace the whole file with the following:

replace-file Source/Scenes/SceneManager.cs
csharp
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Input;

namespace LastPerimeter.Scenes;

// A stack of scenes. Changes are queued and applied after the top scene's Update
// returns. That avoids changing the stack while it is in use, and a scene that
// was just pushed does not see the key press that pushed it.
public sealed class SceneManager : IDisposable
{
    private enum PendingKind
    {
        Change,
        Push,
        Pop,
    }

    private readonly List<Scene> _stack = [];
    private readonly List<(PendingKind Kind, Scene? Scene)> _pending = [];

    public Scene? Top => _stack.Count == 0 ? null : _stack[^1];
    public int Count => _stack.Count;

    // The top scene decides whether the profile may be written this frame.
    public bool CanSave => Top?.AllowsSaving ?? true;

    // Replaces the whole stack with one scene.
    public void Change(Scene scene)
    {
        _pending.Add((PendingKind.Change, scene));
    }

    // Puts an overlay on top.
    public void Push(Scene scene)
    {
        _pending.Add((PendingKind.Push, scene));
    }

    // Removes the top scene and returns to the one below.
    public void Pop()
    {
        _pending.Add((PendingKind.Pop, null));
    }

    // Updates only the top scene, then applies any queued change.
    public void Update(float deltaTime, InputState input)
    {
        Top?.Update(deltaTime, input);
        ApplyPending();
    }

    public void Prepare()
    {
        for (int index = FirstVisibleIndex(); index < _stack.Count; index++)
        {
            _stack[index].Prepare();
        }
    }

    // Draws from the highest non-overlay scene up to the top.
    public void Draw(SpriteBatch spriteBatch)
    {
        for (int index = FirstVisibleIndex(); index < _stack.Count; index++)
        {
            _stack[index].Draw(spriteBatch);
        }
    }

    public void Dispose()
    {
        DisposeAll();
        _pending.Clear();
    }

    private int FirstVisibleIndex()
    {
        int index = _stack.Count - 1;
        while (index > 0 && _stack[index].IsOverlay)
        {
            index--;
        }

        return Math.Max(0, index);
    }

    private void ApplyPending()
    {
        // Entering a scene may queue more changes, so the count is read each time.
        for (int index = 0; index < _pending.Count; index++)
        {
            (PendingKind kind, Scene? scene) = _pending[index];
            switch (kind)
            {
                case PendingKind.Change when scene is not null:
                    DisposeAll();
                    Add(scene);
                    break;
                case PendingKind.Push when scene is not null:
                    Add(scene);
                    break;
                case PendingKind.Pop when _stack.Count > 0:
                    _stack[^1].Dispose();
                    _stack.RemoveAt(_stack.Count - 1);
                    break;
            }
        }

        _pending.Clear();
    }

    private void Add(Scene scene)
    {
        scene.Attach(this);
        _stack.Add(scene);
        scene.Enter();
    }

    private void DisposeAll()
    {
        for (int index = _stack.Count - 1; index >= 0; index--)
        {
            _stack[index].Dispose();
        }

        _stack.Clear();
    }
}

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

The key changes are:

  • PendingKind is a private enum of Change, Push and Pop. The queue now holds a kind and a scene together, so ApplyPending knows what to do with each entry. ApplyPending reads each entry with a tuple deconstruction. New to tuples? See the C# primer.
  • Push and Pop only queue a request. This is the deferral that keeps one key press from acting twice.
  • ApplyPending handles the three kinds in a switch. A Change disposes the whole stack first. A Pop disposes only the top scene. Both Change and Push end in the new Add helper, which attaches the manager, adds the scene and calls Enter.
  • FirstVisibleIndex walks down from the top while the scene is an overlay, and stops at the first one that is not. Draw and Prepare both run from that index to the top.
  • Prepare now visits every visible scene, because a gameplay scene under an overlay may still need to rebuild its claimed-area image before the batch opens.

Building the menu models ​

The three models, MenuList, OptionsModel and TutorialModel, come before any scene that uses them. Each follows the usual rhythm. The tables of labels and commands come with them.

In a terminal, from the LastPerimeter folder, run the following two commands, one at a time:

text
mkdir Source/Scenes/Menus
mkdir Tests/Scenes/Menus

The menu enums ​

In the Source/Scenes/Menus folder, create a new file named MenuInput.cs and add the following code. A MenuInput is what a menu reports after it has looked at one frame of input.

new-file Source/Scenes/Menus/MenuInput.cs
csharp
namespace LastPerimeter.Scenes.Menus;

public enum MenuInput
{
    None,
    Moved,
    Confirmed,
    Cancelled,
}

In the same folder, create a new file named MenuCommand.cs and add the following code. It names every action any menu can ask for, in one enum.

new-file Source/Scenes/Menus/MenuCommand.cs
csharp
namespace LastPerimeter.Scenes.Menus;

public enum MenuCommand
{
    StartRun,
    LevelSelect,
    Tutorial,
    Options,
    Quit,
    Resume,
    QuitToMenu,
}

Selecting a row ​

MenuList.HandleInput(input) : MenuInput

  • Takes: the input for one frame.
  • Gives: Moved when up or down changed the selection, Confirmed for a confirm, Cancelled for a cancel, and None otherwise.
  • Promises: a menu that wraps goes from the first row to the last on up, and from the last to the first on down. A menu that does not wrap stops at the ends. SelectedIndex is always inside the list.
  • Refuses: a confirm or a cancel is reported and not acted on. An empty menu reports None.
  • Requirements: FE-03, FE-06.

The shell of MenuList is written in full, apart from the operation itself. The constructor only needs the number of items and whether the menu wraps, so it does not keep the labels. In the Source/Scenes/Menus folder, create a new file named MenuList.cs and add the following code:

new-file Source/Scenes/Menus/MenuList.cs
csharp
using LastPerimeter.Input;

namespace LastPerimeter.Scenes.Menus;

// The selection logic of a vertical menu. It reports what the input did and
// leaves acting on a confirm or a cancel to the scene.
public sealed class MenuList
{
    private readonly int _count;
    private readonly bool _wraps;

    public MenuList(IReadOnlyList<string> items, bool wraps = true)
    {
        _count = items.Count;
        _wraps = wraps;
    }

    public int SelectedIndex { get; private set; }

    public MenuInput HandleInput(InputState input)
    {
        throw new NotImplementedException();
    }
}

In the Tests/Scenes/Menus folder, create a new file named MenuTests.cs and add the following code. The up and down inputs are shared by the tests, so they are static fields. The file will hold the tests for all three models, so it has a plural name.

new-file Tests/Scenes/Menus/MenuTests.cs
csharp
using LastPerimeter.Input;
using LastPerimeter.Scenes.Menus;

namespace LastPerimeter.Tests.Scenes.Menus;

public sealed class MenuListTests
{
    private static readonly InputState Up = new() { IsMenuUpPressed = true };
    private static readonly InputState Down = new() { IsMenuDownPressed = true };

    [Fact]
    public void MenuList_WrapsAtBothEnds()
    {
        MenuList menu = new(["A", "B", "C"]);

        Assert.Equal(MenuInput.Moved, menu.HandleInput(Up));
        Assert.Equal(2, menu.SelectedIndex);
        menu.HandleInput(Down);
        Assert.Equal(0, menu.SelectedIndex);
    }
}

Open Tests/Scenes/Menus/MenuTests.cs. Add the following test to the MenuListTests class, below the MenuList_WrapsAtBothEnds test. It presses up on the first row, which a non-wrapping menu must ignore, and then presses down five times.

add-member Tests/Scenes/Menus/MenuTests.cs after=MenuList_WrapsAtBothEnds
csharp
    [Fact]
    public void MenuList_ClampsWhenNotWrapping()
    {
        MenuList menu = new(["A", "B", "C"], wraps: false);

        menu.HandleInput(Up);
        Assert.Equal(0, menu.SelectedIndex);
        for (int press = 0; press < 5; press++)
        {
            menu.HandleInput(Down);
        }

        Assert.Equal(2, menu.SelectedIndex);
    }

Add the following test below the MenuList_ClampsWhenNotWrapping test. It checks that a confirm and a cancel are reported, that an empty input gives None, and that none of them move the selection.

add-member Tests/Scenes/Menus/MenuTests.cs after=MenuList_ClampsWhenNotWrapping
csharp
    [Fact]
    public void MenuList_ReportsConfirmAndCancel()
    {
        MenuList menu = new(["A", "B"]);

        Assert.Equal(MenuInput.Confirmed, menu.HandleInput(new InputState { IsConfirmPressed = true }));
        Assert.Equal(MenuInput.Cancelled, menu.HandleInput(new InputState { IsCancelPressed = true }));
        Assert.Equal(MenuInput.None, menu.HandleInput(InputState.Empty));
        Assert.Equal(0, menu.SelectedIndex);
    }

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

Open Source/Scenes/Menus/MenuList.cs. Find the HandleInput method and replace the whole method with the following:

replace-method Source/Scenes/Menus/MenuList.cs HandleInput
csharp
    public MenuInput HandleInput(InputState input)
    {
        if (_count == 0)
        {
            return MenuInput.None;
        }

        if (input.IsMenuUpPressed)
        {
            Move(-1);
            return MenuInput.Moved;
        }

        if (input.IsMenuDownPressed)
        {
            Move(1);
            return MenuInput.Moved;
        }

        if (input.IsConfirmPressed)
        {
            return MenuInput.Confirmed;
        }

        return input.IsCancelPressed ? MenuInput.Cancelled : MenuInput.None;
    }

Add the following method to the MenuList class, below the HandleInput method. It is not used by a scene in this chapter. It moves the selection straight to a row and keeps it inside the list.

add-member Source/Scenes/Menus/MenuList.cs after=HandleInput
csharp
    public void Select(int index)
    {
        SelectedIndex = Math.Clamp(index, 0, Math.Max(0, _count - 1));
    }

Add the following private method below the Select method. It does the stepping for HandleInput.

add-member Source/Scenes/Menus/MenuList.cs after=Select
csharp
    private void Move(int step)
    {
        SelectedIndex = _wraps
            ? (SelectedIndex + step + _count) % _count
            : Math.Clamp(SelectedIndex + step, 0, _count - 1);
    }

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

The key things to note are:

  • The method checks up and down before confirm and cancel. If several arrive in one frame, a move wins.
  • For a wrapping menu, (SelectedIndex + step + _count) % _count is the wrap. Adding _count first keeps the sum positive when the step is -1 on row 0.
  • For a menu that does not wrap, Math.Clamp holds the index between 0 and the last row.
  • Nothing in the class plays a sound or changes a scene. The scene does that when it sees Moved or Confirmed.

The menu tables ​

The main menu and the pause menu each have a table of rows. A row is a label and a command. The tables are data, so you write them in full in the shell. Two helpers do work. Labels turns a table into the plain list of labels that MenuList and the renderer take. LevelLabels builds the rows of the level select screen.

MenuTables.Labels(table) : string[] takes a table of rows and gives the labels in the same order. Requirements: FE-02.

MenuTables.LevelLabels(highestUnlockedLevel) : string[] takes the highest unlocked level and gives one label per level, LEVEL 1 up to that level. Promises: there is always at least one row. A value below 1 still gives LEVEL 1. Requirements: FE-06.

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

new-file Source/Scenes/Menus/MenuTables.cs
csharp
namespace LastPerimeter.Scenes.Menus;

// Each menu is a table of labels and commands. The scene carries the command out.
public static class MenuTables
{
    public static readonly (string Label, MenuCommand Command)[] Main =
    [
        ("START RUN", MenuCommand.StartRun),
        ("LEVEL SELECT", MenuCommand.LevelSelect),
        ("TUTORIAL", MenuCommand.Tutorial),
        ("OPTIONS", MenuCommand.Options),
        ("QUIT", MenuCommand.Quit),
    ];

    public static readonly (string Label, MenuCommand Command)[] Pause =
    [
        ("RESUME", MenuCommand.Resume),
        ("OPTIONS", MenuCommand.Options),
        ("QUIT TO MENU", MenuCommand.QuitToMenu),
    ];

    public static string[] Labels((string Label, MenuCommand Command)[] table)
    {
        throw new NotImplementedException();
    }

    public static string[] LevelLabels(int highestUnlockedLevel)
    {
        throw new NotImplementedException();
    }
}

Open Tests/Scenes/Menus/MenuTests.cs. Add the following test to the MenuListTests class, below the MenuList_ReportsConfirmAndCancel test. It is a theory, one test method that runs once for each InlineData line. Each case presses down to a row, confirms, and checks which command the table gives for that row.

add-member Tests/Scenes/Menus/MenuTests.cs after=MenuList_ReportsConfirmAndCancel
csharp
    [Theory]
    [InlineData(0, MenuCommand.StartRun)]
    [InlineData(1, MenuCommand.LevelSelect)]
    [InlineData(2, MenuCommand.Tutorial)]
    [InlineData(3, MenuCommand.Options)]
    [InlineData(4, MenuCommand.Quit)]
    public void MainMenu_ConfirmOnEachItem_IssuesItsCommand(int row, MenuCommand expected)
    {
        MenuList menu = new(MenuTables.Labels(MenuTables.Main));
        for (int press = 0; press < row; press++)
        {
            menu.HandleInput(new InputState { IsMenuDownPressed = true });
        }

        MenuInput result = menu.HandleInput(new InputState { IsConfirmPressed = true });

        Assert.Equal(MenuInput.Confirmed, result);
        Assert.Equal(expected, MenuTables.Main[menu.SelectedIndex].Command);
    }

Add the following test below the MainMenu_ConfirmOnEachItem_IssuesItsCommand test. It builds the rows for three unlocked levels, presses down ten times and checks that the selection stops on the third. It also checks that a level count of 0 still gives one row.

add-member Tests/Scenes/Menus/MenuTests.cs after=MainMenu_ConfirmOnEachItem_IssuesItsCommand
csharp
    [Fact]
    public void LevelSelect_StopsAtHighestUnlockedLevel()
    {
        string[] labels = MenuTables.LevelLabels(3);
        MenuList menu = new(labels, wraps: false);

        for (int press = 0; press < 10; press++)
        {
            menu.HandleInput(Down);
        }

        Assert.Equal(["LEVEL 1", "LEVEL 2", "LEVEL 3"], labels);
        Assert.Equal(2, menu.SelectedIndex);
        Assert.Single(MenuTables.LevelLabels(0));
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 6 and Passed: 132. The theory counts as five test cases, and the level test is the sixth.

Open Source/Scenes/Menus/MenuTables.cs. Find the Labels method and replace the whole method with the following:

replace-method Source/Scenes/Menus/MenuTables.cs Labels
csharp
    public static string[] Labels((string Label, MenuCommand Command)[] table)
    {
        string[] labels = new string[table.Length];
        for (int index = 0; index < table.Length; index++)
        {
            labels[index] = table[index].Label;
        }

        return labels;
    }

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

replace-method Source/Scenes/Menus/MenuTables.cs LevelLabels
csharp
    // One row per unlocked level, and always at least level 1.
    public static string[] LevelLabels(int highestUnlockedLevel)
    {
        int count = Math.Max(1, highestUnlockedLevel);
        string[] labels = new string[count];
        for (int index = 0; index < count; index++)
        {
            labels[index] = $"LEVEL {index + 1}";
        }

        return labels;
    }

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

The key things to note are:

  • The theory has five cases for the five main menu rows, and the test names the command that each row must give. The tutorial at Chapter 19 adds a daily challenge row and a sixth case.
  • LevelLabels uses Math.Max(1, highestUnlockedLevel), so even a damaged profile gives the player a level to start.
  • The level select test also proves FE-06, because a menu built with wraps: false stops on the last unlocked level.

The options model ​

The options screen shows one row per setting, and a Back row. This chapter has two settings, difficulty and audio. Chapter 20 adds four more rows.

OptionsModel.GetLabels(settings) : string[]

  • Takes: the settings.
  • Gives: one label per row, including BACK, showing the current value.
  • Promises: the last row is BACK, at the row number BackRow.
  • Refuses: nothing.
  • Requirements: FE-05.

OptionsModel.Change(settings, row, direction) : bool

  • Takes: the settings, a row, and a direction of -1 or 1.
  • Gives: true when a setting changed.
  • Promises: the difficulty cycles through its values and wraps round. The audio row toggles.
  • Refuses: the Back row, or a direction of 0, changes nothing and gives false.
  • Requirements: FE-05.

In the Source/Scenes/Menus folder, create a new file named OptionsModel.cs and add the following code. It is a static class, because it keeps no state of its own. The settings object belongs to the profile.

new-file Source/Scenes/Menus/OptionsModel.cs
csharp
using LastPerimeter.Data;

namespace LastPerimeter.Scenes.Menus;

public static class OptionsModel
{
    public const int BackRow = 2;

    public static string[] GetLabels(GameSettings settings)
    {
        throw new NotImplementedException();
    }

    public static bool Change(GameSettings settings, int row, int direction)
    {
        throw new NotImplementedException();
    }
}

Open Tests/Scenes/Menus/MenuTests.cs. The new tests use GameSettings and DifficultyPreset. At the top of the file, add the following line above the other using lines:

add-using Tests/Scenes/Menus/MenuTests.cs before=LastPerimeter.Input
csharp
using LastPerimeter.Data;

Add the following class to the end of the file, below the MenuListTests class. It cycles the difficulty forward twice and back once, then checks the Back row.

add-type Tests/Scenes/Menus/MenuTests.cs
csharp
public sealed class OptionsModelTests
{
    [Fact]
    public void OptionsModel_Change_CyclesDifficulty()
    {
        GameSettings settings = new();

        Assert.True(OptionsModel.Change(settings, 0, 1));
        Assert.Equal(DifficultyPreset.Hardcore, settings.Difficulty);
        OptionsModel.Change(settings, 0, 1);
        Assert.Equal(DifficultyPreset.Chill, settings.Difficulty);
        OptionsModel.Change(settings, 0, -1);
        Assert.Equal(DifficultyPreset.Hardcore, settings.Difficulty);
        Assert.False(OptionsModel.Change(settings, OptionsModel.BackRow, 1));
    }
}

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

Open Source/Scenes/Menus/OptionsModel.cs. Find the GetLabels method and replace the whole method with the following:

replace-method Source/Scenes/Menus/OptionsModel.cs GetLabels
csharp
    // One label per row, including Back. Chapter 20 adds four more rows.
    public static string[] GetLabels(GameSettings settings)
    {
        return
        [
            $"DIFFICULTY {settings.Difficulty}",
            $"AUDIO {(settings.AudioEnabled ? "ON" : "OFF")}",
            "BACK",
        ];
    }

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

replace-method Source/Scenes/Menus/OptionsModel.cs Change
csharp
    // Cycles the difficulty and toggles the audio. Returns true when a setting changed.
    public static bool Change(GameSettings settings, int row, int direction)
    {
        if (direction == 0)
        {
            return false;
        }

        switch (row)
        {
            case 0:
                settings.Difficulty = Cycle(settings.Difficulty, direction);
                return true;
            case 1:
                settings.AudioEnabled = !settings.AudioEnabled;
                return true;
            default:
                return false;
        }
    }

Add the following method to the OptionsModel class, below the Change method:

add-member Source/Scenes/Menus/OptionsModel.cs after=Change
csharp
    private static TEnum Cycle<TEnum>(TEnum value, int direction) where TEnum : struct, Enum
    {
        TEnum[] values = Enum.GetValues<TEnum>();
        int index = Array.IndexOf(values, value);
        index = (index + direction + values.Length) % values.Length;
        return values[index];
    }

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

The key things to note are:

  • Cycle works for any enum. New to generic constraints? See the C# primer. Enum.GetValues lists the values in order, and the modulus wraps from the last to the first. The same method serves the theme in Chapter 20.
  • The test starts from the default Classic difficulty. One step forward gives Hardcore, and the second step wraps to Chill, so the order of the enum decides the cycle.
  • A change goes to the GameSettings object, which is the live profile. The scene, not the model, tells the tracker the settings changed.

The tutorial model ​

The tutorial is five pages. The model holds the pages and the current page number. Its one operation moves on.

TutorialModel.Advance() : bool

  • Takes: nothing.
  • Gives: true when the tutorial is finished, and false otherwise.
  • Promises: each call moves to the next of the 5 pages. After the last page, it calls ProfileTracker.CompleteTutorial and gives true.
  • Refuses: nothing. Leaving early with cancel is the scene's job, and does not mark the tutorial completed.
  • Requirements: FE-07.

In the Source/Scenes/Menus folder, create a new file named TutorialModel.cs and add the following code. The page text is data, so it is written in full.

new-file Source/Scenes/Menus/TutorialModel.cs
csharp
using LastPerimeter.Systems;

namespace LastPerimeter.Scenes.Menus;

public sealed class TutorialModel
{
    private readonly ProfileTracker _profile;

    public TutorialModel(ProfileTracker profile)
    {
        _profile = profile;
    }

    public string[] Pages { get; } =
    [
        "STAY ON THE WALL TO STAY SAFE",
        "MOVE INTO THE ARENA TO DRAW A TRAIL",
        "RECONNECT TO CLAIM AREA",
        "DO NOT STOP OR THE FUSE WILL BURN YOU",
        "REACH THE TARGET PERCENT TO CLEAR THE LEVEL",
    ];

    public int PageIndex { get; private set; }

    public bool Advance()
    {
        throw new NotImplementedException();
    }
}

Open Tests/Scenes/Menus/MenuTests.cs. At the top of the file, add the following line below the using LastPerimeter.Scenes.Menus; line:

add-using Tests/Scenes/Menus/MenuTests.cs after=LastPerimeter.Scenes.Menus
csharp
using LastPerimeter.Systems;

Add the following class to the end of the file. It uses a temporary profile path and cleans it up, exactly as the profile tests of Chapter 16 do, so the test never touches your real profile. It advances through all but the last page and checks that nothing is marked, then advances once more.

add-type Tests/Scenes/Menus/MenuTests.cs
csharp
public sealed class TutorialModelTests : IDisposable
{
    private readonly string _path = Path.Combine(Path.GetTempPath(), $"lastperimeter-tutorial-tests-{Guid.NewGuid():N}", "profile.json");

    [Fact]
    public void Tutorial_FinishingLastPage_MarksItCompleted()
    {
        ProfileTracker profile = new(new ProfileStorage(_path));
        TutorialModel tutorial = new(profile);

        for (int page = 0; page < tutorial.Pages.Length - 1; page++)
        {
            Assert.False(tutorial.Advance());
            Assert.False(profile.Settings.TutorialCompleted);
        }

        Assert.True(tutorial.Advance());
        Assert.True(profile.Settings.TutorialCompleted);
        Assert.Equal(5, tutorial.Pages.Length);
    }

    public void Dispose()
    {
        string? directory = Path.GetDirectoryName(_path);
        if (directory is not null && Directory.Exists(directory))
        {
            Directory.Delete(directory, recursive: true);
        }
    }
}

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

Open Source/Scenes/Menus/TutorialModel.cs. Find the Advance method and replace the whole method with the following:

replace-method Source/Scenes/Menus/TutorialModel.cs Advance
csharp
    // Moves to the next page. After the last page it marks the tutorial completed and returns true.
    public bool Advance()
    {
        if (PageIndex + 1 >= Pages.Length)
        {
            _profile.CompleteTutorial();
            return true;
        }

        PageIndex++;
        return false;
    }

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

The key things to note are:

  • The model takes a ProfileTracker in its constructor, so a test can give it a tracker with a temporary file.
  • PageIndex + 1 >= Pages.Length is the check for the last page. On the last page the index does not move, so a second call would complete the tutorial again.
  • The scene asks Advance on every confirm and leaves the screen when it gives true.

Drawing the menus ​

Every menu draws the same way: a title, a subtitle, a column of rows with a marker on the selected one, and sometimes a dark box behind. If each scene wrote its own layout code, the screens would drift apart. MenuRenderer holds the layout, and the scenes only say what to show.

In the Source/Rendering folder, create a new file named MenuRenderer.cs and add the following code. It needs a graphics device to draw, so it has no test. You check it by running the game.

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

namespace LastPerimeter.Rendering;

// Owns the layout of every menu and overlay: title and subtitle rows, item
// spacing, the selection marker, and the dimmed boxes. The app decides what to
// show; this class decides where it goes.
public sealed class MenuRenderer
{
    private readonly BitmapTextRenderer _textRenderer;
    private readonly int _screenWidth;
    private readonly int _screenHeight;

    public MenuRenderer(int screenWidth, int screenHeight, BitmapTextRenderer textRenderer)
    {
        _textRenderer = textRenderer;
        _screenWidth = screenWidth;
        _screenHeight = screenHeight;
    }

    public void DrawCenteredText(SpriteBatch spriteBatch, Texture2D pixel, string text, int y, int scale, Color color)
    {
        Vector2 size = _textRenderer.MeasureString(text, scale);
        Vector2 position = new((_screenWidth - size.X) / 2f, y);
        _textRenderer.DrawString(spriteBatch, pixel, text, position, color, scale);
    }

    public void DrawMenu(SpriteBatch spriteBatch, Texture2D pixel, string title, string subtitle, IReadOnlyList<string> items, int selectedIndex, Color accent, bool overlay = false)
    {
        if (overlay)
        {
            spriteBatch.Draw(pixel, new Rectangle(80, 80, _screenWidth - 160, _screenHeight - 160), Color.Black * 0.78f);
        }

        DrawCenteredText(spriteBatch, pixel, title, 110, 3, Color.White);
        DrawCenteredText(spriteBatch, pixel, subtitle, 160, 2, Color.LightGray);

        for (int index = 0; index < items.Count; index++)
        {
            Color color = index == selectedIndex ? accent : Color.White;
            DrawCenteredText(spriteBatch, pixel, $"{(index == selectedIndex ? ">" : " ")} {items[index]}", 240 + (index * 36), 2, color);
        }
    }

    public void DrawCenteredOverlay(SpriteBatch spriteBatch, Texture2D pixel, string title, string? body, string footer)
    {
        Rectangle overlay = new(100, 140, _screenWidth - 200, _screenHeight - 280);
        spriteBatch.Draw(pixel, overlay, Color.Black * 0.8f);
        DrawCenteredText(spriteBatch, pixel, title, overlay.Y + 40, 3, Color.White);
        if (!string.IsNullOrWhiteSpace(body))
        {
            DrawCenteredText(spriteBatch, pixel, body, overlay.Y + 130, 2, Color.LightGray);
        }

        DrawCenteredText(spriteBatch, pixel, footer, overlay.Bottom - 60, 2, Color.White);
    }
}

The key things to note are:

  • DrawCenteredText measures the text and centres it across the screen. Every other method calls it.
  • DrawMenu draws the title and subtitle, then one line per row. The selected row gets a > marker and the accent colour. With overlay: true it first draws a dark box over the scene below.
  • DrawCenteredOverlay draws a smaller dark box with a title, an optional body line and a footer. The level complete scene uses it.
  • Color.Black * 0.78f is a black with 78 percent opacity, so the frozen game shows through the pause box.

Adding the renderer to the shared services ​

The scenes reach the renderer, and the command that closes the game, through GameServices. Open Source/Game/GameServices.cs. Add the following property to the GameServices class, below the Profile property:

add-member Source/Game/GameServices.cs after=Profile
csharp
    public MenuRenderer Menus { get; }

Add the following property below the Menus property:

add-member Source/Game/GameServices.cs after=Menus
csharp
    public Action Quit { get; }

In the same file, find this line in the constructor parameters:

find Source/Game/GameServices.cs type=GameServices
csharp
        ProfileTracker profile,

Add the following line directly below it. The constructor takes a new Action quit, between the profile and the window title action. Quit stores it, so a scene can close the game without holding the Game object:

csharp
        Action quit,

In the constructor body, find this line:

find Source/Game/GameServices.cs type=GameServices
csharp
        Profile = profile;

Add the following lines directly below it. Menus is built from the screen size and the text renderer. Audio.Configure applies the stored sound settings at start-up, so the player's audio choice from the last session is in force before the first sound plays:

csharp
        Menus = new MenuRenderer(config.ScreenWidth, config.ScreenHeight, Text);
        Quit = quit;
        Audio.Configure(profile.Settings.AudioEnabled, profile.Settings.MasterVolume);

Open Source/Game/LastPerimeterApp.cs. Exit is the method of the Game class that closes the window.

In the LastPerimeterApp constructor, find this line in the call to GameServices:

find Source/Game/LastPerimeterApp.cs type=LastPerimeterApp
csharp
            _profile,

Add the following line directly below it:

csharp
            Exit,

In a terminal, from the LastPerimeter folder, run dotnet test. This is a checkpoint. The renderer, the services and the host fit together, and no test changed. The summary line should report Failed: 0 and Passed: 140.

Building the scenes ​

Five new scenes and three changed ones come next. Every scene follows the same pattern from the section on models. It asks the model about the input, plays the menu cue when a row moves or is chosen, acts on the answer and draws through MenuRenderer.

IMPORTANT

Scene classes need a graphics device, because they draw, so no test builds one. They are proved by running the game. When you run it later in this chapter, look for the routing. The marker moves and the right screen opens. Escape goes back to the screen that opened it. Nothing freezes. The rules behind each menu are already tested in the models.

The Tutorial and Options scenes stand alone, so you build after each. The other six files refer to each other. The main menu starts a run, the run opens the pause menu, and the pause menu returns to the main menu. The project builds again only when all six are in place. Type them all, then build once.

Scene promises. MainMenuScene gives each row of Figure 17-1 its command (FE-02). PauseScene is an overlay that pops on Escape or on Resume (FE-04). OptionsScene pops back to whichever scene opened it (FE-05). LevelSelectScene offers only the unlocked levels (FE-06). TutorialScene leaves early on cancel and completes the tutorial on the last page (FE-07). The models behind these promises have tests. The routing in the scenes is proved by running the game.

The tutorial scene ​

In the Source/Scenes folder, create a new file named TutorialScene.cs and add the following code. Cancel pops the scene without completing the tutorial. Confirm advances, and pops when Advance reports that the last page is done.

new-file Source/Scenes/TutorialScene.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Game;
using LastPerimeter.Input;
using LastPerimeter.Scenes.Menus;

namespace LastPerimeter.Scenes;

public sealed class TutorialScene : Scene
{
    private readonly GameServices _services;
    private readonly TutorialModel _model;

    public TutorialScene(GameServices services)
    {
        _services = services;
        _model = new TutorialModel(services.Profile);
    }

    public override void Update(float deltaTime, InputState input)
    {
        if (input.IsCancelPressed)
        {
            Scenes.Pop();
            return;
        }

        if (input.IsConfirmPressed && _model.Advance())
        {
            Scenes.Pop();
        }
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        _services.Menus.DrawCenteredText(spriteBatch, _services.Pixel, "TUTORIAL", 120, 3, Color.White);
        _services.Menus.DrawCenteredText(spriteBatch, _services.Pixel, _model.Pages[_model.PageIndex], 250, 2, Color.LightGray);
        _services.Menus.DrawCenteredText(spriteBatch, _services.Pixel, $"STEP {_model.PageIndex + 1}/{_model.Pages.Length}", 320, 2, Color.Gray);
        _services.Menus.DrawCenteredText(spriteBatch, _services.Pixel, "ENTER NEXT  ESC BACK", 420, 2, Color.White);
    }
}

In a terminal, from the LastPerimeter folder, run dotnet test. This is a checkpoint. The new scene builds on its own. The summary line should report Failed: 0 and Passed: 140.

The options scene ​

In the Source/Scenes folder, create a new file named OptionsScene.cs and add the following code. It takes a dimBackground flag. The pause menu passes true, so the box is drawn over the frozen game. The main menu passes false.

new-file Source/Scenes/OptionsScene.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Game;
using LastPerimeter.Input;
using LastPerimeter.Scenes.Menus;

namespace LastPerimeter.Scenes;

public sealed class OptionsScene : Scene
{
    private readonly GameServices _services;
    private readonly bool _dimBackground;
    private readonly MenuList _menu;
    private string[] _labels;

    public OptionsScene(GameServices services, bool dimBackground)
    {
        _services = services;
        _dimBackground = dimBackground;
        _labels = OptionsModel.GetLabels(services.Profile.Settings);
        _menu = new MenuList(_labels);
    }

    public override void Update(float deltaTime, InputState input)
    {
        if (_menu.HandleInput(input) == MenuInput.Moved)
        {
            _services.Audio.PlayMenuSelect();
        }

        if (input.IsCancelPressed)
        {
            Leave();
            return;
        }

        bool changed = false;
        if (input.IsMenuLeftPressed || input.IsMenuRightPressed || input.IsConfirmPressed)
        {
            if (_menu.SelectedIndex == OptionsModel.BackRow)
            {
                Leave();
                return;
            }

            changed = OptionsModel.Change(_services.Profile.Settings, _menu.SelectedIndex, input.IsMenuLeftPressed ? -1 : 1);
        }

        if (changed)
        {
            _services.Audio.Configure(_services.Profile.Settings.AudioEnabled, _services.Profile.Settings.MasterVolume);
            _services.Audio.PlayMenuSelect();
            _services.Profile.MarkSettingsChanged();
            _labels = OptionsModel.GetLabels(_services.Profile.Settings);
        }
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        _services.Menus.DrawMenu(spriteBatch, _services.Pixel, "OPTIONS", "LEFT/RIGHT TO CHANGE", _labels, _menu.SelectedIndex, Color.Gold, _dimBackground);
    }

    private void Leave()
    {
        _services.Profile.MarkSettingsChanged();
        Scenes.Pop();
    }
}

The key things to note are:

  • Leave marks the settings changed and pops. It is the one exit, whether the player chose Back or pressed cancel. The scene below is whichever one opened options.
  • A left, right or confirm press on a setting row calls OptionsModel.Change with -1 for left and 1 otherwise.
  • When a setting changes, the scene reapplies the audio settings, plays the cue and marks the profile dirty. The scene never writes the file. Chapter 16 saves it when the scene allows saving.
  • The labels are rebuilt after a change, so the row shows the new value.

In a terminal, from the LastPerimeter folder, run dotnet test. This is a checkpoint. The summary line should report Failed: 0 and Passed: 140.

The next six files refer to each other, so the project does not build until the last of them is in place. Do not run dotnet test before the checkpoint at the end of the gameplay scene.

The level select scene ​

In the Source/Scenes folder, create a new file named LevelSelectScene.cs and add the following code. It builds its rows from the profile's highest unlocked level, and it does not wrap.

new-file Source/Scenes/LevelSelectScene.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Game;
using LastPerimeter.Input;
using LastPerimeter.Scenes.Menus;

namespace LastPerimeter.Scenes;

public sealed class LevelSelectScene : Scene
{
    private readonly GameServices _services;
    private readonly string[] _labels;
    private readonly MenuList _menu;

    public LevelSelectScene(GameServices services)
    {
        _services = services;
        _labels = MenuTables.LevelLabels(services.Profile.Profile.HighestUnlockedLevel);
        _menu = new MenuList(_labels, wraps: false);
    }

    public override void Update(float deltaTime, InputState input)
    {
        switch (_menu.HandleInput(input))
        {
            case MenuInput.Cancelled:
                Scenes.Pop();
                break;
            case MenuInput.Confirmed:
                _services.Audio.PlayMenuSelect();
                Scenes.Change(GameplayScene.StartRun(_services, _menu.SelectedIndex + 1));
                break;
        }
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        _services.Menus.DrawMenu(spriteBatch, _services.Pixel, "LEVEL SELECT", "CHOOSE A STARTING LEVEL", _labels, _menu.SelectedIndex, Color.Gold);
    }
}

The scene calls GameplayScene.StartRun, which you write in the gameplay scene below. The row index plus one is the starting level.

The pause scene ​

In the Source/Scenes folder, create a new file named PauseScene.cs and add the following code. It is an overlay.

new-file Source/Scenes/PauseScene.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Game;
using LastPerimeter.Input;
using LastPerimeter.Scenes.Menus;

namespace LastPerimeter.Scenes;

public sealed class PauseScene : Scene
{
    private static readonly string[] Labels = MenuTables.Labels(MenuTables.Pause);

    private readonly GameServices _services;
    private readonly MenuList _menu = new(Labels);

    public PauseScene(GameServices services)
    {
        _services = services;
    }

    public override bool IsOverlay => true;

    public override void Update(float deltaTime, InputState input)
    {
        MenuInput result = _menu.HandleInput(input);
        if (result == MenuInput.Moved)
        {
            _services.Audio.PlayMenuSelect();
        }

        if (input.IsPausePressed)
        {
            Scenes.Pop();
            return;
        }

        if (result != MenuInput.Confirmed)
        {
            return;
        }

        _services.Audio.PlayMenuSelect();
        switch (MenuTables.Pause[_menu.SelectedIndex].Command)
        {
            case MenuCommand.Resume:
                Scenes.Pop();
                break;
            case MenuCommand.Options:
                Scenes.Push(new OptionsScene(_services, dimBackground: true));
                break;
            case MenuCommand.QuitToMenu:
                Scenes.Change(new MainMenuScene(_services));
                break;
        }
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        _services.Menus.DrawMenu(spriteBatch, _services.Pixel, "PAUSED", "PRESS ENTER TO SELECT", Labels, _menu.SelectedIndex, Color.Gold, overlay: true);
    }
}

The key things to note are:

  • IsOverlay is true, so the manager draws the gameplay scene first and then the pause menu over it. The gameplay scene is not updated, so the game is frozen.
  • The scene checks IsPausePressed after the menu has looked at the input. A second Escape pops the scene and resumes.
  • Options is pushed on top of the pause menu with a dimmed background. When options pops, the pause menu is on top again.
  • Quit To Menu uses Change, which replaces the whole stack and so removes the run.

The main menu scene ​

In the Source/Scenes folder, create a new file named MainMenuScene.cs and add the following code. The switch is the place that carries out each command.

new-file Source/Scenes/MainMenuScene.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Game;
using LastPerimeter.Input;
using LastPerimeter.Scenes.Menus;

namespace LastPerimeter.Scenes;

public sealed class MainMenuScene : Scene
{
    private static readonly string[] Labels = MenuTables.Labels(MenuTables.Main);

    private readonly GameServices _services;
    private readonly MenuList _menu = new(Labels);

    public MainMenuScene(GameServices services)
    {
        _services = services;
    }

    public override void Update(float deltaTime, InputState input)
    {
        MenuInput result = _menu.HandleInput(input);
        if (result == MenuInput.Moved)
        {
            _services.Audio.PlayMenuSelect();
        }

        if (result != MenuInput.Confirmed)
        {
            return;
        }

        _services.Audio.PlayMenuSelect();
        switch (MenuTables.Main[_menu.SelectedIndex].Command)
        {
            case MenuCommand.StartRun:
                Scenes.Change(GameplayScene.StartRun(_services, 1));
                break;
            case MenuCommand.LevelSelect:
                Scenes.Push(new LevelSelectScene(_services));
                break;
            case MenuCommand.Tutorial:
                Scenes.Push(new TutorialScene(_services));
                break;
            case MenuCommand.Options:
                Scenes.Push(new OptionsScene(_services, dimBackground: false));
                break;
            case MenuCommand.Quit:
                _services.Quit();
                break;
        }
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        _services.Menus.DrawMenu(spriteBatch, _services.Pixel, "LAST PERIMETER", "ARCADE TERRITORY COURSE BUILD", Labels, _menu.SelectedIndex, Color.Gold);
    }
}

The key things to note are:

  • The labels and the commands come from the same MenuTables.Main table that the theory test uses. A row cannot give one command in the test and another in the game.
  • Start Run uses Change to replace the menu with a run at level 1. Level Select, Tutorial and Options use Push, so they pop back to the menu.
  • Quit calls _services.Quit(), which is the Exit method of the host.

The level complete scene ​

The level complete screen becomes an overlay on the gameplay scene, so the finished level stays visible behind it. Open Source/Scenes/LevelCompleteScene.cs and replace the whole file with the following. Most of the file changes, including the using lines, so the whole file is simpler:

replace-file Source/Scenes/LevelCompleteScene.cs
csharp
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Game;
using LastPerimeter.Input;

namespace LastPerimeter.Scenes;

public sealed class LevelCompleteScene : Scene
{
    private readonly GameServices _services;
    private readonly GameplayScene _gameplay;
    private readonly string _bonusLine;

    public LevelCompleteScene(GameServices services, int bonus, GameplayScene gameplay)
    {
        _services = services;
        _gameplay = gameplay;
        _bonusLine = $"BONUS {bonus}";
    }

    public override bool IsOverlay => true;

    public override void Update(float deltaTime, InputState input)
    {
        if (!input.IsConfirmPressed)
        {
            return;
        }

        Scenes.Pop();
        _gameplay.BeginLevel(_gameplay.Simulation.Session.Level + 1);
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        _services.Menus.DrawCenteredOverlay(spriteBatch, _services.Pixel, "LEVEL COMPLETE", _bonusLine, "PRESS ENTER FOR THE NEXT LEVEL");
    }
}

The key changes are:

  • The scene holds the GameplayScene that pushed it, and takes the bonus before it in the constructor.
  • IsOverlay is true.
  • On confirm it pops itself and then calls BeginLevel on the gameplay scene, which starts the next level.
  • It draws through DrawCenteredOverlay, so its own centred text code is gone.

The title scene ​

The title screen no longer starts a run. It goes to the main menu on confirm or cancel. The Draw method also loses its private helper, because MenuRenderer.DrawCenteredText now centres text for every scene. The file is short, so you replace the whole file. Open Source/Scenes/TitleScene.cs and replace the whole file with the following:

replace-file Source/Scenes/TitleScene.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Game;
using LastPerimeter.Input;

namespace LastPerimeter.Scenes;

public sealed class TitleScene : Scene
{
    private readonly GameServices _services;

    public TitleScene(GameServices services)
    {
        _services = services;
    }

    public override void Update(float deltaTime, InputState input)
    {
        if (input.IsConfirmPressed || input.IsCancelPressed)
        {
            _services.Audio.PlayMenuSelect();
            Scenes.Change(new MainMenuScene(_services));
        }
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        _services.Menus.DrawCenteredText(spriteBatch, _services.Pixel, "LAST PERIMETER", 160, 4, Color.White);
        _services.Menus.DrawCenteredText(spriteBatch, _services.Pixel, "PRESS ENTER", 280, 2, Color.LightGray);
    }
}

The key changes are:

  • Update goes to MainMenuScene on confirm or cancel, and plays the menu cue.
  • Draw calls _services.Menus.DrawCenteredText, so the private DrawCentered method is deleted.

The gameplay scene ​

GameplayScene changes in many places. It has a Simulation property and a StartRun method that builds a run from the chosen level and the stored difficulty. It pushes the pause menu. It has a BeginLevel method for the next level, a Dispose, and it rebuilds its claimed-area image when the level changes. The class comment changes as well. Open Source/Scenes/GameplayScene.cs and replace the whole file with the following. Read the key changes before you type it.

replace-file Source/Scenes/GameplayScene.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Data;
using LastPerimeter.Entities;
using LastPerimeter.Game;
using LastPerimeter.Input;
using LastPerimeter.Rendering;
using LastPerimeter.Simulation;
using LastPerimeter.Systems;

namespace LastPerimeter.Scenes;

// Runs the simulation and decides what each event means: a tone, a profile
// counter, a status line or another scene.
public sealed class GameplayScene : Scene
{
    private readonly GameServices _services;
    private readonly GameplaySimulation _simulation;
    private readonly ArenaRenderer _arenaRenderer = new();
    private readonly TrailRenderer _trailRenderer = new();
    private readonly PlayerRenderer _playerRenderer = new();
    private readonly EnemyRenderer _enemyRenderer = new();
    private readonly PowerupRenderer _powerupRenderer = new();
    private readonly HudRenderer _hudRenderer;
    private LevelServices _drawnLevel;
    private ClaimedAreaRenderer _claimedArea;
    private string _status = string.Empty;
    private (int Score, int Lives, int Level, float Claim)? _shownTitleValues;

    // How many captures have completed. The smoke run reads it.
    public int CaptureCount { get; private set; }

    public GameplayScene(GameServices services, GameplaySimulation simulation)
    {
        _services = services;
        _simulation = simulation;
        _hudRenderer = new HudRenderer(services.Text);
        _drawnLevel = simulation.Level;
        _claimedArea = CreateClaimedArea(simulation.Level);
        React(simulation.Events);
    }

    // Gameplay is the only scene that must not trigger a profile write.
    public override bool AllowsSaving => false;

    public GameplaySimulation Simulation => _simulation;

    // Starts a run from a menu. Chapter 18 builds the run in RunFactory instead.
    public static GameplayScene StartRun(GameServices services, int startingLevel, int? seed = null)
    {
        services.Profile.RecordRunStarted();
        GameSession session = new()
        {
            Player = new Player(),
            Level = startingLevel,
            Difficulty = services.Profile.Settings.Difficulty,
            HighScore = services.Profile.Profile.HighScore,
        };
        session.Player.Lives = new LevelProgressionSystem().GetStartingLives(session.Difficulty);
        return new GameplayScene(services, new GameplaySimulation(services.Config, session, seed is null ? new Random() : new Random(seed.Value)));
    }

    public override void Enter()
    {
        UpdateWindowTitle();
    }

    public override void Update(float deltaTime, InputState input)
    {
        // The scene manager defers the push, so the pause menu does not see this same press.
        if (input.IsPausePressed)
        {
            Scenes.Push(new PauseScene(_services));
            return;
        }

        _simulation.Session.HighScore = _services.Profile.Profile.HighScore;
        React(_simulation.Tick(deltaTime, input));
        UpdateWindowTitle();
    }

    // Called by the upgrade scene once an upgrade has been chosen.
    public void BeginLevel(int levelNumber)
    {
        React(_simulation.StartLevel(levelNumber));
        UpdateWindowTitle();
    }

    public override void Prepare()
    {
        if (!ReferenceEquals(_drawnLevel, _simulation.Level))
        {
            _claimedArea.Dispose();
            _drawnLevel = _simulation.Level;
            _claimedArea = CreateClaimedArea(_drawnLevel);
        }

        // Rebuild the claimed-area cache before the batch opens, because a rebuild switches render targets.
        _claimedArea.Prepare();
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        GameSession session = _simulation.Session;
        LevelServices level = _simulation.Level;
        Texture2D pixel = _services.Pixel;

        _arenaRenderer.Draw(spriteBatch, pixel, level.Arena.Bounds, session.PlayableWallPath);
        _claimedArea.Draw(spriteBatch);
        _trailRenderer.Draw(spriteBatch, pixel, session.Player.CurrentTrail, session.SlowDrawActive ? Color.LightYellow : Color.Yellow, session.SlowDrawActive ? 5f : 3f);
        _powerupRenderer.Draw(spriteBatch, pixel, session.Powerups);

        if (level.Fuse.IsActive)
        {
            PrimitiveDrawing.DrawFilledCircle(spriteBatch, pixel, level.Fuse.Position, 4f, Color.Red);
        }

        for (int index = 0; index < session.Enemies.Count; index++)
        {
            _enemyRenderer.Draw(spriteBatch, pixel, session.Enemies[index], Color.OrangeRed);
        }

        _playerRenderer.Draw(spriteBatch, pixel, session.Player, Color.Cyan);
        _hudRenderer.Draw(spriteBatch, pixel, session, level.Config, _status, level.Fuse.IsWarning || level.Fuse.IsActive, level.Fuse.IsActive);
    }

    public override void Dispose()
    {
        _claimedArea.Dispose();
    }

    private ClaimedAreaRenderer CreateClaimedArea(LevelServices level)
    {
        return new ClaimedAreaRenderer(level.Arena, _services.GraphicsDevice, _services.Pixel, Color.RoyalBlue, Color.Orange);
    }

    private void React(IReadOnlyList<GameEvent> events)
    {
        for (int index = 0; index < events.Count; index++)
        {
            React(events[index]);
        }
    }

    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:
                CaptureCount++;
                _claimedArea.MarkDirty();
                _services.Audio.PlayClaim();
                _services.Profile.RecordCapture();
                break;
            case LifeLost:
                _services.Profile.RecordDeath();
                _services.Audio.PlayDeath();
                break;
            case RunLost:
                _services.Profile.RecordRunFinished(_simulation.Session.Score);

                // Chapter 18 shows a run summary here instead.
                Scenes.Change(new MainMenuScene(_services));
                break;
            case PowerupCollected:
                _services.Profile.RecordPowerupCollected();
                _services.Audio.PlayPowerup();
                break;
            case LevelCleared cleared:
                _services.Audio.PlayLevelComplete();
                _services.Profile.RecordLevelCleared(_simulation.Session.Level);
                Scenes.Push(new LevelCompleteScene(_services, cleared.Bonus, this));
                break;
        }
    }

    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:

  • StartRun replaces the old constructor that built its own simulation. It records the start of the run, and reads the starting level and the difficulty from the arguments and the profile settings.
  • Update checks IsPausePressed first. It pushes the pause scene and returns, so the simulation does not tick on the frame that paused. This is the other half of INP-05. The manager defers the push, so the pause scene first updates on the next frame.
  • Update copies the stored high score into the session each frame, so the HUD shows the best score.
  • BeginLevel starts a level in the simulation and reacts to its events. The level complete scene calls it.
  • Prepare rebuilds the claimed-area renderer when the simulation has a new level, because a new level has a new arena.
  • RunLost now changes to MainMenuScene, and LevelCleared pushes a LevelCompleteScene and plays the level complete cue.
  • Dispose frees the claimed-area image when the manager removes the scene.
  • CaptureCount and the optional seed of StartRun are the smoke run's hooks from Chapter 13. The count lets the host check that a capture happened, and the seed makes the enemies the same every run. A normal start from the menu passes no seed.

The scripted smoke run from Chapter 13: Proving the Level still builds its scene with the old constructor, which no longer exists. Open Source/Game/LastPerimeterApp.cs. In the LoadContent method, find this line:

find Source/Game/LastPerimeterApp.cs type=LastPerimeterApp
csharp
            _smokeScene = new GameplayScene(_services.Value, SmokeScript.Seed);

Replace it with the following line. The smoke run now starts through StartRun at level 1 with the fixed seed, which is the same run as before. StartRun gained an optional seed parameter for this:

csharp
            _smokeScene = GameplayScene.StartRun(_services.Value, 1, SmokeScript.Seed);

In a terminal, from the LastPerimeter folder, run dotnet test. This is the checkpoint for all the scenes. The six files that refer to each other now build together. The summary line should report Failed: 0 and Passed: 140.

Running the tests ​

In a terminal, from the LastPerimeter folder, run dotnet test. The build now includes every scene, so a pass proves that the files fit together. The summary line should report Failed: 0 and Passed: 140. The 140 tests are the 126 from Chapter 16 and the 14 new ones.

TestProves
SceneManager_PushedOverlay_DrawsTheSceneBelowFE-04
SceneManager_Pop_ReturnsToCallerFE-05
PausePress_OpensPauseAndIsConsumedINP-05
MenuList_WrapsAtBothEndsFE-03
MenuList_ClampsWhenNotWrappingFE-06
MenuList_ReportsConfirmAndCancelFE-03
OptionsModel_Change_CyclesDifficultyFE-05
MainMenu_ConfirmOnEachItem_IssuesItsCommand (5 cases)FE-02
LevelSelect_StopsAtHighestUnlockedLevelFE-06
Tutorial_FinishingLastPage_MarksItCompletedFE-07

FE-01 has no test, because the title scene needs a graphics device. You check it in the next section.

Running the game ​

Every check in the list below needs a window and a keyboard, because the scene classes have no tests. The test counts confirm the menu rules, but only running the game confirms the routing between screens.

From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Check each part in turn.

  1. Title and main menu (FE-01, FE-02). The title shows LAST PERIMETER and PRESS ENTER. Press Enter. The main menu appears, as in Figure 17-1, with the first row marked.
  2. Wrapping (FE-03). Press Up on the first row. The marker jumps to QUIT. Press Down. It returns to START RUN. Each move plays a short cue.
  3. Options from the main menu (FE-05). Select OPTIONS and press Enter. Press Left or Right on the difficulty row. The word after DIFFICULTY changes. Press Escape. The main menu returns.
  4. Level select (FE-06). Select LEVEL SELECT and press Enter. Only LEVEL 1 is listed. Press Escape to go back.
  5. The tutorial (FE-07). Select TUTORIAL and press Enter. Press Enter four times to see steps 2 to 5 of 5. Press Enter on the fifth page. The screen returns to the main menu, and the profile now records the tutorial as completed.
  6. Pause (FE-04, INP-05). Select START RUN and press Enter. Press Escape. The game freezes, with PAUSED drawn over it. The menu does not close at once.
  7. Options from pause (FE-05). Choose OPTIONS, then press Escape. You are back in the pause menu, not the main menu. Press Escape again. The game resumes where it stopped.
  8. Quit. Pause again and choose QUIT TO MENU. The main menu appears. Choose QUIT. The window closes.

Level select shows one level for a new player. To see more rows, you can raise the unlock by hand. This is a test-only edit of your own profile. Close the game. Open profile.json, the file described in Chapter 16: Profiles, Settings and Saving, in a text editor. Change "HighestUnlockedLevel": 1 to "HighestUnlockedLevel": 4, and save the file. Run the game again. Level select now lists four levels and stops on LEVEL 4 when you press Down repeatedly. Set the value back to 1 when you are finished.

TIP

To see the wrap logic at work, open Source/Scenes/MainMenuScene.cs and change new(Labels) to new(Labels, wraps: false). Run the game, and Up on the first row no longer jumps to the last. Change it back afterwards.

Last, run the smoke check again. In PowerShell, from the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK -- --smoke-test-seconds 3 and then $LASTEXITCODE. In bash, run the same dotnet command and then echo $?. The exit code must be 0. The smoke run skips every menu and plays the scripted capture through StartRun, and it writes its profile under the system temp folder, not your real profile.

The next section is optional. It replaces your files with the chapter 17 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 17 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/17-Menus-And-The-Front-End"
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/17-Menus-And-The-Front-End"
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: 140.

Common mistakes ​

  • The build fails with a missing MainMenuScene or GameplayScene.StartRun. The scenes refer to each other. Check that all five new scene files exist and that you replaced GameplayScene.cs.
  • The pause menu closes the moment it opens. A scene change or push is being applied in the same frame. Check that Push queues a request and that ApplyPending runs after the top scene's Update.
  • The game under the pause menu disappears. PauseScene.IsOverlay is missing or false, so the manager draws only the top scene.
  • Back from options in the pause menu goes to the main menu. The pause menu pushed options with Change. It must use Push, so that Pop has a scene to return to.
  • Level select lists every level. It builds its rows from the wrong number. Use HighestUnlockedLevel from services.Profile.Profile.
  • A menu moves two rows for one key press. The input was read twice in one frame. The host reads it once and gives the same InputState to the scene.

Conclusion ​

In this chapter, you accomplished the following:

The tests now prove FE-02 to FE-07 and INP-05, and the run of the game proves FE-01. In the next chapter, Chapter 18: Runs and Upgrades, you build a run as a unit, with upgrades chosen between levels and a summary when the run ends.

Test Your Knowledge ​

  1. Why does the options scene not need to know whether the pause menu or the main menu opened it?

    Answer

    It only pops itself. The stack returns to whatever scene is below, and that is the scene that pushed it.

  2. What would go wrong if Push took effect at once?

    Answer

    The pause scene would be on the stack during the same frame, and could see the same Escape press. It would resume the game at once, so the player could never pause.

  3. Why is MenuList a class of its own, when each menu could handle its own keys?

    Answer

    One tested model gives every menu the same wrapping and the same keys. Several hand-written copies drift apart, and a scene cannot be tested without a window.

  4. Why does Draw start at the highest scene that is not an overlay, and not at the bottom of the stack?

    Answer

    A scene below an opaque scene is hidden, so drawing it would waste time. An overlay is the only kind of scene that lets the scene below show through.

Extensions ​

  • Add a row to the pause menu named RESTART. Which files change, and which test could prove the new row?
  • Make MenuList skip a row that is disabled. What would the constructor need to know?