Select Page

A rule table is easier to trust when every cell is checked. This console tutorial scores Rock, Paper, Scissors, Lizard, Spock with one switch expression over the pair of moves, then checks all 25 possible rounds. The result is always from the player’s perspective: 1 for a win, 0 for a tie, and -1 for a loss.

Define the matchup rules

Use these five rules, with matching moves tied:

  • Rock beats Scissors and Lizard.
  • Paper beats Rock and Spock.
  • Scissors beats Paper and Lizard.
  • Lizard beats Paper and Spock.
  • Spock beats Rock and Scissors.

Each move wins against two others and loses against two. Swapping the players must exchange wins and losses while keeping ties tied. With signed results, that reversal check is Resolve(a, b) == -Resolve(b, a): mathematically, antisymmetry. Simply requiring equal results after swapping would be wrong.

This is a deterministic scorer and self-check, with no random opponent or console input. Running it unattended always finishes. For background on enums, see C# enums.

Run the complete program

The program below was built and run targeting net10.0 in a pinned .NET 10 SDK container without network access. Compiler warnings were treated as errors; the build reported zero warnings and errors. It needs no external packages.

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

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

Replace all of Program.cs with this program. To match the checked build settings, set TreatWarningsAsErrors to true in the project’s existing property group. Keep the generated nullable and implicit-usings settings enabled.

using System;

public enum Move { Rock, Paper, Scissors, Lizard, Spock }

public static class Program
{
    // Result is from the player's perspective: win 1, tie 0, loss -1.
    public static int Resolve(Move player, Move opponent) => (player, opponent) switch
    {
        (Move.Rock, Move.Rock) or (Move.Paper, Move.Paper) or
        (Move.Scissors, Move.Scissors) or (Move.Lizard, Move.Lizard) or
        (Move.Spock, Move.Spock) => 0,

        (Move.Rock, Move.Scissors or Move.Lizard) => 1,
        (Move.Paper, Move.Rock or Move.Spock) => 1,
        (Move.Scissors, Move.Paper or Move.Lizard) => 1,
        (Move.Lizard, Move.Paper or Move.Spock) => 1,
        (Move.Spock, Move.Rock or Move.Scissors) => 1,

        (Move.Rock, Move.Paper or Move.Spock) => -1,
        (Move.Paper, Move.Scissors or Move.Lizard) => -1,
        (Move.Scissors, Move.Rock or Move.Spock) => -1,
        (Move.Lizard, Move.Rock or Move.Scissors) => -1,
        (Move.Spock, Move.Paper or Move.Lizard) => -1,
        _ => throw new ArgumentException("Both moves must be declared Move values.")
    };

    public static void Main()
    {
        Move[] moves = Enum.GetValues<Move>();
        // Rows and columns: Rock, Paper, Scissors, Lizard, Spock.
        string[] expectedRows = { "TLWWL", "WTLLW", "LWTWL", "LWLTW", "WLWLT" };
        Check(moves.Length == 5, "Update the expected rule table.");
        int ties = 0, wins = 0, losses = 0, pairs = 0;
        Console.WriteLine("Player/Opponent: Rock Paper Scissors Lizard Spock");
        for (int row = 0; row < moves.Length; row++)
        {
            int rowWins = 0, rowLosses = 0;
            char[] cells = new char[moves.Length];
            for (int column = 0; column < moves.Length; column++)
            {
                Move player = moves[row], opponent = moves[column];
                int result = Resolve(player, opponent);
                Check(result >= -1 && result <= 1, "Unknown result.");
                char cell = result == 0 ? 'T' : result == 1 ? 'W' : 'L';
                Check(cell == expectedRows[row][column], $"Wrong rule: {player}/{opponent}");
                Check((result == 0) == (player == opponent), "Wrong tie.");
                Check(result == -Resolve(opponent, player), "Reversed outcome disagrees.");
                cells[column] = cell;
                if (result == 0) ties++;
                else if (result == 1) { wins++; rowWins++; }
                else { losses++; rowLosses++; }
                pairs++;
            }
            Check(rowWins == 2 && rowLosses == 2, "Each move must win twice and lose twice.");
            Console.WriteLine($"{moves[row]}: {string.Join(" ", cells)}");
        }
        Check(pairs == 25 && ties == 5 && wins == 10 && losses == 10, "Wrong totals.");
        Console.WriteLine($"Pairs: {pairs}; ties: {ties}; player wins: {wins}; opponent wins: {losses}");
        Console.WriteLine("Reversal checks: 25 passed; each move wins 2 and loses 2");

        int invalidChecks = 0;
        foreach (int value in new[] { -1, 99 })
        foreach (Move move in moves)
        {
            ExpectInvalid((Move)value, move);
            ExpectInvalid(move, (Move)value);
            invalidChecks += 2;
        }
        ExpectInvalid((Move)99, (Move)99);
        Console.WriteLine($"Rejected invalid inputs: {invalidChecks + 1}");
    }

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

    private static void ExpectInvalid(Move player, Move opponent)
    {
        try { _ = Resolve(player, opponent); }
        catch (ArgumentException) { return; }
        throw new InvalidOperationException("An unnamed move was accepted.");
    }
}

Run it:

dotnet run

Expected standard output, matched exactly by the isolated run:

Player/Opponent: Rock Paper Scissors Lizard Spock
Rock: T L W W L
Paper: W T L L W
Scissors: L W T W L
Lizard: L W L T W
Spock: W L W L T
Pairs: 25; ties: 5; player wins: 10; opponent wins: 10
Reversal checks: 25 passed; each move wins 2 and loses 2
Rejected invalid inputs: 21

The grid’s rows are player moves; columns are opponent moves. W means the player wins, L means the opponent wins, and T means a tie. For example, the Lizard row loses to Rock and Scissors, ties Lizard, and wins against Paper and Spock. A failed assertion throws an exception; a successful run exits with code 0.

Read both positions of the pattern

The switch input is (player, opponent). Its positional patterns test the two tuple elements in order. In the Rock winning arm, the first position requires Rock, and the second accepts either Scissors or Lizard. Here or combines patterns, rather than Boolean expressions. Microsoft documents matching tuple inputs in positional patterns and the alternatives in logical patterns.

The five tied pairs share one result arm. The next five arms declare player wins, and the following five declare losses. Listing both directions takes a few extra lines, but makes each move’s two winning and two losing opponents visible beside its name.

A switch expression chooses the first matching arm in source order. The final discard pattern accepts every remaining pair and throws our chosen exception, making the expression exhaustive. It belongs last. These rules are described in Microsoft’s switch-expression reference.

Exhaustive matching does not mean every input is a valid game move. In this program only the 25 declared pairs produce scores. Numeric enum casts such as the test values -1 and 99 reach the discard arm instead. Keeping explicit loss arms avoids silently awarding a win or loss to an unknown move. The exhaustive enum handling tutorial examines that distinction and compiler diagnostics in more detail.

Check the rules, not just the totals

The expected rows are handwritten from the rules above, not calculated by calling Resolve. Every result must agree with its cell. Totals alone would miss a balanced but incorrect table: exchanging which opponents a move beats can preserve ten wins and ten losses.

The harness adds three structural checks: only identical moves tie, reversing either round negates its score, and each individual move has exactly two wins and two losses. It then requires 25 rounds with five ties, ten player wins and ten opponent wins. Each check describes a different part of the contract.

The expected matrix uses the same move order shown in the output header. Review those rows and columns whenever you change the enum’s numeric values or membership. Adding a sixth member trips the size assertion, and any new pair left out of Resolve reaches the exception arm. The discard arm provides coverage, so it cannot make the compiler demand a new scoring rule for you.

The 21 rejection checks try -1 and 99 in each position against every declared move, plus one both-invalid pair. They sample unnamed numeric values; they do not enumerate every integer. The 25 valid pairs, however, cover the complete declared game domain.

To adapt the scorer, change the written rules and expected matrix together, then rerun all checks. To connect it to a playable game later, let the caller gather moves and display the returned score. Keep input handling separate so the full table stays easy to test. For a related use of paired inputs with a different contract, see the game state-machine tutorial.

Share This