Select Page

A turn-based battle needs a rule for deciding who acts next. Here, a Knight and a Goblin both start at tick zero. The Knight acts first because it was scheduled first; after that, each fighter waits its own delay before attacking again. We will use a priority queue to advance directly to the next action and check the complete battle trace.

This console example was built and run for .NET 10 with nullable analysis and warnings treated as errors. That target defaults to C# 14, as documented in Microsoft’s language-version table. It needs no packages. For background on typed collections, see our introduction to C# generics.

Define the battle’s ordering policy

PriorityQueue<TElement, TPriority> removes the item whose priority compares lowest. Equal priorities do not have a guaranteed FIFO order. Give each scheduled action two priority fields: its due tick and a unique insertion sequence. Compare ticks first, then sequences. Two actions at tick zero therefore have a deliberate, reproducible order.

The two fighters and their fixed rules
Fighter Starting HP Damage Delay after attacking
Knight 9 4 3 ticks
Goblin 10 3 2 ticks

Both initial actions are due at tick zero. After a nonlethal attack, schedule the same fighter at the current tick plus its delay. A smaller delay means more frequent actions. Stop immediately when a fighter reaches zero HP; any pending action is discarded with the local battle queue.

Run the complete program

Create a console project targeting net10.0, replace Program.cs with the following, and run it with dotnet run. The checks throw if ordering or the expected battle changes. Actor IDs 0 and 1 index the parallel arrays in Battle; the queue itself only stores an ID and its scheduling priority.

using System;
using System.Collections.Generic;

CheckQueueRules();
string expectedBattle = string.Join("\n", new[]
{
    "0: Knight hits Goblin; HP=6",
    "0: Goblin hits Knight; HP=6",
    "2: Goblin hits Knight; HP=3",
    "3: Knight hits Goblin; HP=2",
    "4: Goblin hits Knight; HP=0",
    "Winner: Goblin"
});
for (int run = 0; run < 20; run++)
    Require(Battle() == expectedBattle, "battle trace");
Console.WriteLine("Queue checks: lowest tick, insertion ties, empty passed");
Console.WriteLine(expectedBattle);
Console.WriteLine("Replay: 20 identical battles passed");

static void Require(bool condition, string message)
{
    if (!condition) throw new InvalidOperationException(message);
}

static void CheckQueueRules()
{
    var turns = new TurnQueue();
    Require(!turns.TryTake(out _, out _), "initially empty");
    turns.Add(9, 9);
    turns.Add(2, 2);
    turns.Add(5, 5);
    foreach (int expected in new[] { 2, 5, 9 })
        Require(turns.TryTake(out int actor, out long tick)
                && actor == expected && tick == expected, "lowest tick");
    Require(!turns.TryTake(out _, out _), "drained empty");

    turns.Add(10, 7);
    turns.Add(20, 7);
    Require(turns.TryTake(out int first, out long firstTick)
            && first == 10 && firstTick == 7, "first insertion");
    turns.Add(30, 7); // A newly scheduled tie joins behind the waiting turn.
    foreach (int expected in new[] { 20, 30 })
        Require(turns.TryTake(out int actor, out long tick)
                && actor == expected && tick == 7, "insertion tie");
    Require(!turns.TryTake(out _, out _), "ties drained");
}

static string Battle()
{
    string[] names = { "Knight", "Goblin" };
    int[] health = { 9, 10 };
    int[] damage = { 4, 3 };
    long[] delay = { 3, 2 };
    var turns = new TurnQueue();
    turns.Add(0, 0); // Knight wins the initial tie by insertion sequence.
    turns.Add(1, 0);
    var trace = new List<string>();

    while (turns.TryTake(out int actor, out long tick))
    {
        int target = 1 - actor;
        health[target] = Math.Max(0, health[target] - damage[actor]);
        trace.Add($"{tick}: {names[actor]} hits {names[target]}; HP={health[target]}");
        if (health[target] == 0)
        {
            trace.Add($"Winner: {names[actor]}");
            return string.Join("\n", trace);
        }
        turns.Add(actor, checked(tick + delay[actor]));
    }
    throw new InvalidOperationException("Battle ended without a winner.");
}

sealed class TurnQueue
{
    private long nextSequence;
    private readonly PriorityQueue<int, (long Tick, long Sequence)> pending = new(
        Comparer<(long Tick, long Sequence)>.Create((left, right) =>
        {
            int byTick = left.Tick.CompareTo(right.Tick);
            return byTick != 0 ? byTick : left.Sequence.CompareTo(right.Sequence);
        }));

    public void Add(int actor, long tick)
    {
        long sequence = nextSequence;
        nextSequence = checked(nextSequence + 1);
        pending.Enqueue(actor, (tick, sequence));
    }

    public bool TryTake(out int actor, out long tick)
    {
        bool found = pending.TryDequeue(out actor, out var priority);
        tick = priority.Tick;
        return found;
    }
}

Compare the exact output

The verified run produced this output. The internal trace uses newline separators and is compared before printing; the whole console output is also checked against this expected text.

Queue checks: lowest tick, insertion ties, empty passed
0: Knight hits Goblin; HP=6
0: Goblin hits Knight; HP=6
2: Goblin hits Knight; HP=3
3: Knight hits Goblin; HP=2
4: Goblin hits Knight; HP=0
Winner: Goblin
Replay: 20 identical battles passed

The opening tie lets the Knight attack first. The Goblin then acts at ticks zero and two before the Knight returns at tick three. At tick four the Goblin lands the winning hit. There is no sleeping or wall-clock timing: a tick is simply an integer position on this simulation’s timeline.

Why the wrapper matters

The comparer explicitly orders the two numeric fields using Int64.CompareTo. Comparing values avoids implementing the comparison by subtraction. Every call to Add assigns a new sequence, including rescheduled turns. The tie test removes one action, adds another at the same tick, then proves the already waiting action stays ahead of the newcomer. The queue is never asked to preserve FIFO order for equal composite priorities.

TryDequeue returns false for an empty queue. The wrapper forwards that result, and callers only consume the actor and tick when it is true. The tests cover both a newly created queue and queues drained after distinct ticks and ties. The battle’s empty-queue exception signals an unexpected scheduling gap: these two fixed fighters should always produce a winner.

The checked additions prevent silent wraparound of ticks or the insertion counter. They throw on overflow; this example does not implement an unbounded timeline. Its delays and damage are fixed positive values. If you accept fighter definitions from input, validate those values first so that zero damage cannot create an endless battle.

Keep extensions deterministic

Each call to Battle creates fresh health arrays and a fresh queue. Twenty calls must match the same six-line trace. This checks the supplied rules and initial ordering, not every possible battle configuration. To change initiative, change the initial insertion order and update the expected trace deliberately.

For a larger party, define target selection, defeated-fighter handling, and a turn limit before adding more actors. This two-fighter loop returns on the first defeat, so it does not need to remove stale turns for dead actors. A graphics layer is a separate next step; our C# game-engine guide can help you choose where to display the results.

Share This