Skip to content

Chapter 03: The Service Pattern and the Arena ​

In Chapter 02: Drawing from One Pixel, you drew the arena outline and the player dot from a single white pixel. The arena rectangle was typed straight into the host as new Rectangle(50, 122, 924, 552). Nothing in the game yet knows what that rectangle means, or which parts of it belong to the player.

In this chapter, you build the first real service, ArenaSystem, which turns that rectangle into a grid of tiles. You also learn the rhythm that every later chapter repeats: contract card, stub, test, body, explanation.

Figure 03-1: The chapter 03 window. It looks the same as chapter 02, but the arena rectangle now comes from GameConfig
Figure 03-1: The chapter 03 window. It looks the same as chapter 02, but the arena rectangle now comes from GameConfig. This is a drawn illustration, not a screenshot.

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

In this chapter, you will:

  • Learn what this course means by a service, an operation and a contract.
  • Write GameConfig, the one record that holds every tuning number.
  • Build ArenaSystem one operation at a time, writing each test before its body.
  • Learn why the grid answers Boundary for a point outside it instead of throwing.
  • Add the data types that the capture solver will produce in Chapter 09.

Requirements in this chapter ​

IDShort name
ARN-01Arena layout inside the screen
ARN-024 px tile grid, 231 x 138
ARN-03Three tile states
ARN-04World to grid, with rejection outside
ARN-05Outside the grid reads as Boundary
ARN-06Claims counted once, claimed percentage
ARN-07Slow-draw flag per tile

What a service is ​

The course uses three words in a fixed sense. A service is a sealed class that owns one kind of truth about the game and offers operations on it. ArenaSystem owns the grid of tiles. A service never refers to MonoGame's Game class or to the graphics device, so a test can create one with a single line and no window. The code keeps the System suffix for services, so the class is ArenaSystem and not ArenaService.

An operation is a public method of a service. Each operation has a contract, which says what it takes, what it gives back, what it promises and what it refuses. A service receives its dependencies through its constructor, so nothing reaches out to a global. This is what makes the rules testable in isolation, and it is why most chapters of this course change nothing you can see. The proof is the test run.

The contract card ​

Before you write any operation, the chapter shows a contract card. The card has four lines plus the requirement IDs. Takes lists the inputs. Gives names the result. Promises states what is always true when the operation succeeds. Refuses states what the operation will not do, and how it says no. If an operation needs more than four lines to describe, it is probably two operations.

Each promise and each refusal on a card is a claim that the game relies on. A test that checks one claim turns it from a hope into a fact. You will meet a card for every operation in this chapter, and the same format returns in every later chapter.

Why tests come first ​

It is tempting to draw everything to the screen and judge the result by eye. That works until a rule fails silently, for example a claim counted twice, because the picture still looks plausible. Visuals lie. A test compares a number with the number you promised, and a picture that merely looks right cannot fool it.

A test that has never failed has never proved anything, so this course makes every test fail first. A method that throws NotImplementedException is a stub. A stub keeps the project compiling while the test goes red, so you see a failure for the right reason and not a page of compiler errors. You then write the body and watch the test go green.

The screen layout ​

The window is 1024 by 768 pixels. The arena does not fill it. A 50 pixel margin runs round every side. At the top, 72 pixels are reserved for the heads-up display, or HUD, which later shows score and lives. At the bottom, 44 pixels are reserved for a status line. Figure 03-2 shows the sums. The arena rectangle that remains starts at (50, 122) and measures 924 by 552.

Figure 03-2: How the arena bounds are computed from the screen size, the margin and the HUD reserves
Figure 03-2: How the arena bounds are computed from the screen size, the margin and the HUD reserves

World to grid ​

The game stores claimed ground as a grid of 4 pixel tiles. The arena is 924 by 552 pixels, so the grid is 231 by 138 tiles, which is 31,878 tiles in total. A position on screen is a world position, measured in pixels. A tile is addressed by a grid point, which is a column and a row. Converting one to the other has three steps. Subtract the arena's top-left corner, divide by the tile size and round down, then clamp the result to the grid.

The clamp matters on the right and bottom edges. The arena edge at x = 974 is inside the arena, but (974 - 50) / 4 is 231. Column 231 does not exist, because the columns run from 0 to 230. Without the clamp, a player on the right wall would be told they were off the grid. Figure 03-3 shows both cases.

Figure 03-3: World to grid. Floor the offset divided by the tile size, then clamp. Positions outside the arena are rejected
Figure 03-3: World to grid. Floor the offset divided by the tile size, then clamp. Positions outside the arena are rejected

The Boundary sentinel ​

A tile is in exactly one of three states: Unclaimed, ClaimedByPlayer or Boundary. The third state is never stored in the grid. It is the answer the grid gives for any point that is not on it. A value that stands in for "no real answer" is called a sentinel.

The reason is the wall rebuild in Chapter 06: The Wall Path Service. To find the walls, that code asks about every neighbour of every unclaimed tile, and some neighbours lie off the grid. If GetTileState threw an exception for those points, every caller would need its own bounds check. Answering Boundary makes the edge of the grid behave like a wall, with no special case.

Setting up the data ​

The service needs a few plain data types first. A plain data type holds values and has no behaviour of its own. You also need a helper that builds a small arena for tests. The first step is to create the folders.

Open a terminal in the LastPerimeter folder, the project folder you created in Chapter 01. Run each of the following commands from there, one at a time. The Source/Entities folder already exists from Chapter 02.

text
mkdir Source/Data
mkdir Source/Systems
mkdir Tests/Systems
mkdir Tests/TestHelpers

In the Source/Data folder, create a new file named Enums.cs and add the following code. It holds three enums. Direction and TrailState are not used until later chapters, but they live beside TileState, so you add all three now.

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

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

public enum TrailState
{
    InProgress,
    Completed,
    Cancelled,
}

public enum TileState
{
    Unclaimed,
    ClaimedByPlayer,
    Boundary,
}

In the Source/Data folder, create a new file named GameConfig.cs and add the following code. A record is a class that is compared by its values. Each property has an init setter, which means a value can be set when the object is created and never changed afterwards. New to init? See the C# primer. The one calculated property, ArenaBounds, applies the layout from Figure 03-2. It uses =>. New to expression-bodied members? See the C# primer.

new-file Source/Data/GameConfig.cs
csharp
using Microsoft.Xna.Framework;

namespace LastPerimeter.Data;

// Every tuning number lives here, so a test can build a small arena with the same code.
public sealed record GameConfig
{
    public int ScreenWidth { get; init; } = 1024;
    public int ScreenHeight { get; init; } = 768;
    public int ArenaMargin { get; init; } = 50;
    public int HudTopReserve { get; init; } = 72;
    public int HudBottomReserve { get; init; } = 44;
    public int TileSize { get; init; } = 4;

    public Rectangle ArenaBounds => new(
        ArenaMargin,
        ArenaMargin + HudTopReserve,
        ScreenWidth - (ArenaMargin * 2),
        ScreenHeight - (ArenaMargin * 2) - HudTopReserve - HudBottomReserve);
}

The key things to note are:

  • GameConfig holds every tuning number in one place. Later chapters add more properties to it.
  • Every property has a default that matches the real game, so new GameConfig() is the real layout.
  • A test can change the properties with an object initialiser and get a small arena built with the same code.

In the Source/Entities folder, create a new file named Region.cs and add the following code. A region is a group of tiles. Chapter 09 uses it for the areas the capture solver finds.

new-file Source/Entities/Region.cs
csharp
using Microsoft.Xna.Framework;

namespace LastPerimeter.Entities;

public sealed class Region
{
    public List<Point> Tiles { get; } = new();
    public int TileCount => Tiles.Count;
}

In the Source/Data folder, create a new file named ClaimResult.cs and add the following code. It describes the outcome of a capture: the region the player won, the region that remains, the tiles under the trail, and the enemies that the capture removed.

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

namespace LastPerimeter.Data;

public sealed record ClaimResult(
    Region CapturedRegion,
    Region RemainingPlayableRegion,
    IReadOnlyList<Point> TrailTiles,
    IReadOnlyList<int>? EliminatedEnemyIndexes = null);

In the Source/Data folder, create a new file named CapturedZone.cs and add the following code. Nothing uses it in this chapter. It records one captured area for the scoring and the replay of Chapter 09, and creating it now keeps the data folder complete.

new-file Source/Data/CapturedZone.cs
csharp
using Microsoft.Xna.Framework;

namespace LastPerimeter.Data;

public sealed record CapturedZone(
    int Order,
    IReadOnlyList<Point> Tiles,
    bool IsSlowDraw);

In the Tests/TestHelpers folder, create a new file named TestConfigFactory.cs and add the following code. Tests use a small arena, 40 by 20 pixels with no margin, because a 10 by 5 grid is small enough to check by hand. The real arena has 31,878 tiles, which no one can check by eye.

new-file Tests/TestHelpers/TestConfigFactory.cs
csharp
using LastPerimeter.Data;

namespace LastPerimeter.Tests.TestHelpers;

internal static class TestConfigFactory
{
    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,
        };
    }
}

Building the arena service ​

Your first listing here is the whole shell of ArenaSystem. It declares every operation of this chapter and makes each one throw. The constructor and the properties are written in full, because every test needs a built arena before it can ask a question. This is the one place the five-step rhythm bends. The tests for the constructor come at the end of the chapter, and they pass the first time you run them.

In the Source/Systems folder, create a new file named ArenaSystem.cs and add the following code. The grid is a TileState[,], a table with a width and a height. New to two-dimensional arrays? See the C# primer.

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

namespace LastPerimeter.Systems;

public sealed class ArenaSystem
{
    private readonly TileState[,] _grid;
    private readonly bool[,] _slowClaimed;

    public ArenaSystem(GameConfig config)
    {
        Bounds = config.ArenaBounds;
        GridWidth = Bounds.Width / config.TileSize;
        GridHeight = Bounds.Height / config.TileSize;
        TileSize = config.TileSize;
        _grid = new TileState[GridWidth, GridHeight];
        _slowClaimed = new bool[GridWidth, GridHeight];
    }

    public Rectangle Bounds { get; }
    public int GridWidth { get; }
    public int GridHeight { get; }
    public int TileSize { get; }
    public int ClaimedTileCount { get; private set; }
    public int TotalTileCount => GridWidth * GridHeight;

    public TileState GetTileState(Point gridPoint)
    {
        throw new NotImplementedException();
    }

    public TileState[,] CloneGrid()
    {
        throw new NotImplementedException();
    }

    public bool IsValidGridPoint(Point point)
    {
        throw new NotImplementedException();
    }

    public bool IsWithinBounds(Vector2 position)
    {
        throw new NotImplementedException();
    }

    public bool TryWorldToGrid(Vector2 position, out Point gridPoint)
    {
        throw new NotImplementedException();
    }

    public Rectangle GetTileBounds(Point gridPoint)
    {
        throw new NotImplementedException();
    }

    public bool IsUnclaimedWorld(Vector2 position)
    {
        throw new NotImplementedException();
    }

    public bool IsClaimedWorld(Vector2 position)
    {
        throw new NotImplementedException();
    }

    public bool IsSlowClaimed(Point gridPoint)
    {
        throw new NotImplementedException();
    }

    public void ApplyClaimResult(ClaimResult claimResult, bool slowDraw = false)
    {
        throw new NotImplementedException();
    }

    public float GetClaimedPercentage()
    {
        throw new NotImplementedException();
    }
}

The key things to note are:

  • The class is sealed, and the only thing it needs is a GameConfig.
  • _grid holds one TileState per tile. _slowClaimed holds one flag per tile, which you use in the last step of this chapter.
  • The constructor divides the arena size by the tile size, so a 924 by 552 arena with 4 pixel tiles gives 231 by 138 tiles.
  • A new array of an enum is filled with the first enum value, which is Unclaimed. That is why a new arena has no claimed tiles.
  • Every other operation throws NotImplementedException. From the LastPerimeter folder, run dotnet build. The build should succeed, which proves the stubs compile.

You now build the operations in groups, each with its tests first. The tests live in one file, and the order of the tests in that file follows the order you write them.

Finding a tile from a position ​

IsWithinBounds and TryWorldToGrid answer the question "which tile is this pixel on?". Here are the cards.

ArenaSystem.IsWithinBounds(position) : bool

  • Takes: a world position.
  • Gives: true when the position is inside the arena.
  • Promises: the arena edges count as inside.
  • Refuses: nothing. A position outside gives false.
  • Requirements: ARN-04.

ArenaSystem.TryWorldToGrid(position, out gridPoint) : bool

  • Takes: a world position.
  • Gives: true and the grid point of the tile that contains the position.
  • Promises: a position inside the arena maps to one tile, clamped to the grid.
  • Refuses: a position outside the arena returns false.
  • Requirements: ARN-04.

The stubs are already in your file, so you move straight to the test. In the Tests/Systems folder, create a new file named ArenaSystemTests.cs and add the following code. It starts with a single test. It checks the origin, an interior point, and two points just outside the arena.

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

namespace LastPerimeter.Tests.Systems;

public sealed class ArenaSystemTests
{
    [Fact]
    public void TryWorldToGrid_MapsPositionsInsideBounds_AndRejectsOutside()
    {
        ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));

        Assert.True(arena.TryWorldToGrid(new Vector2(0, 0), out Point origin));
        Assert.Equal(new Point(0, 0), origin);

        Assert.True(arena.TryWorldToGrid(new Vector2(13, 9), out Point interior));
        Assert.Equal(new Point(3, 2), interior);

        Assert.False(arena.TryWorldToGrid(new Vector2(-1, 5), out _));
        Assert.False(arena.TryWorldToGrid(new Vector2(5, 21), out _));
    }
}

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 3. The three passes are tests from earlier chapters. The one failure is your new test, which hit the NotImplementedException in the stub.

Now write the bodies. Open Source/Systems/ArenaSystem.cs, find the IsWithinBounds method and replace the whole method with the following:

replace-method Source/Systems/ArenaSystem.cs IsWithinBounds
csharp
    public bool IsWithinBounds(Vector2 position)
    {
        return position.X >= Bounds.Left && position.X <= Bounds.Right && position.Y >= Bounds.Top && position.Y <= Bounds.Bottom;
    }

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

replace-method Source/Systems/ArenaSystem.cs TryWorldToGrid
csharp
    public bool TryWorldToGrid(Vector2 position, out Point gridPoint)
    {
        if (!IsWithinBounds(position))
        {
            gridPoint = default;
            return false;
        }

        int x = Math.Clamp((int)((position.X - Bounds.Left) / TileSize), 0, GridWidth - 1);
        int y = Math.Clamp((int)((position.Y - Bounds.Top) / TileSize), 0, GridHeight - 1);
        gridPoint = new Point(x, y);
        return true;
    }

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

The key things to note are:

  • IsWithinBounds uses <= on the right and bottom edges, so a position exactly on the arena edge is inside.
  • TryWorldToGrid rejects first, and only then converts. A rejected call sets gridPoint to default, because an out parameter must always be given a value.
  • The cast to int drops the fraction, which rounds down for positions that are not negative.
  • Math.Clamp pulls an edge position back onto the last column or row, as Figure 03-3 shows.

Claiming tiles ​

A claim is how the player gains ground. ApplyClaimResult takes the result of a capture and marks its tiles. The two query operations IsClaimedWorld and IsUnclaimedWorld let a test, and later the player and the enemies, ask what state a pixel is in. GetClaimedPercentage turns the count into the number the HUD will show.

ArenaSystem.IsUnclaimedWorld(position) and IsClaimedWorld(position) : bool

  • Takes: a world position.
  • Gives: true when the tile under the position is Unclaimed, or ClaimedByPlayer.
  • Promises: each one combines TryWorldToGrid with a lookup in the grid.
  • Refuses: a position outside the arena is neither, so both return false.
  • Requirements: ENM-02, TRL-05.

ArenaSystem.ApplyClaimResult(claimResult, slowDraw) : void

  • Takes: a claim result and whether the trail was drawn slowly.
  • Gives: nothing. The arena changes.
  • Promises: the tiles of the captured region and of the trail become claimed. Each tile is counted once.
  • Refuses: nothing. A tile that is already claimed stays claimed and is not counted again.
  • Requirements: ARN-06, CAP-06.

ArenaSystem.GetClaimedPercentage() : float

  • Takes: nothing.
  • Gives: the claimed tiles as a percentage of all tiles, from 0 to 100.
  • Promises: the result is ClaimedTileCount * 100 / TotalTileCount.
  • Refuses: an empty grid gives 0, never a division by zero.
  • Requirements: ARN-06.

Open Tests/Systems/ArenaSystemTests.cs. Add the following test to the ArenaSystemTests class, below the TryWorldToGrid_MapsPositionsInsideBounds_AndRejectsOutside test. The trail tile (1, 0) overlaps the captured region on purpose, so the test proves that an overlap is counted once.

add-member Tests/Systems/ArenaSystemTests.cs after=TryWorldToGrid_MapsPositionsInsideBounds_AndRejectsOutside
csharp
    [Fact]
    public void ApplyClaimResult_CountsEachTileOnce_AndUpdatesPercentage()
    {
        ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));

        Region captured = new();
        captured.Tiles.AddRange([new Point(0, 0), new Point(1, 0)]);
        ClaimResult claim = new(captured, new Region(), [new Point(1, 0), new Point(2, 0)]);

        arena.ApplyClaimResult(claim);

        // 3 distinct tiles out of a 10x5 grid; the overlapping tile counts once.
        Assert.Equal(3, arena.ClaimedTileCount);
        Assert.Equal(6f, arena.GetClaimedPercentage(), precision: 2);
        Assert.True(arena.IsClaimedWorld(new Vector2(2, 2)));
        Assert.True(arena.IsUnclaimedWorld(new Vector2(14, 2)));
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 4. The new test fails on the stubs.

Open Source/Systems/ArenaSystem.cs. Find the IsUnclaimedWorld method and replace the whole method with the following:

replace-method Source/Systems/ArenaSystem.cs IsUnclaimedWorld
csharp
    public bool IsUnclaimedWorld(Vector2 position)
    {
        return TryWorldToGrid(position, out Point gridPoint) && _grid[gridPoint.X, gridPoint.Y] == TileState.Unclaimed;
    }

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

replace-method Source/Systems/ArenaSystem.cs IsClaimedWorld
csharp
    public bool IsClaimedWorld(Vector2 position)
    {
        return TryWorldToGrid(position, out Point gridPoint) && _grid[gridPoint.X, gridPoint.Y] == TileState.ClaimedByPlayer;
    }

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

replace-method Source/Systems/ArenaSystem.cs ApplyClaimResult
csharp
    public void ApplyClaimResult(ClaimResult claimResult, bool slowDraw = false)
    {
        foreach (Point tile in claimResult.CapturedRegion.Tiles)
        {
            ClaimTile(tile, slowDraw);
        }

        foreach (Point tile in claimResult.TrailTiles)
        {
            ClaimTile(tile, slowDraw);
        }
    }

Add the following method to the ArenaSystem class, below the ApplyClaimResult method. It is a private helper, so it has no card of its own:

add-member Source/Systems/ArenaSystem.cs after=ApplyClaimResult
csharp
    private void ClaimTile(Point tile, bool slowDraw)
    {
        if (_grid[tile.X, tile.Y] != TileState.ClaimedByPlayer)
        {
            _grid[tile.X, tile.Y] = TileState.ClaimedByPlayer;
            ClaimedTileCount++;
        }

        _slowClaimed[tile.X, tile.Y] = slowDraw;
    }

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

replace-method Source/Systems/ArenaSystem.cs GetClaimedPercentage
csharp
    public float GetClaimedPercentage()
    {
        return TotalTileCount == 0 ? 0f : (ClaimedTileCount * 100f) / TotalTileCount;
    }

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

The key things to note are:

  • && stops at the first false, so IsUnclaimedWorld only reads the grid when TryWorldToGrid succeeded. The array is never indexed with a bad point.
  • ClaimTile checks the state before it adds to ClaimedTileCount. This is the line that makes an overlapping tile count once. Without it, the 3 tiles in the test would count as 4.
  • ClaimTile records the slow flag on every claim, even for a tile that was already claimed. The flag always describes the latest claim.
  • GetClaimedPercentage multiplies by 100f before it divides. Dividing two integers first would round the result down to 0.

Asking about a grid point ​

The next group answers the question "what is on this tile?" for a grid point, including points that are not on the grid.

ArenaSystem.IsValidGridPoint(point) : bool

  • Takes: a grid point.
  • Gives: true only when the point is inside the grid.
  • Promises: columns run from 0 to GridWidth - 1 and rows from 0 to GridHeight - 1.
  • Refuses: nothing. A negative or too large point gives false.
  • Requirements: ARN-05.

ArenaSystem.GetTileState(gridPoint) : TileState

  • Takes: a grid point.
  • Gives: the state of that tile.
  • Promises: a point outside the grid reads as Boundary.
  • Refuses: it never throws, so callers need no bounds check of their own.
  • Requirements: ARN-05.

Open Tests/Systems/ArenaSystemTests.cs. Add the following test to the ArenaSystemTests class, below the ApplyClaimResult_CountsEachTileOnce_AndUpdatesPercentage test:

add-member Tests/Systems/ArenaSystemTests.cs after=ApplyClaimResult_CountsEachTileOnce_AndUpdatesPercentage
csharp
    [Fact]
    public void GetTileState_ReturnsBoundary_ForInvalidGridPoints()
    {
        ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));

        Assert.Equal(TileState.Boundary, arena.GetTileState(new Point(-1, 0)));
        Assert.Equal(TileState.Boundary, arena.GetTileState(new Point(0, 99)));
        Assert.Equal(TileState.Unclaimed, arena.GetTileState(new Point(0, 0)));
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 1 and Passed: 5. Now open Source/Systems/ArenaSystem.cs, find the IsValidGridPoint method and replace the whole method with the following:

replace-method Source/Systems/ArenaSystem.cs IsValidGridPoint
csharp
    public bool IsValidGridPoint(Point point)
    {
        return point.X >= 0 && point.X < GridWidth && point.Y >= 0 && point.Y < GridHeight;
    }

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

replace-method Source/Systems/ArenaSystem.cs GetTileState
csharp
    public TileState GetTileState(Point gridPoint)
    {
        return IsValidGridPoint(gridPoint) ? _grid[gridPoint.X, gridPoint.Y] : TileState.Boundary;
    }

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

The key things to note are:

  • IsValidGridPoint is the single place that knows the shape of the grid. GetTileState, IsSlowClaimed and later chapters all rely on it.
  • GetTileState checks the point before it indexes the array. The array itself would throw an exception for a bad index, and the check turns that into Boundary.
  • The test asks about (-1, 0) and (0, 99), which are off the left edge and below the bottom edge, and about (0, 0) as a control.

Two more operations need no test of their own in this chapter. GetTileBounds gives the screen rectangle of a tile, and a later renderer uses it. CloneGrid gives the solver a copy to work on, and Chapter 09 tests it through the solver. Both are short, so you write the bodies straight away.

ArenaSystem.GetTileBounds(gridPoint) : Rectangle takes a grid point and gives the tile's rectangle on screen, which is TileSize pixels square. Requirements: ARN-02.

ArenaSystem.CloneGrid() : TileState[,] takes nothing and gives an independent copy of the grid. Changing the copy never changes the arena. Requirements: CAP-01.

In Source/Systems/ArenaSystem.cs, find the GetTileBounds method and replace the whole method with the following:

replace-method Source/Systems/ArenaSystem.cs GetTileBounds
csharp
    public Rectangle GetTileBounds(Point gridPoint)
    {
        return new Rectangle(Bounds.Left + (gridPoint.X * TileSize), Bounds.Top + (gridPoint.Y * TileSize), TileSize, TileSize);
    }

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

replace-method Source/Systems/ArenaSystem.cs CloneGrid
csharp
    public TileState[,] CloneGrid()
    {
        return (TileState[,])_grid.Clone();
    }

The key things to note are:

  • A tile's rectangle is the arena's top-left corner plus the grid point times the tile size. This is the reverse of TryWorldToGrid.
  • Array.Clone makes a shallow copy. That is enough here, because the elements are enum values and not objects.

Checking the shape ​

Three tests check the shape of the arena itself. Each one passes the first time you run it, because the constructor and GameConfig are already written. A tip below shows you how to make one of them fail.

Open Tests/Systems/ArenaSystemTests.cs. Add the following test to the ArenaSystemTests class, below the GetTileState_ReturnsBoundary_ForInvalidGridPoints test. It checks that the real layout gives the rectangle in Figure 03-2.

add-member Tests/Systems/ArenaSystemTests.cs after=GetTileState_ReturnsBoundary_ForInvalidGridPoints
csharp
    [Fact]
    public void ArenaBounds_LeavesMarginAndHudReserves()
    {
        GameConfig config = new();

        Assert.Equal(new Rectangle(50, 122, 924, 552), config.ArenaBounds);
    }

Add the following test below the ArenaBounds_LeavesMarginAndHudReserves test. It checks that a 40 by 20 arena with 4 pixel tiles gives a 10 by 5 grid of 50 tiles.

add-member Tests/Systems/ArenaSystemTests.cs after=ArenaBounds_LeavesMarginAndHudReserves
csharp
    [Fact]
    public void Constructor_SizesGridFromBoundsAndTileSize()
    {
        ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));

        Assert.Equal(10, arena.GridWidth);
        Assert.Equal(5, arena.GridHeight);
        Assert.Equal(50, arena.TotalTileCount);
    }

Add the following test below the Constructor_SizesGridFromBoundsAndTileSize test. It visits every tile of a new arena and checks that none is claimed.

add-member Tests/Systems/ArenaSystemTests.cs after=Constructor_SizesGridFromBoundsAndTileSize
csharp
    [Fact]
    public void NewArena_HasEveryTileUnclaimed()
    {
        ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));

        Assert.Equal(0, arena.ClaimedTileCount);
        for (int x = 0; x < arena.GridWidth; x++)
        {
            for (int y = 0; y < arena.GridHeight; y++)
            {
                Assert.Equal(TileState.Unclaimed, arena.GetTileState(new Point(x, y)));
            }
        }
    }

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

TIP

To see a shape test fail, open Source/Systems/ArenaSystem.cs and change Bounds.Width / config.TileSize to Bounds.Width / 2. Run dotnet test, and Constructor_SizesGridFromBoundsAndTileSize fails. Change the line back and run the tests again before you go on.

Recording slow draw ​

The player can draw a trail slowly for a score bonus, which Chapter 12 adds up. The grid must remember, per tile, whether the claim was slow. That memory is the _slowClaimed array, and IsSlowClaimed reads it.

ArenaSystem.IsSlowClaimed(gridPoint) : bool

  • Takes: a grid point.
  • Gives: true when the tile was last claimed with slowDraw: true.
  • Promises: a tile claimed without slow draw gives false.
  • Refuses: a point outside the grid gives false.
  • Requirements: ARN-07.

Open Tests/Systems/ArenaSystemTests.cs. Add the following test to the ArenaSystemTests class, below the NewArena_HasEveryTileUnclaimed test. It makes one slow claim and one normal claim, then checks a tile from each, a trail tile and a tile off the grid.

add-member Tests/Systems/ArenaSystemTests.cs after=NewArena_HasEveryTileUnclaimed
csharp
    [Fact]
    public void ApplyClaimResult_RecordsSlowDrawPerTile()
    {
        ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));
        Region slowRegion = new();
        slowRegion.Tiles.Add(new Point(1, 1));
        Region fastRegion = new();
        fastRegion.Tiles.Add(new Point(3, 3));

        arena.ApplyClaimResult(new ClaimResult(slowRegion, new Region(), [new Point(2, 2)]), slowDraw: true);
        arena.ApplyClaimResult(new ClaimResult(fastRegion, new Region(), []), slowDraw: false);

        Assert.True(arena.IsSlowClaimed(new Point(1, 1)));
        Assert.True(arena.IsSlowClaimed(new Point(2, 2)));
        Assert.False(arena.IsSlowClaimed(new Point(3, 3)));
        Assert.False(arena.IsSlowClaimed(new Point(-1, 0)));
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 1 and Passed: 9. In Source/Systems/ArenaSystem.cs, find the IsSlowClaimed method and replace the whole method with the following:

replace-method Source/Systems/ArenaSystem.cs IsSlowClaimed
csharp
    public bool IsSlowClaimed(Point gridPoint)
    {
        return IsValidGridPoint(gridPoint) && _slowClaimed[gridPoint.X, gridPoint.Y];
    }

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

The key things to note are:

  • IsValidGridPoint comes first in the &&, so a point off the grid returns false before the array is read.
  • The test makes two claims, and the second does not touch the tiles of the first. This shows that the flag belongs to the tile and not to the arena.

Wiring it into the game ​

The arena service does not appear on screen yet, because the player and the renderer do not use tiles until later chapters. What changes now is the host: it reads the arena rectangle from GameConfig instead of a typed number.

Open Source/Game/LastPerimeterApp.cs. At the top of the file, add the following line below the using Microsoft.Xna.Framework.Graphics; line:

add-using Source/Game/LastPerimeterApp.cs after=Microsoft.Xna.Framework.Graphics
csharp
using LastPerimeter.Data;

Add the following field to the LastPerimeterApp class, below the _launchOptions field. It holds one GameConfig, which supplies the arena rectangle.

add-member Source/Game/LastPerimeterApp.cs after=_launchOptions
csharp
    private readonly GameConfig _config = new();

In the Draw method of Source/Game/LastPerimeterApp.cs, find this line:

find Source/Game/LastPerimeterApp.cs type=LastPerimeterApp
csharp
            _arenaRenderer.Draw(_spriteBatch, _pixel, new Rectangle(50, 122, 924, 552));

Replace it with the following line, so that the arena rectangle comes from the config and not from typed numbers:

csharp
            _arenaRenderer.Draw(_spriteBatch, _pixel, _config.ArenaBounds);

The key changes are:

  • using LastPerimeter.Data; is new, below the using Microsoft.Xna.Framework.Graphics; line.
  • A _config field holds a GameConfig, below the _launchOptions field.
  • In Draw, the call to _arenaRenderer.Draw passes _config.ArenaBounds instead of new Rectangle(50, 122, 924, 552).

Running the tests ​

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 10. The 10 tests are the 3 from earlier chapters and the 7 in ArenaSystemTests.

TestProves
ArenaBounds_LeavesMarginAndHudReservesARN-01
Constructor_SizesGridFromBoundsAndTileSizeARN-02
NewArena_HasEveryTileUnclaimedARN-03
TryWorldToGrid_MapsPositionsInsideBounds_AndRejectsOutsideARN-04
GetTileState_ReturnsBoundary_ForInvalidGridPointsARN-05
ApplyClaimResult_CountsEachTileOnce_AndUpdatesPercentageARN-06
ApplyClaimResult_RecordsSlowDrawPerTileARN-07

Running the game ​

The arena rules are proved by the test count above. Only the picture needs a window and a screen.

From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. A window opens. It shows a light grey rectangle 50 pixels in from the sides, with space above and below it, and a cyan dot at its top-left corner, as in Figure 03-1. It looks the same as it did in Chapter 02. The rectangle now comes from GameConfig, and the numbers are the same. Close the window with its close button.

The next section is optional. It replaces your files with the chapter 03 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 03 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/03-The-Service-Pattern-And-The-Arena"
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/03-The-Service-Pattern-And-The-Arena"
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: 10.

Common mistakes ​

  • A NotImplementedException in the final test run. You left a stub in ArenaSystem.cs. Search the file for throw new NotImplementedException(); and replace that method.
  • Constructor_SizesGridFromBoundsAndTileSize fails with a width of 5 or 20. The constructor divides by the wrong value. Check that the width is divided by config.TileSize.
  • The claimed count is one too high. ClaimTile lost its if check, so the overlapping tile is counted twice.
  • TryWorldToGrid rejects a point on the right wall. The comparison in IsWithinBounds uses < instead of <=, or the Math.Clamp calls are missing.
  • The build says Region is not found. Region.cs is in the wrong folder, or the file has the wrong namespace. It belongs in Source/Entities.

Conclusion ​

In this chapter, you accomplished the following:

The tests now prove ARN-01 to ARN-07. In the next chapter, Chapter 04: Input and Frame Time, you read the keyboard once per frame and move the dot at the same speed on every machine.

Test Your Knowledge ​

  1. What does GetTileState return for the point (-1, 0), and why does it not throw?

    Answer

    It returns Boundary. The wall rebuild in Chapter 06 asks about every neighbour of every tile, including neighbours off the grid. Off the grid must behave like a wall, so the answer is a value and not an error.

  2. Why does ClaimTile check the tile's state before it adds to ClaimedTileCount?

    Answer

    The trail's tiles can overlap tiles that are already claimed. Counting them twice would push the percentage above the true share of the arena.

  3. Why do you write the test before the body of an operation?

    Answer

    A test that has never failed has never proved anything. Seeing it fail shows that it checks the right thing, and the stub makes the failure a clean one.

  4. Why does TryWorldToGrid clamp the tile index when the position is already inside the arena?

    Answer

    A position exactly on the right or bottom edge divides to one past the last column or row. The clamp pulls it back onto the last tile, so a player standing on the edge still has a tile.

Extensions ​

  • Change TileSize in GameConfig to 8 and run dotnet test. No test fails. Ask yourself why. Every arena test builds its own arena with a 4 pixel tile through TestConfigFactory, so none of them reads the default. Write a test that builds an ArenaSystem from new GameConfig() and checks the grid size that the default tile size gives. Run it with a tile size of 4 and then 8, and see it fail for 8.
  • Add a test that calls CloneGrid, claims a tile in the arena, and checks that the clone still reads Unclaimed. This proves the copy is independent.