Select Page

A game can receive a valid command at the wrong time: Start after a win, Win before play begins, or Restart while playing. A small state machine makes those decisions explicit. Here we build a console-only reducer that returns the next state from the current state and one event, then check its complete transition table and replay a recording.

The reducer has no clock, random number generator, console input, or shared mutable state. The same state and event produce the same result. The console harness supplies events and prints the verification results; there is no engine or graphics dependency.

Choose the transition policy first

Our states are Ready, Playing, Won, and Lost. Events are Start, Win, Lose, and Restart. Start begins a game only from Ready. Win and Lose finish an active game. Restart returns every valid state to Ready; starting the next round requires a separate Start event. Other combinations of declared values leave the state unchanged.

Next state for every declared state/event pair
Current state Start Win Lose Restart
Ready Playing Ready Ready Ready
Playing Playing Won Lost Ready
Won Won Won Won Ready
Lost Lost Lost Lost Ready

Ignoring an out-of-sequence event is a deliberate policy here. For example, a second Win cannot undo a loss. An unnamed numeric enum value is different: it is rejected. If you need a refresher on named constants, start with C# enums.

Run the complete reducer and assertion harness

This program was compiled and run targeting net10.0, using the default C# 14 language version, nullable analysis and implicit usings enabled, and warnings treated as errors. Microsoft documents the target-framework defaults in C# language versioning. No NuGet package is needed.

With a .NET 10 SDK installed, create the console project:

dotnet new console --framework net10.0 --name GameLifecycle
cd GameLifecycle

Replace the entire Program.cs with the following program. In the project file, set TreatWarningsAsErrors to true alongside the generated properties, then run dotnet run.

using System;
using System.Collections.Generic;
using System.Linq;

public enum GameState { Ready, Playing, Won, Lost }
public enum GameEvent { Start, Win, Lose, Restart }

public static class Program
{
    public static GameState Reduce(GameState state, GameEvent input)
    {
        if (!Enum.IsDefined(state))
            throw new ArgumentOutOfRangeException(nameof(state), state, "Unknown state");
        if (!Enum.IsDefined(input))
            throw new ArgumentOutOfRangeException(nameof(input), input, "Unknown event");

        return (state, input) switch
        {
            (_, GameEvent.Restart) => GameState.Ready,
            (GameState.Ready, GameEvent.Start) => GameState.Playing,
            (GameState.Playing, GameEvent.Win) => GameState.Won,
            (GameState.Playing, GameEvent.Lose) => GameState.Lost,
            _ => state
        };
    }

    public static GameState[] Replay(GameEvent[] inputs)
    {
        GameState state = GameState.Ready;
        var trace = new List<GameState> { state };
        foreach (GameEvent input in inputs)
        {
            state = Reduce(state, input);
            trace.Add(state);
        }
        return trace.ToArray();
    }

    public static void Main()
    {
        GameState[] states = Enum.GetValues<GameState>();
        GameEvent[] events = Enum.GetValues<GameEvent>();
        Check(states.Length == 4 && events.Length == 4, "Update the transition table");

        // Rows: Ready, Playing, Won, Lost. Columns: Start, Win, Lose, Restart.
        GameState[,] expected =
        {
            { GameState.Playing, GameState.Ready, GameState.Ready, GameState.Ready },
            { GameState.Playing, GameState.Won, GameState.Lost, GameState.Ready },
            { GameState.Won, GameState.Won, GameState.Won, GameState.Ready },
            { GameState.Lost, GameState.Lost, GameState.Lost, GameState.Ready }
        };
        int pairs = 0;
        foreach (GameState state in states)
        foreach (GameEvent input in events)
        {
            Check(Reduce(state, input) == expected[(int)state, (int)input],
                $"Unexpected transition: {state}/{input}");
            pairs++;
        }
        Console.WriteLine($"Transition matrix: {pairs} pairs passed");

        int invalidChecks = 0;
        foreach (int value in new[] { -1, 99, int.MinValue, int.MaxValue })
        {
            foreach (GameEvent input in events)
            {
                ExpectArgument(() => Reduce((GameState)value, input), "state");
                invalidChecks++;
            }
            foreach (GameState state in states)
            {
                ExpectArgument(() => Reduce(state, (GameEvent)value), "input");
                invalidChecks++;
            }
        }
        ExpectArgument(() => Reduce((GameState)99, (GameEvent)99), "state");
        invalidChecks++;
        Console.WriteLine($"Invalid enum values: {invalidChecks} checks passed");

        GameEvent[] recording =
        {
            GameEvent.Start, GameEvent.Win, GameEvent.Start, GameEvent.Restart,
            GameEvent.Start, GameEvent.Lose, GameEvent.Win, GameEvent.Restart
        };
        GameEvent[] original = (GameEvent[])recording.Clone();
        GameState[] expectedTrace =
        {
            GameState.Ready, GameState.Playing, GameState.Won, GameState.Won,
            GameState.Ready, GameState.Playing, GameState.Lost, GameState.Lost,
            GameState.Ready
        };
        for (int repeat = 0; repeat < 100; repeat++)
        {
            Check(Replay(recording).SequenceEqual(expectedTrace), "Replay changed");
            Check(recording.SequenceEqual(original), "Input recording changed");
        }
        Check(Replay(Array.Empty<GameEvent>()).SequenceEqual(new[] { GameState.Ready }),
            "Empty recording must retain the initial state");
        Console.WriteLine("Replay: " + string.Join(" -> ", Replay(recording)));
        Console.WriteLine("Replay: 100 identical traces; input unchanged");
    }

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

    private static void ExpectArgument(Action action, string parameter)
    {
        try
        {
            action();
        }
        catch (ArgumentOutOfRangeException error) when (error.ParamName == parameter)
        {
            return;
        }
        throw new InvalidOperationException($"Expected rejection of {parameter}");
    }
}

Expected standard output, matched exactly by the isolated run:

Transition matrix: 16 pairs passed
Invalid enum values: 33 checks passed
Replay: Ready -> Playing -> Won -> Won -> Ready -> Playing -> Lost -> Lost -> Ready
Replay: 100 identical traces; input unchanged

Read the switch as a transition table

The switch input is the tuple (state, input). Each two-position pattern checks both parts, so the Start rule applies only when the current state is Ready. The underscore in the Restart arm accepts any state that passed validation. Microsoft’s positional-pattern reference explains matching the individual tuple elements.

A switch expression returns the result of its first matching arm. The final discard arm returns the current state for every remaining pair. See Microsoft’s switch-expression reference for arm ordering and exhaustive handling. The Restart arm and the three other transition arms do not overlap here; the catch-all belongs last.

The two checks before the switch use Enum.IsDefined to reject values without a declared member. Validation happens before any transition, so even Restart cannot conceal an invalid state. When both arguments are invalid, the state check wins. That order is part of this reducer’s contract.

The catch-all also means adding a named enum member will not force a new transition arm at compile time. This is why the matrix and its size check matter. For a closer look at compiler diagnostics and unnamed enum values, read switch expressions and exhaustive enum handling.

Check the policy independently of the implementation

The expected matrix is written from the policy table, rather than calculated by calling the reducer. The nested loops use Enum.GetValues to visit every declared state/event pair. All 16 cells are asserted, including the no-op transitions and Restart from each state.

This small matrix uses the enums’ contiguous zero-based numeric values as indexes. Keep that assumption visible: renumbering the enums or adding members requires reviewing the table and its size check. A larger or sparse enum would be better served by explicit test cases keyed by state and event.

The rejection tests exercise four representative unnamed values: -1, 99, the smallest int, and the largest int. Each is tested as a state with every declared event and as an event with every declared state. A final both-invalid case checks validation order, giving 33 checks. These tests sample invalid numeric inputs; they do not enumerate every possible int. Assertions throw on failure, so a failed check stops the program instead of printing a success line.

Replay events without hiding state changes

Replay starts from Ready and records the initial state plus one state per event. Its eight-event recording includes both a win and a loss, a Start after winning, a Win after losing, and two restarts. Comparing the entire nine-state trace catches a wrong intermediate transition even if the final state still happens to be Ready.

The harness compares 100 fresh replays with a handwritten expected trace and checks that the input array stays unchanged. An empty recording must produce just Ready. Repeatability follows from the reducer’s explicit inputs and fixed rules; repeating the test is a useful regression check, not proof about every future rule.

When connecting this to an application, translate input into events, call Reduce, and let the caller store or display the returned state. Keep time, random choices and external results outside this function and represent their outcomes as explicit inputs if they affect transitions. Replay here covers the lifecycle state only. Scores, inventory, saved-event formats, concurrent callers, and rendering would each need their own design and tests.

Share This