Skip to content

Chapter 09: The Capture Service ​

In Chapter 08: The Fuse Service, you added the pressure that makes the player keep moving. A trail that reaches the wall again still does nothing. It ends, and the arena stays exactly as it was.

In this chapter, you build the capture solver. When a trail closes, the solver works out which part of the arena the player has won, and the game fills it in. This is the hardest chapter of the course and the moment the game becomes a game, so it goes slowly and it splits the solver into stages.

Figure 09-1: The chapter 09 window. Two captures are filled in, one blue and one orange, and the wall now runs round them
Figure 09-1: The chapter 09 window. Two captures are filled in, one blue and one orange, and the wall now runs round them. This is a drawn illustration, not a screenshot.

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

In this chapter, you will:

  • Learn the capture lifecycle, from a completed trail to a rebuilt wall.
  • Rasterise a trail onto the grid with Bresenham line stepping.
  • Find regions with a breadth-first flood fill, and learn what it costs.
  • Add the partition guard and learn which bug it prevents.
  • Select a region with an ordered list of rules.
  • Write ResolveCapture, the first operation of the simulation that has several stages.
  • Draw the claimed area from a cached render target, rebuilt outside the sprite batch.

Requirements in this chapter ​

IDShort name
CAP-01Rasterise the trail and solve on a copy
CAP-02Split the space into regions
CAP-03A trail that splits nothing claims nothing
CAP-04Claim the smallest enemy-free region
CAP-05Otherwise claim the smallest region and list its enemies
CAP-06Applying a claim marks tiles as claimed
CAP-07Record each capture in order
CAP-08A rejected loop returns the player to the anchor
CAP-09Selection rules are an ordered list
CAP-10Solving fits in a frame (timed in Chapter 13)
CAP-11Snap the player onto the rebuilt wall
WAL-03Rebuild the wall after every claim
REN-02The claimed area is drawn from a cache
REN-03Slow claims use their own colour

The capture lifecycle ​

A trail ends in one of two ways. The player can reach the wall again, which is step 8c of the tick. Or the player can cross their own trail, which is step 8d and is called a loop. Both end the same way, with a trail that has two ends on solid ground and a stretch of open arena beside it. The question is which side of the trail the player has won.

The answer takes several jobs, and Figure 09-2 shows them in order. The solver does the first five and the simulation does the last two. The solver never changes the live grid. It returns a result that says what should change, and the simulation then applies it. This keeps the solver testable, and it means a rejected capture leaves the arena untouched.

Figure 09-2: The capture pipeline. The solver covers the steps up to the result. The simulation applies it and rebuilds the wall

Rasterising the trail ​

The trail is a list of points in pixels. A region, on the other hand, is a set of tiles. Before the solver can ask "which tiles are enclosed?", the trail must become tiles too. Turning a line into the tiles it passes through is called rasterising it.

This step matters because the player sees a closed shape, but the solver sees only tiles. If a line leaves a gap of one tile, the solver finds a way through the gap, and the wrong region fills. The trail tiles must form a wall that no region can slip through.

The method is Bresenham line stepping. It walks from one end tile to the other, one tile at a time, along the axis in which the line is longer. An error term tracks how far the true line has drifted from the tile centres. When the drift grows past half a tile, the walk also steps along the other axis. The loop uses only whole numbers, so it has no rounding trouble.

Figure 09-3 shows a line from tile (0, 0) to tile (6, 2). The walk goes along x, which is the longer axis. It steps down a row twice, at x = 2 and x = 5, to follow the line. The seven tiles it visits are (0, 0), (1, 0), (2, 1), (3, 1), (4, 1), (5, 2) and (6, 2).

Figure 09-3: A line from tile (0, 0) to tile (6, 2) rasterised into seven tiles
Figure 09-3: A line from tile (0, 0) to tile (6, 2) rasterised into seven tiles

The tiles of a slanted line touch only at their corners. The flood fill in the next section moves only up, down, left and right, so it cannot squeeze through a corner. The player draws only straight horizontal and vertical lines, so most segments are simple rows and columns of tiles. The general method costs nothing extra and is correct for any line.

Finding the regions ​

Once the trail is a wall of tiles, the unclaimed tiles fall into separate groups. Two tiles are in the same group when you can walk from one to the other through unclaimed tiles, moving up, down, left or right. Each group is a region. A trail that crosses the whole arena leaves two regions.

The solver finds them with a breadth-first search, also called a flood fill. It picks an unclaimed tile that it has not seen, then spreads out from it one step at a time. A queue holds the tiles waiting to be visited. The solver takes the tile at the front, adds it to the region, and puts each unseen unclaimed neighbour at the back. When the queue empties, the region is complete. The solver then looks for the next unseen unclaimed tile and starts again.

A visited grid records every tile the solver has already put in a queue, so no tile is ever queued twice. Each tile is therefore visited once and each of its four neighbours is looked at once. The cost grows in step with the number of tiles, which is 31,878 on the real arena. Figure 09-4 shows a small example with two regions.

Figure 09-4: A breadth-first search finds two regions separated by the trail column
Figure 09-4: A breadth-first search finds two regions separated by the trail column

The partition guard ​

Now consider a trail that goes out along one row of tiles and comes straight back along the same row. It reaches the wall again, so the game treats it as complete. But it encloses nothing. Every unclaimed tile can still reach every other tile by walking round the thin line. The flood fill finds one region, which is the whole arena.

Here is the danger. A rule that says "claim the smallest region" would pick that only region. The player would win the whole arena with one tiny spur, and every enemy in it would be eliminated. A trail must partition the space, which means split it into at least two parts, before anything is claimed. A check for fewer than two regions, which returns null, is the partition guard. Figure 09-5 shows the case.

Figure 09-5: An out-and-back trail leaves one region, so the guard rejects it
Figure 09-5: An out-and-back trail leaves one region, so the guard rejects it

You first build the solver without the guard, so you can watch the test that needs it fail.

Selecting a region ​

With two or more regions, the solver must pick the one the player wins. The game has two rules, applied in order. First, claim the smallest region that has no enemy in it. Second, if every region holds an enemy, claim the smallest region anyway, and list its enemies so that they can be eliminated.

The rules are held as an ordered list of methods. Each one takes the regions, sorted from the smallest. It either returns a selection or returns null to pass. The solver runs the rules in order and stops at the first selection. To add a new rule, you write one method and add one entry to the list. Nothing else in the solver changes. This is called open for extension and closed for modification. New behaviour is added and existing code is left alone.

Enemies are plain positions in pixels in this chapter, so you can test both rules before the game has any enemies. The solver returns the indexes of the enemies a capture would eliminate, but nothing removes them until Chapter 10: Enemies and Collision.

Why earlier designs went wrong ​

Capture rules rarely fail inside the algorithm. They fail where the rules around it drift apart. A solver that always returns a region, with a fallback that claims a region holding an enemy, quietly changes the game's rules. An elimination rule added without a look at the end of the level can leave the player in an empty arena. This is why TrySelectSmallestRegion is a separate named rule.

For that reason, one place owns the sequence of a capture. ResolveCapture in the simulation decides what a capture means, and each later chapter adds one stage to it. The solver only answers which region and which enemies.

NOTE

Many bugs in a game are not algorithm bugs. They are mismatches between the design, the rules in one service and the state changes outside it. When you add a rule, ask which other rules it changes.

Caching what rarely changes ​

Once territory is claimed, the screen must show it. The claimed area is large, up to thousands of tiles, and it changes only when a capture happens. Drawing every claimed tile as its own rectangle on every frame would repeat identical work about 60 times a second.

Instead, the game draws the claimed tiles once into a render target, which is an off-screen texture that you can draw into. Each frame it then draws that one texture to the screen. The cache is rebuilt only when a capture marks it dirty, or when the colours change.

There is one rule about timing. Rebuilding the cache switches the graphics device to another render target. If that happens inside an open sprite batch, between Begin and End, the switch can discard what the frame has already drawn, including its clear. So the rebuild happens in a method named Prepare, which the host calls before the frame is cleared and before the batch opens.

Setting up the data ​

The solver returns a ClaimResult, which you wrote in Chapter 03: The Service Pattern and the Arena. The simulation needs somewhere to keep the history of captures and the claimed percentage, and two new events to report what happened.

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

add-member Source/Data/GameSession.cs after=PlayableWallPath
csharp
    public List<CapturedZone> CaptureHistory { get; init; } = [];

Add the following property below the CaptureHistory property:

add-member Source/Data/GameSession.cs after=CaptureHistory
csharp
    public float ClaimedAreaPercentage { get; set; }

Open Source/Simulation/GameEvent.cs. Add the following two events at the end of the file. A scene reacts to CaptureCompleted by marking the claimed-area cache dirty. CaptureRejected is for a trail that enclosed nothing. In this chapter, Points and EnemiesEliminated are always zero, because scoring arrives in Chapter 12 and enemies in Chapter 10.

add-type Source/Simulation/GameEvent.cs
csharp
public sealed record CaptureCompleted(int Tiles, int Points, bool SlowDraw, bool WasLoop, int EnemiesEliminated) : GameEvent;

public sealed record CaptureRejected : GameEvent;

Building the capture solver ​

The solver has one public operation, ProcessCompletedTrail. Its private helpers do the stages. Here is the card.

AreaClaimingSystem.ProcessCompletedTrail(trail, enemies) : ClaimResult?

  • Takes: a completed trail and, optionally, the positions of the enemies in pixels.
  • Gives: a ClaimResult with the captured region, the remaining region, the trail tiles and the indexes of any eliminated enemies.
  • Promises: it rasterises the trail onto a copy of the grid, finds regions with a 4-neighbour flood fill and applies the selection rules in order. The live grid is not touched.
  • Refuses: it returns null when the trail leaves fewer than two regions.
  • Requirements: CAP-01, CAP-02, CAP-03, CAP-04, CAP-05, CAP-09.

In the Source/Systems folder, create a new file named AreaClaimingSystem.cs and add the following code. It is the shell of the service. The constructor is complete, because it builds the ordered list of rules. The two rule methods and ProcessCompletedTrail are stubs, and the two private records at the bottom carry the data between stages.

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

namespace LastPerimeter.Systems;

public sealed class AreaClaimingSystem
{
    private readonly ArenaSystem _arenaSystem;
    private readonly IReadOnlyList<Func<IReadOnlyList<RegionAnalysis>, RegionSelection?>> _selectionRules;

    public AreaClaimingSystem(ArenaSystem arenaSystem)
    {
        _arenaSystem = arenaSystem;
        _selectionRules =
        [
            TrySelectEnemyFreeRegion,
            TrySelectSmallestRegion,
        ];
    }

    public ClaimResult? ProcessCompletedTrail(Trail completedTrail, IReadOnlyList<Vector2>? enemies = null)
    {
        throw new NotImplementedException();
    }

    private static RegionSelection? TrySelectEnemyFreeRegion(IReadOnlyList<RegionAnalysis> analyses)
    {
        throw new NotImplementedException();
    }

    private static RegionSelection? TrySelectSmallestRegion(IReadOnlyList<RegionAnalysis> analyses)
    {
        throw new NotImplementedException();
    }

    private sealed record RegionAnalysis(Region Region, IReadOnlyList<int> EnemyIndexes);

    private sealed record RegionSelection(Region Region, IReadOnlyList<int> EliminatedEnemyIndexes);
}

The key things to note are:

  • The solver holds the ArenaSystem and nothing else. It is stateless between calls.
  • _selectionRules is a list of functions. Each takes the analysed regions and returns a RegionSelection?. The order of the list is the order of the rules, which is the point of CAP-09. New to Func? See the C# primer.
  • RegionAnalysis pairs a region with the indexes of the enemies inside it. RegionSelection pairs the chosen region with the enemies to eliminate. Both are private, because only the solver uses them.

From the LastPerimeter folder, run dotnet build. The build should succeed, which proves the stubs compile.

The solver tests ​

All five solver tests are written before any stage, so you see them all fail together. Every test uses a small arena of 40 by 20 pixels, which is 10 by 5 tiles, so you can check each result by hand. A trail along x = 12 occupies tile column 3, which leaves 3 columns on the left and 6 on the right.

In the Tests/Systems folder, create a new file named AreaClaimingSystemTests.cs and add the following code. The first test draws a trail from the top to the bottom at x = 12, with no enemies. The smaller side, on the left, must be claimed.

new-file Tests/Systems/AreaClaimingSystemTests.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 AreaClaimingSystemTests
{
    [Fact]
    public void ProcessCompletedTrail_ClaimsSmallerRegion_WhenNoEnemies()
    {
        ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));
        AreaClaimingSystem areaClaimingSystem = new(arena);
        Trail trail = new();
        trail.AddPoint(new Vector2(12, 0));
        trail.AddPoint(new Vector2(12, 20));

        ClaimResult? result = areaClaimingSystem.ProcessCompletedTrail(trail);

        Assert.NotNull(result);
        Assert.True(result!.CapturedRegion.TileCount < result.RemainingPlayableRegion.TileCount);
    }
}

Add the following test below the ProcessCompletedTrail_ClaimsSmallerRegion_WhenNoEnemies test. The trail now runs along x = 20, which is column 5, so the left side has 5 columns and the right side has 4. The right side is smaller. An enemy sits in the left side at (4, 4), so the rule must still claim the right side, and nothing is eliminated.

add-member Tests/Systems/AreaClaimingSystemTests.cs after=ProcessCompletedTrail_ClaimsSmallerRegion_WhenNoEnemies
csharp
    [Fact]
    public void ProcessCompletedTrail_AvoidsEnemyRegion()
    {
        ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));
        AreaClaimingSystem areaClaimingSystem = new(arena);
        Trail trail = new();
        trail.AddPoint(new Vector2(20, 0));
        trail.AddPoint(new Vector2(20, 20));

        ClaimResult? result = areaClaimingSystem.ProcessCompletedTrail(trail, new[] { new Vector2(4, 4) });

        Assert.NotNull(result);
        Assert.True(result!.CapturedRegion.TileCount < result.RemainingPlayableRegion.TileCount);
        Assert.DoesNotContain(result!.CapturedRegion.Tiles, tile => tile.X < 5);
        Assert.Empty(result.EliminatedEnemyIndexes ?? Array.Empty<int>());
    }

Add the following test below the ProcessCompletedTrail_AvoidsEnemyRegion test. The trail goes out along row 2 and then back along the same row, as in Figure 09-5. It encloses nothing, so the result must be null.

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

        // An out-and-back spur along a single line encloses no area; without the
        // partition guard the smallest-region fallback would claim the whole arena.
        Trail trail = new();
        trail.AddPoint(new Vector2(0, 8));
        trail.AddPoint(new Vector2(20, 8));
        trail.AddPoint(new Vector2(1, 8));

        ClaimResult? result = areaClaimingSystem.ProcessCompletedTrail(trail);

        Assert.Null(result);
    }

Add the following test below the ProcessCompletedTrail_ReturnsNull_WhenTrailDoesNotPartitionArena test. The trail is back at x = 12, with an enemy on each side. Both regions hold an enemy, so the second rule applies. It claims the smaller left side and lists enemy 0, which is the one at (4, 4).

add-member Tests/Systems/AreaClaimingSystemTests.cs after=ProcessCompletedTrail_ReturnsNull_WhenTrailDoesNotPartitionArena
csharp
    [Fact]
    public void ProcessCompletedTrail_CapturesSmallestRegionAndEliminatesContainedEnemy_WhenEachSideContainsAnEnemy()
    {
        ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));
        AreaClaimingSystem areaClaimingSystem = new(arena);
        Trail trail = new();
        trail.AddPoint(new Vector2(12, 0));
        trail.AddPoint(new Vector2(12, 20));

        ClaimResult? result = areaClaimingSystem.ProcessCompletedTrail(trail, new[]
        {
            new Vector2(4, 4),
            new Vector2(32, 4),
        });

        Assert.NotNull(result);
        Assert.True(result!.CapturedRegion.TileCount < result.RemainingPlayableRegion.TileCount);
        Assert.Contains(result.CapturedRegion.Tiles, tile => tile.X < 3);
        Assert.Equal(new[] { 0 }, result.EliminatedEnemyIndexes);
    }

Add the following test below the ProcessCompletedTrail_CapturesSmallestRegionAndEliminatesContainedEnemy_WhenEachSideContainsAnEnemy test. It copies the grid before the solve, runs the solver, and checks that the live arena is unchanged. This is the promise that the solver works on a copy.

add-member Tests/Systems/AreaClaimingSystemTests.cs after=ProcessCompletedTrail_CapturesSmallestRegionAndEliminatesContainedEnemy_WhenEachSideContainsAnEnemy
csharp
    [Fact]
    public void ProcessCompletedTrail_DoesNotChangeTheLiveGrid()
    {
        ArenaSystem arena = new(TestConfigFactory.Create(width: 40, height: 20, margin: 0, tileSize: 4));
        AreaClaimingSystem solver = new(arena);
        Trail trail = new();
        trail.AddPoint(new Vector2(12, 0));
        trail.AddPoint(new Vector2(12, 20));
        TileState[,] before = arena.CloneGrid();

        ClaimResult? result = solver.ProcessCompletedTrail(trail);

        Assert.NotNull(result);
        Assert.Equal(0, arena.ClaimedTileCount);
        TileState[,] after = arena.CloneGrid();
        for (int x = 0; x < arena.GridWidth; x++)
        {
            for (int y = 0; y < arena.GridHeight; y++)
            {
                Assert.Equal(before[x, y], after[x, y]);
            }
        }
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 5 and Passed: 48. The 48 passes are the tests from earlier chapters. The five failures are your new tests, which hit the stubs.

Stage 1: rasterise the trail ​

The first stage turns the trail into a set of tiles. Open Source/Systems/AreaClaimingSystem.cs. Add the following method to the AreaClaimingSystem class, below the TrySelectSmallestRegion method. It takes each pair of neighbouring trail points, converts both to tiles, and collects every tile on the line between them. A set holds each tile once, so tiles shared by two segments are not duplicated.

add-member Source/Systems/AreaClaimingSystem.cs after=TrySelectSmallestRegion
csharp
    private HashSet<Point> RasterizeTrailToGrid(Trail trail)
    {
        HashSet<Point> tiles = new();
        for (int index = 0; index < trail.Points.Count - 1; index++)
        {
            if (!_arenaSystem.TryWorldToGrid(trail.Points[index], out Point start) || !_arenaSystem.TryWorldToGrid(trail.Points[index + 1], out Point end))
            {
                continue;
            }

            foreach (Point point in RasterizeLine(start, end))
            {
                if (_arenaSystem.IsValidGridPoint(point))
                {
                    tiles.Add(point);
                }
            }
        }

        return tiles;
    }

Add the following method below the RasterizeTrailToGrid method. This is the line walk from Figure 09-3.

add-member Source/Systems/AreaClaimingSystem.cs after=RasterizeTrailToGrid
csharp
    private static IEnumerable<Point> RasterizeLine(Point start, Point end)
    {
        int x0 = start.X;
        int y0 = start.Y;
        int x1 = end.X;
        int y1 = end.Y;
        int dx = Math.Abs(x1 - x0);
        int sx = x0 < x1 ? 1 : -1;
        int dy = -Math.Abs(y1 - y0);
        int sy = y0 < y1 ? 1 : -1;
        int err = dx + dy;

        while (true)
        {
            yield return new Point(x0, y0);
            if (x0 == x1 && y0 == y1)
            {
                yield break;
            }

            int errorTwice = 2 * err;
            if (errorTwice >= dy)
            {
                err += dy;
                x0 += sx;
            }

            if (errorTwice <= dx)
            {
                err += dx;
                y0 += sy;
            }
        }
    }

The key things to note are:

  • RasterizeTrailToGrid skips a segment if either end is off the grid. TryWorldToGrid refuses such points, so the solver never indexes outside the grid.
  • RasterizeLine is an iterator. The keyword yield return hands back one tile and pauses. The caller's foreach asks for the next tile, and the method carries on from where it paused.
  • dx is the horizontal distance and dy is the vertical distance, stored as a negative number. sx and sy are the step directions, which are 1 or -1.
  • err starts as dx + dy. It is the error term, and it measures how far the line has drifted from the current tile.
  • Each pass doubles err into errorTwice. If that is at least dy, the walk steps in x. If it is at most dx, the walk steps in y. When both are true, the walk steps diagonally. Doubling keeps everything in whole numbers.
  • The loop ends after it has emitted the end tile, so both end tiles are part of the wall.

Nothing calls these methods yet, so the test counts do not change. You can follow a whole walk by hand with a small line from tile (0, 0) to tile (4, 1). Here dx is 4, dy is -1 and err is 3. Pass 1 emits (0, 0). errorTwice is 6, which is at least -1, so x steps to 1 and err becomes 2. It is not at most 4, so y stays. Pass 2 emits (1, 0). errorTwice is 4, so x steps to 2 and err becomes 1. Now 4 is at most 4, so y steps to 1 and err becomes 5. Pass 3 emits (2, 1), and errorTwice is 10, so x steps to 3 and err becomes 4. Pass 4 emits (3, 1) and x steps to 4. Pass 5 emits (4, 1), which is the end tile, so the walk stops. The five tiles are (0, 0), (1, 0), (2, 1), (3, 1) and (4, 1).

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 5 and Passed: 48, the same as before, because nothing calls the new methods yet. The build may warn that RasterizeTrailToGrid is never used. That is expected.

Stage 2: find the regions ​

The second stage is the flood fill from Figure 09-4. Add the following method to the AreaClaimingSystem class, below the ProcessCompletedTrail method. It takes the copy of the grid with the trail already marked, and it returns every region.

add-member Source/Systems/AreaClaimingSystem.cs after=ProcessCompletedTrail
csharp
    private List<Region> FindRegions(TileState[,] tempGrid)
    {
        bool[,] visited = new bool[_arenaSystem.GridWidth, _arenaSystem.GridHeight];
        List<Region> regions = new();

        for (int x = 0; x < _arenaSystem.GridWidth; x++)
        {
            for (int y = 0; y < _arenaSystem.GridHeight; y++)
            {
                if (visited[x, y] || tempGrid[x, y] != TileState.Unclaimed)
                {
                    continue;
                }

                Region region = new();
                Queue<Point> queue = new();
                Point start = new(x, y);
                queue.Enqueue(start);
                visited[x, y] = true;

                while (queue.Count > 0)
                {
                    Point point = queue.Dequeue();
                    region.Tiles.Add(point);

                    foreach (Point neighbor in GetNeighbors(point))
                    {
                        if (!_arenaSystem.IsValidGridPoint(neighbor) || visited[neighbor.X, neighbor.Y] || tempGrid[neighbor.X, neighbor.Y] != TileState.Unclaimed)
                        {
                            continue;
                        }

                        visited[neighbor.X, neighbor.Y] = true;
                        queue.Enqueue(neighbor);
                    }
                }

                regions.Add(region);
            }
        }

        return regions;
    }

Add the following method below the RasterizeLine method. It gives the four neighbours of a tile.

add-member Source/Systems/AreaClaimingSystem.cs after=RasterizeLine
csharp
    private static IEnumerable<Point> GetNeighbors(Point point)
    {
        yield return new Point(point.X - 1, point.Y);
        yield return new Point(point.X + 1, point.Y);
        yield return new Point(point.X, point.Y - 1);
        yield return new Point(point.X, point.Y + 1);
    }

The key things to note are:

  • The two outer loops scan every tile. The continue skips a tile that is visited already, or that is not Unclaimed. A trail tile is Boundary on the copy, so the search never enters it. A claimed tile from an earlier capture is also skipped.
  • A new Region and a new queue start for each unseen tile. The inner while loop is the spread: take a tile from the front, add it to the region, and queue its unseen unclaimed neighbours.
  • A tile is marked visited when it is queued, and not when it is dequeued. This is what stops a tile being queued twice by two neighbours.
  • IsValidGridPoint comes first in the long condition. A neighbour off the grid is skipped before the arrays are read.
  • GetNeighbors lists four directions and no diagonals. This is why the diagonal corners of a rasterised line are a solid wall.
  • Each tile is queued at most once, so the work grows in step with the number of tiles. On the real arena that is at most 31,878 tiles.

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 5 and Passed: 48 again, because ProcessCompletedTrail is still a stub.

Stage 3: select a region ​

The third stage picks the region. It uses LINQ, so if that is new, see the C# primer. Add the following method below the FindRegions method. It pairs each region with the enemies it contains and sorts the pairs from the smallest region. Then it offers them to each rule in turn.

add-member Source/Systems/AreaClaimingSystem.cs after=FindRegions
csharp
    private RegionSelection? SelectRegionToClaim(IEnumerable<Region> regions, IReadOnlyList<Vector2> enemies)
    {
        List<RegionAnalysis> analyses = regions
            .Select(region =>
            {
                HashSet<Point> tiles = region.Tiles.ToHashSet();
                return new RegionAnalysis(region, GetContainedEnemyIndexes(tiles, enemies));
            })
            .OrderBy(analysis => analysis.Region.TileCount)
            .ToList();

        foreach (Func<IReadOnlyList<RegionAnalysis>, RegionSelection?> selectionRule in _selectionRules)
        {
            RegionSelection? selection = selectionRule(analyses);
            if (selection is not null)
            {
                return selection;
            }
        }

        return null;
    }

Add the following method below the SelectRegionToClaim method. It finds which enemies stand in a region, by converting each enemy position to a tile and looking it up in the region's set of tiles.

add-member Source/Systems/AreaClaimingSystem.cs after=SelectRegionToClaim
csharp
    private IReadOnlyList<int> GetContainedEnemyIndexes(HashSet<Point> tiles, IReadOnlyList<Vector2> enemies)
    {
        List<int> enemyIndexes = new();
        for (int index = 0; index < enemies.Count; index++)
        {
            if (_arenaSystem.TryWorldToGrid(enemies[index], out Point enemyGrid) && tiles.Contains(enemyGrid))
            {
                enemyIndexes.Add(index);
            }
        }

        return enemyIndexes;
    }

Find the TrySelectEnemyFreeRegion method and replace the whole method with the following. This is the first rule. Because the list is sorted, FirstOrDefault returns the smallest region that has no enemy.

replace-method Source/Systems/AreaClaimingSystem.cs TrySelectEnemyFreeRegion
csharp
    private static RegionSelection? TrySelectEnemyFreeRegion(IReadOnlyList<RegionAnalysis> analyses)
    {
        RegionAnalysis? enemyFreeRegion = analyses.FirstOrDefault(analysis => analysis.EnemyIndexes.Count == 0);
        return enemyFreeRegion is null
            ? null
            : new RegionSelection(enemyFreeRegion.Region, Array.Empty<int>());
    }

Find the TrySelectSmallestRegion method and replace the whole method with the following. This is the second rule. It takes the first, and so the smallest, region, and lists its enemies for elimination.

replace-method Source/Systems/AreaClaimingSystem.cs TrySelectSmallestRegion
csharp
    private static RegionSelection? TrySelectSmallestRegion(IReadOnlyList<RegionAnalysis> analyses)
    {
        RegionAnalysis? smallestRegion = analyses.FirstOrDefault();
        return smallestRegion is null
            ? null
            : new RegionSelection(smallestRegion.Region, smallestRegion.EnemyIndexes);
    }

The key things to note are:

  • The sort puts the smallest region first. Both rules rely on this and neither sorts again.
  • A rule returns null to pass. TrySelectEnemyFreeRegion passes when every region holds an enemy. Then the loop in SelectRegionToClaim offers the same list to the next rule.
  • TrySelectSmallestRegion never passes while there is at least one region, so it is the final fallback.
  • Adding a rule means writing one more method with this signature and adding its name to _selectionRules in the constructor. Nothing in SelectRegionToClaim changes.
  • Enemy elimination is only reported. The indexes go into the result, and nothing removes an enemy until Chapter 10.

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 5 and Passed: 48 once more. The solver is complete but nothing reaches it until the next stage.

Stage 4: put the stages together ​

Now you write the public operation. You first write it without the partition guard. Find the ProcessCompletedTrail method and replace the whole method with the following:

replace-method Source/Systems/AreaClaimingSystem.cs ProcessCompletedTrail
csharp
    public ClaimResult? ProcessCompletedTrail(Trail completedTrail, IReadOnlyList<Vector2>? enemies = null)
    {
        TileState[,] tempGrid = _arenaSystem.CloneGrid();
        HashSet<Point> trailTiles = RasterizeTrailToGrid(completedTrail);

        foreach (Point tile in trailTiles)
        {
            if (_arenaSystem.IsValidGridPoint(tile))
            {
                tempGrid[tile.X, tile.Y] = TileState.Boundary;
            }
        }

        List<Region> regions = FindRegions(tempGrid);

        RegionSelection? selection = SelectRegionToClaim(regions, enemies ?? Array.Empty<Vector2>());
        if (selection is null)
        {
            return null;
        }

        Region capturedRegion = selection.Region;

        Region remainingRegion = new();
        foreach (Region region in regions)
        {
            if (ReferenceEquals(region, capturedRegion))
            {
                continue;
            }

            remainingRegion.Tiles.AddRange(region.Tiles);
        }

        return new ClaimResult(capturedRegion, remainingRegion, trailTiles.ToList(), selection.EliminatedEnemyIndexes);
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 1 and Passed: 52. Four solver tests now pass. The one that fails is ProcessCompletedTrail_ReturnsNull_WhenTrailDoesNotPartitionArena. This is the bug from Figure 09-5. The out-and-back trail leaves one region, the smallest-region rule picks it, and the solver hands back the whole arena.

In Source/Systems/AreaClaimingSystem.cs, the ProcessCompletedTrail method needs the guard. Find this line in the method:

find Source/Systems/AreaClaimingSystem.cs type=AreaClaimingSystem
csharp
        List<Region> regions = FindRegions(tempGrid);

Replace it with the following. The new lines are the comment, the regions.Count < 2 check and its body:

csharp
        // A valid capture must split the playable space into at least two regions.
        // A degenerate trail (for example one drawn out and straight back along the
        // same line) encloses nothing, and without this guard the smallest-region
        // fallback would select the entire arena.
        List<Region> regions = FindRegions(tempGrid);
        if (regions.Count < 2)
        {
            return null;
        }

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

The key things to note are:

  • CloneGrid gives the solver a private copy. Marking the trail as Boundary on the copy turns the trail into a wall for the search, and the live grid stays as it was. ProcessCompletedTrail_DoesNotChangeTheLiveGrid proves it.
  • The guard sits between FindRegions and the selection. It needs the regions to count them, and it must run before any rule can pick.
  • The remaining region is every region except the captured one, joined into one. The caller can use it to see what is left to play.
  • The result carries trailTiles.ToList(), so the arena can mark the trail itself as claimed in the same step.
  • selection.EliminatedEnemyIndexes is empty when the first rule matched, and lists the enemies of the claimed region when the second rule matched.
  • The timing requirement, CAP-10, is not tested here. A solve visits each tile once, and Chapter 13 measures it on the full arena.

Wiring it into the game ​

The simulation now owns a solver and uses it to end a trail. You make the change in three parts, as in Chapter 08. First the solver and its state, then three scenario tests that fail, then the ResolveCapture operation.

Open Source/Simulation/GameplaySimulation.cs. Add the following field below the _arena field. The solver holds the arena, so the simulation makes a new solver whenever it makes a new arena.

add-member Source/Simulation/GameplaySimulation.cs after=_arena
csharp
    private AreaClaimingSystem _claims;

In the same file, the constructor must build a solver for the arena. Find this line in the GameplaySimulation constructor:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
        _arena = new ArenaSystem(baseConfig);

Add the following line directly after it:

csharp
        _claims = new AreaClaimingSystem(_arena);

Add the following property below the Session property. The tests and the scene read the arena through it.

add-member Source/Simulation/GameplaySimulation.cs after=Session
csharp
    // The arena of the current level. Chapter 14 moves it into LevelServices.
    public ArenaSystem Arena => _arena;

In the StartLevel method, a new level gets a new solver and an empty capture history. Find this line:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
        _arena = new ArenaSystem(_baseConfig);

Add the following lines directly after it:

csharp
        _claims = new AreaClaimingSystem(_arena);
        _session.CaptureHistory.Clear();
        _session.ClaimedAreaPercentage = _arena.GetClaimedPercentage();

The scenario tests drive the whole simulation with scripted key presses. The helper ScriptedInput.DrawRectangleFromTopWall holds Right for 4 frames, Down for 8, Right for 4 and Up for 8. The trail leaves the top wall, goes round and comes back to it, and encloses a block 20 pixels wide and 40 pixels tall.

In the Tests/Simulation folder, create a new file named CaptureScenarioTests.cs and add the following code. The test draws the rectangle and checks five things. There is exactly one CaptureCompleted event. A point inside the block is claimed and a point far outside is not. The claimed percentage is between 5 and 30. The player stands on the rebuilt wall.

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

namespace LastPerimeter.Tests.Simulation;

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

        List<GameEvent> events = ScriptedInput.DrawRectangleFromTopWall(sim);

        Assert.Single(events.OfType<CaptureCompleted>());
        Assert.True(sim.Arena.IsClaimedWorld(new Vector2(30, 20)));
        Assert.False(sim.Arena.IsClaimedWorld(new Vector2(60, 60)));
        Assert.InRange(sim.Session.ClaimedAreaPercentage, 5f, 30f);
        Assert.True(sim.Session.PlayableWallPath.Contains(sim.Session.Player.Position));
    }
}

Add the following test below the Tick_ClosingATrail_ClaimsTheSmallerSide test. It makes a second capture to the right of the first, and checks that the history holds both, numbered 1 and 2.

add-member Tests/Simulation/CaptureScenarioTests.cs after=Tick_ClosingATrail_ClaimsTheSmallerSide
csharp
    [Fact]
    public void Capture_AppendsOrderedCaptureHistory()
    {
        GameplaySimulation sim = SimulationBuilder.Create();
        ScriptedInput.DrawRectangleFromTopWall(sim);

        // Back to the top wall to the right of the first block, then out and back again.
        ScriptedInput.Run(sim, ScriptedInput.Right, 4);
        ScriptedInput.Run(sim, ScriptedInput.Down, 4);
        List<GameEvent> events = ScriptedInput.Run(sim, ScriptedInput.Right, 4);

        Assert.Single(events.OfType<CaptureCompleted>());
        Assert.Equal([1, 2], sim.Session.CaptureHistory.Select(zone => zone.Order));
    }

Add the following test below the Capture_AppendsOrderedCaptureHistory test. The loop is so small that the trail covers every tile it encloses. No region remains inside it, so the solver finds one region and the guard rejects the capture. The player must be back at the anchor, where the trail began.

add-member Tests/Simulation/CaptureScenarioTests.cs after=Capture_AppendsOrderedCaptureHistory
csharp
    [Fact]
    public void RejectedLoop_ReturnsPlayerToAnchor()
    {
        GameplaySimulation sim = SimulationBuilder.Create();
        ScriptedInput.Run(sim, ScriptedInput.Right, 4);
        Vector2 anchor = new(20, 0);

        // A loop so small that its trail covers every tile it encloses.
        ScriptedInput.Run(sim, ScriptedInput.Down, 2);
        ScriptedInput.Run(sim, ScriptedInput.Right, 1);
        ScriptedInput.Run(sim, ScriptedInput.Up, 1);
        List<GameEvent> events = ScriptedInput.Run(sim, ScriptedInput.Left, 1);

        Assert.Single(events.OfType<CaptureRejected>());
        Assert.Equal(anchor, sim.Session.Player.Position);
        Assert.Null(sim.Session.Player.CurrentTrail);
        Assert.Empty(sim.Session.CaptureHistory);
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 3 and Passed: 53. Nothing calls the solver yet, so no capture happens.

The capture operation ​

ResolveCapture is the first operation of the simulation with several stages. It replaces CompleteTrail, the method from Chapter 07 that only ended a trail. Each stage has the number it has in the order of one tick, and the later chapters add the missing numbers.

GameplaySimulation.ResolveCapture(endPoint, snappedToPath) : void

  • Takes: where the trail ended, and whether it ended by reconnecting to the wall.
  • Gives: nothing. The session, the arena and the event list change.
  • Promises: a trail that encloses something is applied to the arena, recorded in the history and followed by a rebuilt wall and a CaptureCompleted event. The player is snapped onto the new wall.
  • Refuses: a trail that encloses nothing is rejected with a CaptureRejected event. A rejected loop returns the player to the first point of the trail.
  • Requirements: CAP-06, CAP-07, CAP-08, CAP-11, WAL-03.

First, replace the call sites. In the TickWhileDrawing method in Source/Simulation/GameplaySimulation.cs, two lines call CompleteTrail. They must call ResolveCapture instead, in steps 8c and 8d. Find this line in step 8c:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
            CompleteTrail(_session.PlayableWallPath.Snap(intendedPosition), snappedToPath: true);

Replace it with:

csharp
            ResolveCapture(_session.PlayableWallPath.Snap(intendedPosition), snappedToPath: true);

Find this line in step 8d:

find Source/Simulation/GameplaySimulation.cs type=GameplaySimulation
csharp
            CompleteTrail(loopIntersection, snappedToPath: false);

Replace it with:

csharp
            ResolveCapture(loopIntersection, snappedToPath: false);

Delete the CompleteTrail method from Source/Simulation/GameplaySimulation.cs. ResolveCapture replaces it. Delete the comment above it too.

Add the following method to the GameplaySimulation class, above the SelectStartNode method:

add-member Source/Simulation/GameplaySimulation.cs before=SelectStartNode
csharp
    // Turns a completed trail into territory. Scoring arrives in chapter 12, enemy
    // removal in chapter 10 and the level check in chapter 14.
    private void ResolveCapture(Vector2 endPoint, bool snappedToPath)
    {
        Player player = _session.Player;

        // 1. Complete the trail and put out the fuse.
        Trail completedTrail = _trails.Complete(endPoint);
        player.Position = endPoint;
        player.CurrentTrail = null;
        _fuse.Reset();

        // 2. Ask the solver.
        ClaimResult? claimResult = _claims.ProcessCompletedTrail(completedTrail);

        // 3. Nothing enclosed. A loop endpoint can sit mid-arena, so return the
        // player to the wall anchor where the trail began.
        if (claimResult is null)
        {
            if (!snappedToPath)
            {
                player.Position = completedTrail.Points[0];
            }

            _events.Add(new CaptureRejected());
            return;
        }

        // 4 and 5. Apply the result and update the percentage.
        _arena.ApplyClaimResult(claimResult, completedTrail.IsSlowDraw);
        _session.ClaimedAreaPercentage = _arena.GetClaimedPercentage();

        // 7. History.
        _session.CaptureHistory.Add(new CapturedZone(_session.CaptureHistory.Count + 1, claimResult.CapturedRegion.Tiles, completedTrail.IsSlowDraw));

        // 8. Rebuild the wall path and snap the player onto it.
        _session.PlayableWallPath = _walls.RebuildPlayablePath(_arena);
        player.Position = _session.PlayableWallPath.Snap(player.Position);

        // 10. Report the capture. Points are zero until chapter 12.
        int tiles = claimResult.CapturedRegion.TileCount + claimResult.TrailTiles.Count;
        _events.Add(new CaptureCompleted(tiles, 0, completedTrail.IsSlowDraw, !snappedToPath, 0));
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 1 and Passed: 55. The three capture scenarios now pass. The one failure is Tick_DrawingOutAndBackToWall_CompletesTheTrail from Chapter 07. It expects the player to stand at the point where the trail ended. After a capture, the player is snapped onto the rebuilt wall, so that position is no longer right. The test needs a new ending.

Open Tests/Simulation/TrailScenarioTests.cs. The old assertion checks a position, so the test must check that one capture was recorded instead. Nothing then uses a position, so the using line goes too. Find this line at the top of the file:

find Tests/Simulation/TrailScenarioTests.cs
csharp
using Microsoft.Xna.Framework;

Delete that line.

In the Tick_DrawingOutAndBackToWall_CompletesTheTrail test, find this line:

find Tests/Simulation/TrailScenarioTests.cs
csharp
        Assert.Equal(new Vector2(40, 0), sim.Session.Player.Position);

Replace it with:

csharp
        Assert.Single(sim.Session.CaptureHistory);

The key things to note about ResolveCapture are:

  • Stage 1 completes the trail in TrailSystem, puts the player at the end point, clears the trail on the player and puts out the fuse. A closed trail must not leave a lit fuse behind. This is the 9a work of Chapter 08, done at the right moment for a capture.
  • Stage 2 asks the solver. The call passes no enemies, because there are no enemies yet. Chapter 10 passes their positions here.
  • Stage 3 handles null. A loop ends where the trail crossed itself, which may be in the middle of the arena. So a rejected loop returns the player to Points[0], the anchor on the wall. A rejected reconnect already ended on the wall, so the player stays there.
  • Stages 4 and 5 apply the result to the live arena and update the percentage. This is the only place the live grid changes, and ApplyClaimResult counts each tile once.
  • Stage 7 appends a CapturedZone numbered one more than the history count, so the orders are 1, 2, 3 and so on.
  • Stage 8 rebuilds the wall path from the new arena, in full, and snaps the player onto it. A snap moves the player to the nearest point on the path.
  • Stage 10 raises CaptureCompleted. The tile count is the region plus the trail. !snappedToPath is true for a loop. The points and the eliminated enemies are zero for now.
  • The stage numbers 6, 9 and 11 are missing on purpose. Scoring is stage 6 in Chapter 12, removing enemies is stage 9 in Chapter 10 and the level check is stage 11 in Chapter 14.

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

Drawing the claimed area ​

The game now claims territory, but nothing draws it yet. You build the cache from the section on caching. In the Source/Rendering folder, create a new file named ClaimedAreaRenderer.cs and add the following code. It has no test, because it draws to the graphics device. It is checked by running the game.

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

namespace LastPerimeter.Rendering;

public sealed class ClaimedAreaRenderer : IDisposable
{
    private readonly ArenaSystem _arenaSystem;
    private readonly GraphicsDevice _graphicsDevice;
    private readonly Texture2D _pixel;
    private readonly SpriteBatch _cacheSpriteBatch;
    private Color _claimedColor;
    private Color _claimedSlowColor;
    private RenderTarget2D? _cache;
    private bool _isDirty = true;

    public ClaimedAreaRenderer(ArenaSystem arenaSystem, GraphicsDevice graphicsDevice, Texture2D pixel, Color claimedColor, Color? claimedSlowColor = null)
    {
        _arenaSystem = arenaSystem;
        _graphicsDevice = graphicsDevice;
        _pixel = pixel;

        // One batch for the life of the renderer. Creating a new SpriteBatch on
        // every rebuild would allocate and free GPU resources on every capture.
        _cacheSpriteBatch = new SpriteBatch(graphicsDevice);
        _cache = new RenderTarget2D(graphicsDevice, arenaSystem.Bounds.Width, arenaSystem.Bounds.Height, false, SurfaceFormat.Color, DepthFormat.None);
        UpdateColor(claimedColor, claimedSlowColor);
    }

    public void MarkDirty()
    {
        _isDirty = true;
    }

    public void UpdateColor(Color claimedColor, Color? claimedSlowColor = null)
    {
        Color resolvedSlowColor = claimedSlowColor ?? claimedColor;
        if (_claimedColor == claimedColor && _claimedSlowColor == resolvedSlowColor)
        {
            return;
        }

        _claimedColor = claimedColor;
        _claimedSlowColor = resolvedSlowColor;
        _isDirty = true;
    }

    // Call once per frame before GraphicsDevice.Clear and SpriteBatch.Begin.
    // A rebuild switches render targets. Doing that inside an open batch can
    // discard the frame's earlier Clear on the back buffer.
    public void Prepare()
    {
        if (_isDirty)
        {
            Rebuild();
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        if (_cache is null)
        {
            return;
        }

        spriteBatch.Draw(_cache, new Vector2(_arenaSystem.Bounds.Left, _arenaSystem.Bounds.Top), Color.White);
    }

    private void Rebuild()
    {
        if (_cache is null)
        {
            return;
        }

        _graphicsDevice.SetRenderTarget(_cache);
        _graphicsDevice.Clear(Color.Transparent);

        _cacheSpriteBatch.Begin(samplerState: SamplerState.PointClamp);
        for (int x = 0; x < _arenaSystem.GridWidth; x++)
        {
            for (int y = 0; y < _arenaSystem.GridHeight; y++)
            {
                Point gridPoint = new(x, y);
                if (_arenaSystem.GetTileState(gridPoint) != TileState.ClaimedByPlayer)
                {
                    continue;
                }

                Rectangle tile = _arenaSystem.GetTileBounds(gridPoint);
                Color color = _arenaSystem.IsSlowClaimed(gridPoint) ? _claimedSlowColor : _claimedColor;
                _cacheSpriteBatch.Draw(_pixel, new Rectangle(tile.X - _arenaSystem.Bounds.Left, tile.Y - _arenaSystem.Bounds.Top, tile.Width, tile.Height), color);
            }
        }

        _cacheSpriteBatch.End();
        _graphicsDevice.SetRenderTarget(null);
        _isDirty = false;
    }

    public void Dispose()
    {
        _cache?.Dispose();
        _cacheSpriteBatch.Dispose();
    }
}

The key things to note are:

  • The constructor creates one SpriteBatch for the cache and keeps it. Making a new batch on every rebuild would allocate and free graphics memory on every capture.
  • The render target is the size of the arena in pixels, so a tile draws at its position minus the arena corner.
  • MarkDirty sets a flag and does nothing else. The expensive work waits until Prepare.
  • UpdateColor compares the new colours with the old and sets the dirty flag only on a change. Nothing calls it yet. Chapter 20 uses it when the theme changes.
  • Prepare rebuilds only when the flag is set. A frame with no capture does no rebuild, which is REN-02.
  • Rebuild sets the render target, clears it to transparent, draws a rectangle for each claimed tile and sets the target back to null, which means the screen. A tile claimed with slow draw uses the slow colour, which is REN-03.
  • Draw puts the cache on the screen at the arena corner with one call. Dispose frees the texture and the batch.

Now connect it to the scene. Open Source/Scenes/GameplayScene.cs. Add the following field to the GameplayScene class, below the _playerRenderer field. It is nullable, because the scene builds it in Enter, after the constructor.

add-member Source/Scenes/GameplayScene.cs after=_playerRenderer
csharp
    private ClaimedAreaRenderer? _claimedArea;

In the Enter method, the scene must build a renderer for the new arena. It disposes of any old one first, so a restarted level does not leak a render target. Find this line:

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

Add the following lines directly after it:

csharp
        _claimedArea?.Dispose();
        _claimedArea = new ClaimedAreaRenderer(_simulation.Arena, _services.GraphicsDevice, _services.Pixel, Color.RoyalBlue, Color.Orange);

In the Update method, the scene must read the events of the tick. It marks the cache dirty for each completed capture, which is how a capture reaches the screen. Find this line:

find Source/Scenes/GameplayScene.cs
csharp
        _simulation.Tick(deltaTime, input);

Replace it with the following:

csharp
        IReadOnlyList<GameEvent> events = _simulation.Tick(deltaTime, input);
        for (int index = 0; index < events.Count; index++)
        {
            if (events[index] is CaptureCompleted)
            {
                _claimedArea?.MarkDirty();
            }
        }

Add the following two methods to the GameplayScene class, below the Update method. The host already calls Prepare on the top scene before it clears the screen and opens the batch.

add-member Source/Scenes/GameplayScene.cs after=Update
csharp
    // Rebuild the claimed-area cache before the batch opens, because a rebuild switches render targets.
    public override void Prepare()
    {
        _claimedArea?.Prepare();
    }

Add the following method below the Prepare method:

add-member Source/Scenes/GameplayScene.cs after=Prepare
csharp
    public override void Dispose()
    {
        _claimedArea?.Dispose();
    }

In the Draw method, the claimed area is drawn after the arena and before the trail, so the trail, the fuse and the player stay on top of it. Find this line:

find Source/Scenes/GameplayScene.cs
csharp
        _arenaRenderer.Draw(spriteBatch, _services.Pixel, _services.Config.ArenaBounds, session.PlayableWallPath);

Add the following line directly after it:

csharp
        _claimedArea?.Draw(spriteBatch);

The key changes are:

  • The _claimedArea field is new, and Enter builds it from the simulation's arena.
  • Update now keeps the events of the tick and reacts to CaptureCompleted.
  • Prepare and Dispose are new overrides. Prepare is where the cache rebuilds, before the batch opens.
  • Draw has one new line, _claimedArea?.Draw(spriteBatch);, between the arena and the trail.

Running the tests ​

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 56. The 56 tests are the 48 from earlier chapters and the 8 you wrote in this chapter.

TestProves
ProcessCompletedTrail_DoesNotChangeTheLiveGridCAP-01
ProcessCompletedTrail_ClaimsSmallerRegion_WhenNoEnemiesCAP-02
ProcessCompletedTrail_ReturnsNull_WhenTrailDoesNotPartitionArenaCAP-03
ProcessCompletedTrail_AvoidsEnemyRegionCAP-04
ProcessCompletedTrail_CapturesSmallestRegionAndEliminatesContainedEnemy_WhenEachSideContainsAnEnemyCAP-05
Capture_AppendsOrderedCaptureHistoryCAP-07
RejectedLoop_ReturnsPlayerToAnchorCAP-08
Tick_ClosingATrail_ClaimsTheSmallerSideCAP-06 and CAP-11, with the wall check in the same test

Four requirements have no test of their own in this chapter. CAP-09 is a property of the constructor's list, and a code review confirms it. CAP-10 is timed in Chapter 13. WAL-03 is covered by the wall tests of Chapter 06, and Tick_ClosingATrail_ClaimsTheSmallerSide shows the rebuilt wall in use by checking that the player stands on it. REN-02 and REN-03 are checked in the next section.

Running the game ​

From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen. The cyan dot sits at the top-left corner of the arena.

Cut off the top-left corner. Hold the Right arrow for about a second, so the dot slides along the top wall. Release it and hold the Down arrow, so a yellow trail runs down into the arena. Release it and hold the Left arrow until the dot reaches the left wall. The trail closes, and the rectangle you enclosed fills blue. The wall now runs round the blue block.

Hold the Right arrow and then the Down arrow to walk along the new edge of the blue block. The dot follows the new wall, not the old one.

Now draw a slow trail. Walk back to the left wall below the blue block. Hold Space and the Right arrow, then the Down arrow, then the Left arrow back to the wall. The trail is thicker, and the claim fills orange. This shows REN-03. Only the claims made with Space held are orange. Close the window with its close button. The test counts prove the solver and the capture rules. Only the window shows the blue and orange fills.

TIP

To see the partition guard, draw a trail that goes out and straight back along the same line. In the game this needs a path thinner than a tile, so it is hard to draw by hand. The unit test is the reliable way to see it.

The next section is optional. It replaces your files with the chapter 09 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 09 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/09-The-Capture-Service"
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/09-The-Capture-Service"
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: 56.

Common mistakes ​

  • A NotImplementedException in the final test run. A stub is left in AreaClaimingSystem.cs. Search the file for throw new NotImplementedException(); and replace that method.
  • The guard test returns a result and the test fails. ProcessCompletedTrail still has the version without if (regions.Count < 2). Use the final listing.
  • A capture fills the wrong side. GetNeighbors includes a diagonal, or RasterizeLine skips the end tile. The trail must be a wall that the search cannot cross.
  • The solver throws an index error. A neighbour is read before IsValidGridPoint is checked. That call must be first in the condition.
  • The claim is correct but the screen shows nothing. The scene does not call MarkDirty on CaptureCompleted, or Prepare is not overridden, so the cache never rebuilds.
  • The first frame after a capture is black. The cache was rebuilt inside the open batch. Rebuild only in Prepare, which runs before the clear.
  • The player stands in the blue area after a capture. The Snap call after the wall rebuild is missing in stage 8 of ResolveCapture.
  • The old Chapter 07 scenario test still fails. You have not yet replaced it. Its position assertion is no longer true after a capture.

Conclusion ​

In this chapter, you accomplished the following:

The tests now prove CAP-01 to CAP-08 and CAP-11. In the next chapter, Chapter 10: Enemies and Collision, you add the enemies that the solver already knows how to count.

Test Your Knowledge ​

  1. Why does the solver work on a copy of the grid?

    Answer

    The trail tiles must act as a wall while the solver searches. Marking them on the copy does that. If the capture is rejected, the live grid is exactly as it was.

  2. What would the smallest-region rule claim for a trail that encloses nothing, if the partition guard were missing?

    Answer

    The only region, which is the whole remaining arena. One small spur would win the whole level and eliminate every enemy.

  3. Why is the claimed-area cache rebuilt in Prepare and not in Draw?

    Answer

    A rebuild switches render targets. Doing that inside an open sprite batch can discard what the frame has already drawn, including its clear. Prepare runs before the batch opens.

  4. Why does the flood fill move only up, down, left and right, and not diagonally?

    Answer

    A rasterised slanted line has tiles that touch only at their corners. If the search could move diagonally, it could slip through those corners and find a way through a trail that looks closed.

  5. What must you change to add a third selection rule?

    Answer

    Write one new method with the same signature as the existing rules and add its name to the _selectionRules list in the constructor. Nothing else in the solver changes.

Extensions ​

  • Add a third rule that prefers the region with the most tiles. Place it first in the list and run the tests. Which tests fail, and why?
  • Add a test where the trail runs horizontally across the arena instead of vertically. Check that the smaller region is claimed.