Skip to content

Chapter 05: Scenes and the Gameplay Simulation ​

In Chapter 04: Input and Frame Time, you made the dot move. You did it inside the Update method of the host class, and the chapter said that this was a first version. The host now holds a game rule, which makes it harder to test and harder to change.

In this chapter, you move everything game-specific out of the host. Screens become scenes, the shared objects become GameServices, and the rules become a GameplaySimulation that runs with no window. The game looks the same at the end. The difference is that every rule from here on can be tested.

Figure 05-1: The chapter 05 title screen. One white bar stands in for the title text
Figure 05-1: The chapter 05 title screen. One white bar stands in for the title text. This is a drawn illustration, not a screenshot.

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

In this chapter, you will:

  • Learn why game rules should not live in the Game subclass.
  • Write GameServices, the one object every scene receives.
  • Write Scene and SceneManager, and learn why a scene change waits until the update ends.
  • Write GameplaySimulation with its first operation, Tick, and the GameEvent type it will report through.
  • Write TitleScene and GameplayScene, and shrink the host to a few lines.
  • Write your first scenario test: a simulation driven by scripted input, with no window.

Requirements in this chapter ​

IDShort name
NFR-03Every gameplay rule testable without a window
NFR-05No nullable late-wired service fields
FE-01Title screen, then the game (first version: Enter starts play)

Why rules do not live in the host ​

The class that MonoGame asks you to subclass is the easiest place to put code. It already has Update and Draw, so each new feature goes in there. A feature adds a field, a few lines to Update and a few lines to Draw. Nothing about this is wrong on the first day.

The trouble comes later. A game that grows this way ends with a host of well over a thousand lines. It reads the keyboard, holds every rule, plays sounds, draws menus and saves files, all in one class. Every change touches that class, so every change risks everything else in it. Most of its fields are set up late, after the graphics device exists, so each method begins with a long check that none of them is null. And no test can run any of it, because the host needs a window.

You stop that now, while the host is still small. The fix is to give each kind of code one home, and to let each home use only the homes below it.

Where rules go ​

Figure 05-2 shows the layers. An arrow means "may use". Each layer uses only the layers below it, and never the ones above.

Figure 05-2: The layers of the game. Each layer uses only the layers below it

The host owns the MonoGame lifetime and nothing else. A scene is one screen of the game, such as the title or the play field. The simulation holds the rules and the state of one run. A service from Chapter 03: The Service Pattern and the Arena does one job for the simulation. Three more terms matter in this chapter. GameServices is the object that carries what every scene shares, such as the sprite batch and the input reader. GameSession is the state of one run. A GameEvent is a value that says what happened.

Simulation and presentation ​

The simulation changes state and reports what happened. It never plays a sound, builds text or draws. The scene reads the events and the state, then decides what to play and what to draw. The simulation does not know that the scene exists.

This split is what makes NFR-03 possible. A test can create a GameplaySimulation, feed it inputs, and read the state and the events afterwards. No window, no graphics device and no audio is needed. Figure 05-3 shows one frame.

Figure 05-3: One frame. Input goes down to the simulation, events come back up, and the scene draws the state

Scenes and deferred changes ​

A scene has four jobs: it updates, it prepares, it draws and it can ask for another scene. The SceneManager holds the current scene and calls only that scene. When the player presses Enter on the title screen, TitleScene asks the manager to change to GameplayScene.

The change does not happen at once. The manager queues it and applies it after the current Update returns. There are two reasons. First, replacing the current scene while its own Update is still running pulls the object out from under its own method. Second, the new scene would be created in the same frame as the key press that asked for it. If the new scene read input in that frame, the same Enter press could act twice.

Building in one step ​

The graphics device does not exist when the host constructor runs. It exists once MonoGame calls LoadContent. So the sprite batch and the one-pixel texture cannot be built in the constructor. A host that keeps them as fields must declare them as nullable and check them in every method that uses them. That is what the Chapter 04 host does.

GameServices removes the problem. Its constructor takes the graphics device and builds every shared object in one statement, so a GameServices that exists is complete. The host keeps it as a Lazy<GameServices>. A lazy value is created the first time anyone reads it, and once only. New to Lazy<T>? See the C# primer. LoadContent reads it first, at the moment the device is ready. That is NFR-05: no field that is half there.

Some MonoGame tutorials use a static class for this job. An object works the same way for the game, and a test can build one with different parts. A static class is shared by every test at once.

The order of one tick ​

One frame of the game always runs in the same order. The input is read once, then GameplaySimulation.Tick runs its numbered steps, then a capture may complete and rebuild the wall, and then the scene draws. The numbers are the ones in the comments of the Tick method. Later chapters link to this table, so it is the one place that shows the whole sequence.

You build the steps one chapter at a time. In this chapter you build only step 4, together with reading the input and drawing. Every other row is filled in by the chapter named in the last column.

StepWhat happensChapter that adds itIn this chapter
InputRead the keyboard and gamepad once into one InputStateChapter 04Yes
1Timers count down: enemy freeze, respawn grace and double pointsChapter 10, then 11 and 15No
2Powerups updateChapter 15No
3Check whether the player really moved since the last frame, for the fuseChapter 08No
4Intent: turn the input into a direction and a speedThis chapterYes
5Enemies moveChapter 10No
6Stop early when there is no input and no trailChapter 07No
7Work out where the player would like to be after this frameChapter 07No
8aWhile drawing a trail: the fuse burnsChapter 08No
8bWhile drawing a trail: an enemy touches the player or the trailChapter 10No
8cWhile drawing a trail: the player reconnects to the wallChapter 07No
8dWhile drawing a trail: the player crosses their own trailChapter 07No
8eWhile drawing a trail: the trail advancesChapter 07No
9aOn the wall: the fuse is put outChapter 08No
9bOn the wall: the player moves along the wallChapter 06No
9cOn the wall: the player tries to start a trailChapter 07No
CaptureSteps 8c and 8d complete a loop, which claims the enclosed areaChapter 09No
Wall rebuildThe wall path is rebuilt after a capture and the player is snapped onto itChapter 09No
DrawingThe scene draws the state that the tick producedThis chapterYes

Steps 8a to 8e run only when a trail is active, and steps 9a to 9c run when none is. A step that a chapter does not yet build is simply absent from the Tick method at that point. The capture has its own numbered steps inside ResolveCapture, which Chapter 09 explains.

Setting up the folders ​

Open a terminal in the LastPerimeter folder. Run each of the following commands from there, one at a time. The Source/Game folder, the Tests/TestHelpers folder and the Source/Data folder already exist.

text
mkdir Source/Scenes
mkdir Source/Simulation
mkdir Tests/Scenes
mkdir Tests/Simulation

Building the shared services ​

In the Source/Game folder, create a new file named GameServices.cs and add the following code. It is the object every scene receives.

new-file Source/Game/GameServices.cs
csharp
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Data;
using LastPerimeter.Input;

namespace LastPerimeter.Game;

// Everything the scenes share, built in one step. It is an object passed to the
// scenes rather than a static class, so a test can build a scene with fakes.
public sealed class GameServices : IDisposable
{
    public GameServices(GameConfig config, GraphicsDevice graphicsDevice)
    {
        Config = config;
        GraphicsDevice = graphicsDevice;
        SpriteBatch = new SpriteBatch(graphicsDevice);
        Pixel = CreatePixel(graphicsDevice);
        Input = new InputManager();
    }

    public GameConfig Config { get; }
    public GraphicsDevice GraphicsDevice { get; }
    public SpriteBatch SpriteBatch { get; }
    public Texture2D Pixel { get; }
    public InputManager Input { get; }

    public void Dispose()
    {
        Pixel.Dispose();
        SpriteBatch.Dispose();
    }

    private static Texture2D CreatePixel(GraphicsDevice graphicsDevice)
    {
        Texture2D pixel = new(graphicsDevice, 1, 1);
        pixel.SetData([Color.White]);
        return pixel;
    }
}

The key things to note are:

  • The constructor builds the sprite batch, the one-pixel texture and the input reader in one go. There is no state in which only some of them exist.
  • It is IDisposable, because the sprite batch and the texture hold graphics memory. Dispose releases both.
  • GameConfig is passed in, and the scenes read the arena and the screen size from it.
  • CreatePixel moved here from the host. It makes the same one-pixel white texture that you made in Chapter 02.

Building the scene manager ​

In the Source/Scenes folder, create a new file named Scene.cs and add the following code. A Scene is an abstract class, which means you cannot create one directly. You create a class that inherits from it, as TitleScene does later. New to abstract classes? See the C# primer. The IDisposable part is explained in the C# primer.

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

namespace LastPerimeter.Scenes;

// One screen of the game. A scene has no constructor parameters of its own here,
// so a test can make a stub scene. The manager attaches itself when it adds the scene.
public abstract class Scene : IDisposable
{
    private SceneManager? _manager;

    // True when the scene below must be drawn first (pause, level complete, upgrade, run summary).
    public virtual bool IsOverlay => false;

    // False only for the gameplay scene, so the profile is never written mid-play.
    public virtual bool AllowsSaving => true;

    protected SceneManager Scenes => _manager ?? throw new InvalidOperationException("The scene has not been added to a scene manager.");

    // Called once, when the manager adds the scene to the stack.
    public virtual void Enter()
    {
    }

    public abstract void Update(float deltaTime, InputState input);

    // Render-target work that must happen before the sprite batch opens.
    public virtual void Prepare()
    {
    }

    // Draws inside the open batch.
    public abstract void Draw(SpriteBatch spriteBatch);

    public virtual void Dispose()
    {
    }

    internal void Attach(SceneManager manager)
    {
        _manager = manager;
    }
}

The key things to note are:

  • Update and Draw are abstract, so every scene must write them. Enter, Prepare and Dispose do nothing by default.
  • A scene has no constructor parameters of its own, so a test can write a small stub scene with one line.
  • Scenes gives a scene access to its manager, and it throws if the scene has not been added to one. The manager calls the internal method Attach when it adds the scene.
  • IsOverlay and AllowsSaving are not used yet. They are here so that later chapters add scenes without changing this class.

The manager has two operations that matter. Change queues a new scene. Update runs the top scene, then applies the queue. Prepare and Draw only pass the call to the top scene.

SceneManager.Change(scene) : void

  • Takes: the scene to show next.
  • Gives: nothing. The scene is queued.
  • Promises: the change takes effect after the current Update returns. It replaces the whole stack with the one scene.
  • Refuses: nothing.
  • Requirements: FE-01.

SceneManager.Update(deltaTime, input) : void

  • Takes: the frame time and one InputState.
  • Gives: nothing.
  • Promises: only the top scene updates. A queued change is applied after that update. The new scene gets no update in the frame that created it.
  • Refuses: with no scene, it does nothing.
  • Requirements: FE-01.

In the Source/Scenes folder, create a new file named SceneManager.cs and add the following code. The fields, Top, Count, Prepare, Draw and Dispose are written in full. Change and Update are stubs.

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

namespace LastPerimeter.Scenes;

// Holds the current scene. A change is queued and applied after the top scene
// finishes its Update. That avoids changing the stack while it is in use, and the new
// scene does not see the key press that asked for it. The stack is a list because
// chapter 17 adds overlay scenes on top of it, with Push and Pop.
public sealed class SceneManager : IDisposable
{
    private readonly List<Scene> _stack = [];
    private readonly List<Scene> _pending = [];

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

    public void Change(Scene scene)
    {
        throw new NotImplementedException();
    }

    public void Update(float deltaTime, InputState input)
    {
        throw new NotImplementedException();
    }

    public void Prepare()
    {
        Top?.Prepare();
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        Top?.Draw(spriteBatch);
    }

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

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

        _stack.Clear();
    }
}

The key things to note are:

  • The scenes are held in a list called _stack. Only one scene is ever in it for now. Chapter 17 adds overlay scenes on top, which is why it is a list.
  • _pending is the queue of scenes that wait for the update to end.
  • The Top property reads the last item, and answers null when the stack is empty.

In a terminal, from the LastPerimeter folder, run dotnet build. The build should succeed.

Now the tests. In the Tests/Scenes folder, create a new file named SceneManagerTests.cs and add the following code. It holds a private StubScene that counts its updates and can run an action when it updates. The action is an Action delegate. New to Action? See the C# primer. The first test makes the first scene ask for a change during its own update. It then checks that the change landed after the update, and that the new scene was not updated in that frame. The second test checks that only the top scene receives updates.

new-file Tests/Scenes/SceneManagerTests.cs
csharp
using Microsoft.Xna.Framework.Graphics;
using LastPerimeter.Input;
using LastPerimeter.Scenes;

namespace LastPerimeter.Tests.Scenes;

public sealed class SceneManagerTests
{
    private sealed class StubScene : Scene
    {
        public int Updates { get; private set; }
        public Action<StubScene, InputState>? OnUpdate { get; init; }

        public override void Update(float deltaTime, InputState input)
        {
            Updates++;
            OnUpdate?.Invoke(this, input);
        }

        public override void Draw(SpriteBatch spriteBatch)
        {
        }

        public void RequestChange(Scene scene) => Scenes.Change(scene);
    }

    private static SceneManager StartWith(Scene scene)
    {
        SceneManager manager = new();
        manager.Change(scene);
        manager.Update(0.016f, InputState.Empty);
        return manager;
    }

    [Fact]
    public void SceneManager_Change_TakesEffectAfterUpdate()
    {
        StubScene second = new();
        StubScene first = new() { OnUpdate = (scene, _) => scene.RequestChange(second) };
        SceneManager manager = StartWith(first);

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

        Assert.Same(second, manager.Top);
        Assert.Equal(1, manager.Count);
        Assert.Equal(0, second.Updates);
    }

    [Fact]
    public void SceneManager_UpdatesOnlyTheTopScene()
    {
        StubScene bottom = new();
        StubScene top = new();
        SceneManager manager = StartWith(bottom);
        manager.Change(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);
    }
}

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 2 and Passed: 15. The 15 passes are the tests from earlier chapters.

Open Source/Scenes/SceneManager.cs. Add the following method to the SceneManager class, above the DisposeAll method. It is a private helper, so it has no card of its own.

add-member Source/Scenes/SceneManager.cs before=DisposeAll
csharp
    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++)
        {
            DisposeAll();
            Scene scene = _pending[index];
            scene.Attach(this);
            _stack.Add(scene);
            scene.Enter();
        }

        _pending.Clear();
    }

In the same file, find the Change method and replace the whole method with the following:

replace-method Source/Scenes/SceneManager.cs Change
csharp
    // Replaces the whole stack with one scene, after the current update.
    public void Change(Scene scene)
    {
        _pending.Add(scene);
    }

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

replace-method Source/Scenes/SceneManager.cs Update
csharp
    // Updates only the top scene, then applies any queued change.
    public void Update(float deltaTime, InputState input)
    {
        Top?.Update(deltaTime, input);
        ApplyPending();
    }

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

The key things to note are:

  • Change only adds to _pending. Nothing about the current scene changes during the call.
  • Update runs the top scene first and applies the queue second. This order is what stops the new scene from seeing the key press.
  • ApplyPending disposes the old stack, attaches the new scene, adds it and calls Enter. It reads _pending.Count on every pass of the loop, because Enter may queue another change.
  • The test proves FE-01 in its general form: a change asked for during an update is applied after it, and only the top scene updates.

Building the simulation ​

The simulation needs a few types before its first operation. In the Source/Data folder, create a new file named GameSession.cs and add the following code. It holds the state of one run. It has a player, a score and a level for now, and each later chapter adds what it needs. A required property must be set when the object is created. New to required? See the C# primer.

new-file Source/Data/GameSession.cs
csharp
using LastPerimeter.Entities;

namespace LastPerimeter.Data;

// The state of one run. It grows in every chapter that adds something to remember.
public sealed class GameSession
{
    public required Player Player { get; init; }
    public int Score { get; set; }
    public int Level { get; set; } = 1;
}

In the Source/Simulation folder, create a new file named GameEvent.cs and add the following code. It is an abstract record with no members, which later chapters inherit from, one record for each thing that can happen. Nothing inherits from it yet.

new-file Source/Simulation/GameEvent.cs
csharp
namespace LastPerimeter.Simulation;

// What happened in one frame of the rules. The simulation reports these values
// and never plays a sound, writes the profile or builds text.
public abstract record GameEvent;

In the Source/Simulation folder, create a new file named SimulationState.cs and add the following code. It has one value for now, because the simulation can only be running.

new-file Source/Simulation/SimulationState.cs
csharp
namespace LastPerimeter.Simulation;

public enum SimulationState
{
    Running,
}

In the Source/Simulation folder, create a new file named GameplaySimulation.cs and add the following code. The constructor and the properties are written in full. Tick is a stub. The listing has more using lines than the stub needs, and the body of Tick uses them in a moment.

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

namespace LastPerimeter.Simulation;

// The headless heart of the game. It owns the session and the services that
// the rules need. It reports what happened as events. It never plays a sound,
// writes the profile, builds text or touches the screen.
public sealed class GameplaySimulation
{
    private readonly GameConfig _baseConfig;
    private readonly GameSession _session;
    private readonly MovementSystem _movement = new();
    private readonly List<GameEvent> _events = [];

    public GameplaySimulation(GameConfig baseConfig, GameSession session)
    {
        _baseConfig = baseConfig;
        _session = session;
    }

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

    public IReadOnlyList<GameEvent> Tick(float deltaTime, InputState input)
    {
        throw new NotImplementedException();
    }
}

The key things to note are:

  • The simulation receives a GameConfig and a GameSession. It does not build them, so a test can pass a small arena and its own session.
  • _events is one list that is reused every frame. Tick clears it and returns it, so the simulation does not allocate a list 60 times a second.
  • MovementSystem is a field here, from Chapter 04. The simulation owns the services that the rules need.
  • Nothing in the file refers to SpriteBatch, GraphicsDevice or audio. The using lines show it.

In a terminal, from the LastPerimeter folder, run dotnet build. The build should succeed.

Ticking the simulation ​

Tick is the one operation that runs a frame of rules. For now the rule is the movement from Chapter 04. Later chapters add steps before and after it, so the movement is labelled step 4 in a comment. The order of one tick lists every step the course builds and the chapter that adds it.

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

  • Takes: the frame time in seconds and one InputState.
  • Gives: the events raised in this frame. The list is reused, so a caller copies what it needs before the next tick.
  • Promises: the player moves in the direction of the input at the configured speed, and never leaves the arena.
  • Refuses: nothing. With no input, the player stays where it is.
  • Requirements: NFR-03.

Two helpers make scenario tests short. They grow in later chapters. In the Tests/TestHelpers folder, open TestConfigFactory.cs. Find the Create method and replace the whole method with the following. The only change is PlayerSpeed = 100f. A speed of 100 pixels per second makes the expected distances easy to work out by eye.

replace-method Tests/TestHelpers/TestConfigFactory.cs Create
csharp
    public static GameConfig Create(int width = 80, int height = 80, int margin = 0, int tileSize = 4)
    {
        return new GameConfig
        {
            ScreenWidth = width,
            ScreenHeight = height,
            ArenaMargin = margin,
            HudTopReserve = 0,
            HudBottomReserve = 0,
            TileSize = tileSize,
            PlayerSpeed = 100f,
        };
    }

In the Tests/TestHelpers folder, create a new file named SimulationBuilder.cs and add the following code. It builds a simulation with a small 80 by 80 arena and a player at its top-left corner.

new-file Tests/TestHelpers/SimulationBuilder.cs
csharp
using LastPerimeter.Data;
using LastPerimeter.Entities;
using LastPerimeter.Simulation;

namespace LastPerimeter.Tests.TestHelpers;

// Builds a small arena (80 by 80, 4 pixel tiles) with a player at its top-left corner.
internal static class SimulationBuilder
{
    public static GameplaySimulation Create(int margin = 0)
    {
        GameConfig config = TestConfigFactory.Create(width: 80 + (margin * 2), height: 80 + (margin * 2), margin: margin, tileSize: 4);
        GameSession session = new() { Player = new Player() };
        return new GameplaySimulation(config, session);
    }
}

In the Tests/TestHelpers folder, create a new file named ScriptedInput.cs and add the following code. Run holds one input for a number of frames, calls Tick on each, and collects every event. The frame time is 0.05 seconds, so at 100 pixels per second one frame moves 5 pixels.

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

namespace LastPerimeter.Tests.TestHelpers;

// Holds an input for a number of frames, calling Tick each frame, and gathers every event raised.
internal static class ScriptedInput
{
    public const float Frame = 0.05f;

    public static readonly InputState Right = new() { IsMovingRight = true };
    public static readonly InputState Left = new() { IsMovingLeft = true };
    public static readonly InputState Up = new() { IsMovingUp = true };
    public static readonly InputState Down = new() { IsMovingDown = true };
    public static readonly InputState Idle = InputState.Empty;

    public static List<GameEvent> Run(GameplaySimulation simulation, InputState input, int frames)
    {
        List<GameEvent> raised = [];
        for (int frame = 0; frame < frames; frame++)
        {
            raised.AddRange(simulation.Tick(Frame, input));
        }

        return raised;
    }
}

In the Tests/Simulation folder, create a new file named MovementScenarioTests.cs and add the following code. A scenario test drives the simulation with a script of inputs and checks the outcome. The first test holds Right for one frame and expects the player at x = 5. The second runs 60 frames in each direction and checks, after every frame, that the player is inside the arena.

new-file Tests/Simulation/MovementScenarioTests.cs
csharp
using Microsoft.Xna.Framework;
using LastPerimeter.Input;
using LastPerimeter.Simulation;
using LastPerimeter.Tests.TestHelpers;

namespace LastPerimeter.Tests.Simulation;

public sealed class MovementScenarioTests
{
    [Fact]
    public void Tick_WithRightHeld_MovesPlayerRight()
    {
        GameplaySimulation sim = SimulationBuilder.Create();

        ScriptedInput.Run(sim, ScriptedInput.Right, 1);

        Assert.Equal(5f, sim.Session.Player.Position.X, precision: 2);
        Assert.Equal(0f, sim.Session.Player.Position.Y, precision: 2);
    }

    [Fact]
    public void Tick_KeepsPlayerInsideArena()
    {
        GameplaySimulation sim = SimulationBuilder.Create();
        Rectangle bounds = TestConfigFactory.Create().ArenaBounds;
        InputState[] script = [ScriptedInput.Right, ScriptedInput.Down, ScriptedInput.Left, ScriptedInput.Up, ScriptedInput.Right];

        foreach (InputState input in script)
        {
            for (int frame = 0; frame < 60; frame++)
            {
                sim.Tick(ScriptedInput.Frame, input);
                Vector2 position = sim.Session.Player.Position;
                Assert.InRange(position.X, bounds.Left, bounds.Right);
                Assert.InRange(position.Y, bounds.Top, bounds.Bottom);
            }
        }
    }
}

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

Open Source/Simulation/GameplaySimulation.cs. Find the Tick method and replace the whole method with the following:

replace-method Source/Simulation/GameplaySimulation.cs Tick
csharp
    // One frame of rules. Returns the reused list of events raised in this frame.
    public IReadOnlyList<GameEvent> Tick(float deltaTime, InputState input)
    {
        _events.Clear();

        // 4. Intent: which way does the player want to go?
        Direction direction = _movement.DetermineDirection(input);

        // Move, then keep the player inside the arena. Chapter 06 replaces the clamp with the wall path.
        Player player = _session.Player;
        Vector2 next = _movement.CalculateNextPosition(player.Position, direction, _baseConfig.PlayerSpeed, deltaTime);
        Rectangle bounds = _baseConfig.ArenaBounds;
        player.Position = new Vector2(Math.Clamp(next.X, bounds.Left, bounds.Right), Math.Clamp(next.Y, bounds.Top, bounds.Bottom));

        return _events;
    }

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

The key things to note are:

  • Tick clears the event list first, so a caller never sees the events of an older frame.
  • The movement code is the one from the Chapter 04 host, moved here. The calls to DetermineDirection, CalculateNextPosition and Math.Clamp are unchanged.
  • The player moves a total of 5 pixels in the first test, which is 100 pixels per second times 0.05 seconds. This is the rule from Chapter 04, now proved with no window.
  • The second test would catch a missing clamp. Each direction runs for 60 frames, which is 300 pixels, and the arena is only 80 pixels wide, so every direction ends against an edge.
  • The comment says that Chapter 06 replaces the clamp. The player will then follow a wall path instead of a rectangle.

Building the scenes ​

In the Source/Scenes folder, create a new file named TitleScene.cs and add the following code. It waits for Enter, then asks the manager for GameplayScene. A white bar stands in for the title text, because the bitmap font arrives in Chapter 12.

new-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)
        {
            Scenes.Change(new GameplayScene(_services));
        }
    }

    // A bar stands in for the title text until the bitmap font arrives in chapter 12.
    public override void Draw(SpriteBatch spriteBatch)
    {
        int width = 400;
        int x = (_services.Config.ScreenWidth - width) / 2;
        spriteBatch.Draw(_services.Pixel, new Rectangle(x, 160, width, 24), Color.White);
    }
}

In the Source/Scenes folder, create a new file named GameplayScene.cs and add the following code. It creates the session and the simulation, ticks the simulation each frame and draws the result. The arena and player renderers are the ones from Chapter 02.

new-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;

namespace LastPerimeter.Scenes;

// Runs the simulation and draws its state. It decides what each event means.
public sealed class GameplayScene : Scene
{
    private readonly GameServices _services;
    private readonly GameplaySimulation _simulation;
    private readonly ArenaRenderer _arenaRenderer = new();
    private readonly PlayerRenderer _playerRenderer = new();

    public GameplayScene(GameServices services)
    {
        _services = services;
        Rectangle bounds = services.Config.ArenaBounds;
        GameSession session = new() { Player = new Player { Position = new Vector2(bounds.Left, bounds.Top) } };
        _simulation = new GameplaySimulation(services.Config, session);
    }

    public override void Update(float deltaTime, InputState input)
    {
        _simulation.Tick(deltaTime, input);
    }

    public override void Draw(SpriteBatch spriteBatch)
    {
        _arenaRenderer.Draw(spriteBatch, _services.Pixel, _services.Config.ArenaBounds);
        _playerRenderer.Draw(spriteBatch, _services.Pixel, _simulation.Session.Player, Color.Cyan);
    }
}

The key things to note are:

  • TitleScene reads input.IsConfirmPressed, which is a pressed edge from Chapter 04. One press starts the game once.
  • GameplayScene does no rules. Its Update is one call to Tick. Its Draw reads the player from the simulation's session.
  • The player starts at the top-left corner of the arena, which is where the Chapter 04 host put it.
  • The scene draws what the simulation holds. It does not keep its own copy of the player's position.

Wiring it into the game ​

The last change is the host. Almost every part of it changes: the using lines, the fields, the constructor and every method but one. A replacement of each part one at a time would take longer than the file itself, so you replace the whole file. Open Source/Game/LastPerimeterApp.cs and replace the whole file with the following. It is the shortest the host will be for the rest of the course.

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

namespace LastPerimeter.Game;

// The thin MonoGame host. It builds the shared services, owns the scene manager
// and forwards Update and Draw. It handles the smoke-test exit.
public sealed class LastPerimeterApp : Microsoft.Xna.Framework.Game
{
    private readonly GraphicsDeviceManager _graphics;
    private readonly GameConfig _config = new();
    private readonly GameLaunchOptions _launchOptions;
    private readonly SceneManager _scenes = new();
    private readonly Lazy<GameServices> _services;

    public LastPerimeterApp(GameLaunchOptions? launchOptions = null)
    {
        _launchOptions = launchOptions ?? new GameLaunchOptions(null);
        _graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        IsMouseVisible = true;
        _graphics.PreferredBackBufferWidth = _config.ScreenWidth;
        _graphics.PreferredBackBufferHeight = _config.ScreenHeight;

        // The services need the graphics device, which exists only from LoadContent.
        // The factory runs once, in one step, so there is never a half-built set.
        _services = new Lazy<GameServices>(() => new GameServices(_config, GraphicsDevice));
    }

    protected override void LoadContent()
    {
        _scenes.Change(new TitleScene(_services.Value));
    }

    protected override void Update(GameTime gameTime)
    {
        if (ShouldAutoExit(gameTime))
        {
            return;
        }

        InputState input = _services.Value.Input.GetCurrentInput();
        _scenes.Update((float)gameTime.ElapsedGameTime.TotalSeconds, input);
        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GameServices services = _services.Value;

        _scenes.Prepare();

        GraphicsDevice.Clear(Color.Black);
        services.SpriteBatch.Begin(samplerState: SamplerState.PointClamp);
        _scenes.Draw(services.SpriteBatch);
        services.SpriteBatch.End();
        base.Draw(gameTime);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _scenes.Dispose();
            if (_services.IsValueCreated)
            {
                _services.Value.Dispose();
            }
        }

        base.Dispose(disposing);
    }

    private bool ShouldAutoExit(GameTime gameTime)
    {
        if (_launchOptions.AutoExitAfter is TimeSpan autoExitAfter && gameTime.TotalGameTime >= autoExitAfter)
        {
            Exit();
            return true;
        }

        return false;
    }
}

The key changes are:

  • The _spriteBatch, _pixel, _input, _movement, _player and renderer fields are gone. GameServices and the scenes own them now.
  • _scenes holds the SceneManager, and _services holds a Lazy<GameServices>. Neither is nullable.
  • The constructor takes the screen size from _config, and it builds the lazy factory. The factory does not run until something reads _services.Value.
  • LoadContent reads _services.Value, which builds GameServices at the first moment the graphics device exists. It then queues the TitleScene.
  • Update reads one InputState and passes it to _scenes.Update. This is still the single call per frame from Chapter 04.
  • Draw calls Prepare, clears the screen, opens one batch, lets the scene draw and closes the batch.
  • Dispose releases the scenes and the services. CreatePixel is gone, because GameServices has it.
  • The LastPerimeter.Entities, LastPerimeter.Systems and LastPerimeter.Rendering using lines are gone, because the host no longer uses those types.

NOTE

Count what is left. The host has no rule, no renderer and no player. It builds the services, forwards two calls and handles the smoke-test exit. When a later chapter adds a screen, a rule or a sound, this file does not change.

Running the tests ​

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

TestProves
SceneManager_Change_TakesEffectAfterUpdateFE-01
SceneManager_UpdatesOnlyTheTopSceneFE-01
Tick_WithRightHeld_MovesPlayerRightNFR-03
Tick_KeepsPlayerInsideArenaNFR-03

NFR-05 has no test of its own. You can check it by reading the host listing: there is no nullable field and no null check on a service. FE-01 also needs the title screen, which you check in the next section.

Running the game ​

From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. The movement rules are proved by the two Tick tests, and the scene change by the scene manager tests. The title bar, the arena and the dot need a window and a screen, so only you can confirm them.

A window opens on a black screen with one white bar near the top, as in Figure 05-1. This is the title scene. Press Enter. The arena appears with the cyan dot at its top-left corner. Hold the arrow keys and the dot moves exactly as it did in Chapter 04. Close the window with its close button.

The smoke run still proves only start-up and shutdown in this chapter. It reaches the title scene and never presses Enter, so it does not play the game.

NOTE

Nothing about the movement looks different from Chapter 04, and that is the point. What changed is where the code lives. The movement rule now runs in a test with no window, and the host does not change when a rule changes.

The next section is optional. It replaces your files with the chapter 05 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 05 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/05-Scenes-And-The-Gameplay-Simulation"
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/05-Scenes-And-The-Gameplay-Simulation"
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: 19.

Common mistakes ​

  • The window opens and stays black. LoadContent does not call _scenes.Change, or the change was never applied. A change applies only when SceneManager.Update runs, so check that the host Update calls _scenes.Update.
  • Pressing Enter does nothing. TitleScene.Update reads IsConfirmPressed, which is true for one frame. If GetCurrentInput is called twice in a frame, the edge is lost. Check that the host calls it once.
  • SceneManager_Change_TakesEffectAfterUpdate fails with the new scene updated. Update applies the queue before it updates the top scene. Update first, then apply.
  • The build says required member 'Player' must be set. A GameSession was built without a player. Write new GameSession { Player = new Player() }.
  • A test that builds GameServices fails. GameServices needs a real graphics device, and a test has none. Tests build a GameplaySimulation instead, which needs no device.

Conclusion ​

In this chapter, you accomplished the following:

The tests now prove FE-01 in its first form and NFR-03. NFR-05 is met by the shape of the host. In the next chapter, Chapter 06: The Wall Path Service, you replace the rectangle clamp with a path that the player follows around the edge of the unclaimed area.

Test Your Knowledge ​

  1. The movement looks the same as in Chapter 04. What did this chapter buy?

    Answer

    The movement rule now runs in a test with no window, and the host no longer changes when a rule changes. Every later rule is built on that.

  2. Why does SceneManager.Change wait until the current update ends?

    Answer

    Changing the stack during an update can pull a scene out from under its own method. The new scene could also see the same key press that caused the change, and act on it twice.

  3. Why does Tick return events instead of playing sounds itself?

    Answer

    The simulation must not depend on audio or the screen. The scene decides what an event sounds like, and a test can read the events directly.

  4. Why is GameServices an object and not a static class?

    Answer

    A test can build an object with different parts, and each test gets its own. A static class is shared by every test at once, so one test could change what another sees.

Extensions ​

  • Add a test that holds Down for 10 frames from the starting corner and checks that the player's x stays 0 and its y is 50. This shows the clamp does not disturb free movement.
  • Add a second stub scene to SceneManagerTests and call Change twice in one update. Which scene ends up on top, and what happens to the first one? Read ApplyPending to predict the answer before you run it.