Skip to content

Chapter 02 - Arena Model and Game State Foundations ​

Where this chapter fits: the window from chapter 01 gains real state behind it: a tile grid that will own every claim, and a GameSession that gathers the runtime state. The picture on screen does not change, and that is the lesson.

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

Prerequisites ​

Chapter 01 (working MonoGame project, render loop, GameConfig). You should be comfortable with 2D arrays and integer division.

Learning objectives ​

By the end of this chapter you should be able to:

  1. explain why the game needs both continuous world coordinates and a discrete tile grid,
  2. read the screen layout and derive ArenaBounds and the grid size from GameConfig,
  3. implement world-to-grid quantisation with correct clamping and out-of-bounds rejection,
  4. store and query per-tile ownership (TileState) in O(1), and explain the Boundary sentinel,
  5. compute the claimed percentage from tile counts,
  6. assemble a GameSession that gathers the active runtime state, and pass the chapter's 6 tests.

Code anchors ​

  • Source/Data/GameConfig.cs
  • Source/Systems/ArenaSystem.cs
  • Source/Data/Enums.cs
  • Source/Data/ClaimResult.cs, Source/Data/CapturedZone.cs, Source/Entities/Region.cs, Source/Entities/Enemy.cs (data types modelled now, used later)
  • Source/Data/GameSession.cs (the chapter 02 snapshot uses a staged version without later run/upgrade state)
  • Tests/Systems/ArenaSystemTests.cs, Tests/TestHelpers/TestConfigFactory.cs

Why two representations are necessary ​

The game needs both:

  • continuous coordinates (Vector2) for movement and rendering,
  • discrete coordinates (Point tile indexes) for claiming, occupancy checks, and percentage tracking.

Trying to force one representation to do everything is one of the fastest ways to produce a fragile implementation. Movement in pixels is smooth; ownership in pixels is about 510,000 booleans that no algorithm wants to flood fill. Movement in tiles is jerky; ownership in tiles is 31,878 cells that a breadth-first search handles in a millisecond. Use each where it is strong.

The screen layout ​

GameConfig.ArenaBounds is not simply "the window minus a margin". The HUD needs room above and below the arena, so two reserves are subtracted as well:

How ArenaBounds is computed: 50 px margins, a 72 px HUD reserve on top, a 44 px status reserve below

With the defaults, the arena is the rectangle (50, 122, 924 x 552), and at TileSize = 4 the grid is 231 x 138 = 31,878 tiles. Both divisions are exact. If you change the window size, keep the arena width and height divisible by the tile size. Otherwise ArenaSystem silently truncates the last partial row and column.

Core data model ​

The tile grid stores one TileState per tile:

  • TileState.Unclaimed: open field, where enemies roam and trails are drawn,
  • TileState.ClaimedByPlayer: captured territory,
  • TileState.Boundary: never stored in the grid by this chapter's code; it is the value GetTileState returns for coordinates outside the grid, and chapter 06 also uses it for the temporary trail cells during a solve.

This model powers world-to-grid conversion, occupancy checks, claim application, and the claimed percentage.

The code ​

ArenaSystem derives its grid dimensions from the config at construction time. Nothing is hard-coded:

csharp
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];   // per-tile slow-draw flag, used from chapter 08
}

TileState[,] is a rectangular array: every cell starts as the enum's default value, which is Unclaimed because it is declared first. That is a deliberate ordering choice, not luck.

World to grid ​

TryWorldToGrid: floor the offset divided by the tile size, then clamp; positions outside the arena are rejected

The quantisation workhorse is TryWorldToGrid. Note the two distinct concerns: reject positions outside the arena, then clamp the division result so edge positions never index off the grid:

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

Worked example with the test arena (TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4), a 10 x 5 grid at the origin): world (13, 9) becomes floor(13 / 4) = 3 and floor(9 / 4) = 2, so tile (3, 2). World (40, 9) sits exactly on the right edge. 40 / 4 = 10 would be one past the last column, so the clamp folds it back to column 9. World (-1, 5) fails IsWithinBounds and the method returns false.

The Boundary sentinel ​

csharp
public TileState GetTileState(Point gridPoint)
{
    return IsValidGridPoint(gridPoint) ? _grid[gridPoint.X, gridPoint.Y] : TileState.Boundary;
}

Returning Boundary for invalid points instead of throwing lets chapter 04 treat "off the grid" and "claimed" identically. Both are "not playable" when it derives the wall. A sentinel value turns an error case into ordinary data.

Claim application and the percentage ​

Claim application is idempotent per tile, which means a tile is only counted the first time it becomes claimed. That keeps the percentage honest even if a trail tile also sits inside the captured region:

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);
    }
}

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

public float GetClaimedPercentage()
{
    return TotalTileCount == 0 ? 0f : (ClaimedTileCount * 100f) / TotalTileCount;
}

The other helpers are one-liners you will meet constantly:

  • IsUnclaimedWorld(position) and IsClaimedWorld(position) convert a position, then read the tile,
  • GetTileBounds(gridPoint) returns the tile's world rectangle,
  • CloneGrid() returns a copy for speculative solving in chapter 06,
  • EnumerateUnclaimedTiles() lists every unclaimed tile,
  • IsSlowClaimed(gridPoint) returns the per-tile slow-draw flag that ApplyClaimResult records, and chapter 08 uses it to paint slow-drawn claims in a second colour.

The data types modelled now, used later ​

Chapter 02 also adds four small types so that GameSession can be assembled in its final shape. They are worth reading now because they define the contract between the solver (chapter 06) and everything else:

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

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

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

Enemy is a data class with a position, velocity, radius, and (for chapter 07) variant fields; the enemy list in GameSession stays empty until chapter 07.

GameSession (chapter 02 version) ​

The staged chapter 02 GameSession is a deliberately plain state bag. required forces the caller to supply the four references, and init stops anyone from swapping them later:

csharp
public sealed class GameSession
{
    public required Player Player { get; init; }
    public required PlayableWallPath PlayableWallPath { get; set; }
    public required List<CapturedZone> CaptureHistory { get; init; }
    public required List<Enemy> Enemies { get; init; }
    public float ClaimedAreaPercentage { get; set; }
    public float RespawnGraceRemaining { get; set; }
    public string StatusMessage { get; set; } = string.Empty;
    public GameStatus Status { get; set; } = GameStatus.Playing;
}

PlayableWallPath is the one set property: it is replaced as a whole after every claim (chapter 04), never mutated in place.

Complexity ​

Grid lookups are O(1), which is why the course uses the grid for questions like:

  • Is this tile claimed?
  • Is this position unclaimed?
  • What percentage of the arena is owned?

Build it step by step ​

This chapter is copy-along. Step 1 copies the chapter's files from the snapshot, and the steps after it walk through what changed and why. The listings in this chapter show the parts worth studying, not every line.

Step 1 - Copy the chapter files ​

From your LastPerimeter folder, copy the Source and Tests folders from this chapter's snapshot over your own. The command creates any folders you do not have yet and overwrites the files that changed. Replace <course-repo> with the path to your copy of the course repository (the course index explains how to get it).

In PowerShell:

powershell
Copy-Item -Recurse -Force "<course-repo>/DOCUMENTATION/LastPerimeter-Source/02-Arena-Model-And-Game-State-Foundations/Source", "<course-repo>/DOCUMENTATION/LastPerimeter-Source/02-Arena-Model-And-Game-State-Foundations/Tests" .

In bash:

bash
cp -R "<course-repo>/DOCUMENTATION/LastPerimeter-Source/02-Arena-Model-And-Game-State-Foundations/Source" "<course-repo>/DOCUMENTATION/LastPerimeter-Source/02-Arena-Model-And-Game-State-Foundations/Tests" .

That copy brings in these files:

New files:

  • Source/Data/CapturedZone.cs
  • Source/Data/ClaimResult.cs
  • Source/Data/GameSession.cs
  • Source/Entities/Enemy.cs
  • Source/Entities/Region.cs
  • Source/Systems/ArenaSystem.cs
  • Tests/Systems/ArenaSystemTests.cs
  • Tests/TestHelpers/TestConfigFactory.cs

Replaced files (the copy overwrites your versions):

  • Source/Game/LastPerimeterApp.cs

NOTE

Every step after this one describes code that is already in the files you just copied. Open the file each step names and read along. You type nothing unless a step says so.

Step 2 - Read the arena and the data types ​

Open Source/Systems/ArenaSystem.cs and match it against the listings above. Then open the data types Source/Data/ClaimResult.cs, Source/Data/CapturedZone.cs, Source/Entities/Region.cs, and Source/Entities/Enemy.cs, and the staged Source/Data/GameSession.cs.

Step 3 - The game class: LastPerimeterApp (chapter 02 version) ​

Open Source/Game/LastPerimeterApp.cs. The _playableWallPath and _player fields are replaced by private ArenaSystem? _arenaSystem; and private GameSession? _gameSession;. Initialize now builds an ArenaSystem and a GameSession instead of a loose Player:

csharp
protected override void Initialize()
{
    _arenaSystem = new ArenaSystem(_config);
    PlayableWallPath playableWallPath = CreateRectanglePath(_config.ArenaBounds);
    _gameSession = new GameSession
    {
        Player = new Player
        {
            Position = new Vector2(_config.ArenaBounds.Center.X, _config.ArenaBounds.Center.Y),
            Speed = _config.PlayerSpeed,
        },
        PlayableWallPath = playableWallPath,
        CaptureHistory = [],
        Enemies = [],
    };

    base.Initialize();
}

Draw now reads from those two objects: _arenaRenderer.Draw(_spriteBatch, _pixel, _arenaSystem.Bounds, _gameSession.PlayableWallPath) and _playerRenderer.Draw(_spriteBatch, _pixel, _gameSession.Player, _config.PlayerColor).

Step 4 - The test helper and the arena tests ​

Open Tests/TestHelpers/TestConfigFactory.cs and Tests/Systems/ArenaSystemTests.cs. TestConfigFactory is how every test in the course gets a small, predictable arena:

csharp
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,
            PlayerSpeed = 100f,
            MinimumTrailLength = 4f,
        };
    }
}

Zero margins and zero HUD reserves put the arena at the origin, so test coordinates read like grid coordinates times four. The three arena tests check exactly the three behaviours above: mapping and rejection, idempotent counting with the percentage, and the Boundary sentinel.

Step 5 - Build, test, run ​

Run these commands from the LastPerimeter folder:

bash
dotnet build
dotnet test
dotnet run --project Platforms/DesktopVK

dotnet test reports 6 passing tests. On Windows you can also run dotnet run --project Platforms/WindowsDX12.

Chapter snapshot ​

The matching buildable project is DOCUMENTATION/LastPerimeter-Source/02-Arena-Model-And-Game-State-Foundations; build and test it standalone with dotnet build and dotnet test. This chapter adds Tests/Systems/ArenaSystemTests.cs (world-to-grid mapping, idempotent claim counting, boundary behaviour for invalid grid points) alongside chapter 01's launch-option tests: dotnet test should report 6 passing tests.

Checkpoint ​

  1. In your LastPerimeter folder, run dotnet test: 6 tests pass. If yours differ, compare your files with the snapshot in DOCUMENTATION/LastPerimeter-Source/02-Arena-Model-And-Game-State-Foundations.
  2. Run dotnet run --project Platforms/DesktopVK and confirm the window still shows the arena frame and the player dot exactly as in chapter 01. No key moves anything yet. Press Escape to close it. The staged chapter 02 app now builds an ArenaSystem and a GameSession, so the visible result is unchanged but the state behind it is real (a good lesson in itself).
  3. Explain, without notes, why GetTileState returns TileState.Boundary for invalid grid points instead of throwing.
  4. Open Source/Data/GameConfig.cs and change the TileSize default from 4 to 8. Then open Source/Game/LastPerimeterApp.cs and, in Initialize, add Console.WriteLine($"{_arenaSystem.GridWidth} x {_arenaSystem.GridHeight} = {_arenaSystem.TotalTileCount}"); on the line before base.Initialize();. Predict the three numbers, run the game, and read them in the terminal. Then change TileSize back to 4 and delete the line you added.

What you should have now ​

You now have:

  • screen and arena sizing,
  • tile storage,
  • helper methods for bounds checks,
  • claimed percentage calculation,
  • a GameSession that gathers the active runtime state.

Common mistakes ​

  • indexing _grid[y, x] instead of _grid[x, y] (the array is width-major in this project),
  • forgetting the clamp and indexing off the grid for positions on the right or bottom edge,
  • storing claim state in pixels, or in the trail, or in the wall path, instead of in one grid,
  • counting a tile twice when a trail tile is also inside the captured region.

Questions to think about ​

Ask yourself: If the player moves in pixels, why not store claimed territory in pixels too? The intended answer is about algorithm clarity, cost, and tractable state updates.