Select Page

A locked hatch is both an exit and something you can use. A chest holds objects but does not lead anywhere. Modeling those abilities separately lets the command loop ask what an object can do without maintaining a different branch for every concrete class.

Build a small console adventure with six rooms, four verbs, and three interfaces: IExit, IContainer, and IInteractable. The same loop accepts a scripted walkthrough or console input. The script must reach the garden holding exactly a key and a map.

Choose capabilities before classes

An interface defines a contract. A class can implement several interfaces while inheriting from one base class; Microsoft’s interface guide explains those rules. If the syntax is new, start with Lesson 13: Interfaces, then return for this application.

Abilities in this adventure
Contract Meaning here Implementations
IExit Provides a destination room, or null while locked Passage, Gate
IContainer Exposes contents and supports opening Chest
IInteractable Responds to use with access to inventory names Gate, Scenery

Gate implements two contracts. The move command sees its exit capability; the use command sees its interaction capability. Both operations reach the same object and therefore share its unlocked state. The shallow Thing base class supplies only a name. Rooms hold mixed lists of those objects.

Run the complete game

Use a .NET 10 SDK. The program was compiled and run targeting net10.0, with nullable analysis and implicit usings enabled and warnings treated as errors. It uses the SDK’s default language settings and no external packages.

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

Replace the entire Program.cs with the following listing. Set TreatWarningsAsErrors to true in the project’s property group to match the verification settings, then run dotnet run.

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

SelfCheck();
var game = new Game();
string[] walkthrough = {
    "take key", "move arch", "open chest", "take map",
    "move stairs", "use hatch", "move hatch", "move ladder",
    "use bell", "open locker", "move bridge", "use fountain"
};
game.Run(walkthrough);
Check(game.RoomId == 6, "Walkthrough must finish in room 6.");
Check(game.Inventory.OrderBy(x => x, StringComparer.Ordinal)
    .SequenceEqual(new[] { "key", "map" }), "Expected exactly key and map.");
Console.WriteLine("Self-check passed: room 6; inventory key, map.");
if (args.Length == 1 && args[0] == "--play")
{
    Console.WriteLine("Live play: move/take/open/use NAME; quit to leave.");
    var live = new Game();
    live.Run(ReadCommands(live));
}
else if (args.Length != 0)
    throw new ArgumentException("Use no arguments or --play.");

static IEnumerable<string> ReadCommands(Game game)
{
    while (true)
    {
        Console.WriteLine(game.Describe());
        Console.Write("> ");
        string? line = Console.ReadLine();
        if (line is null || line.Trim().Equals("quit", StringComparison.OrdinalIgnoreCase))
            yield break;
        yield return line;
    }
}

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

static void SelfCheck()
{
    var g = new Game();
    Check(g.Step("open key") == "That cannot be opened.", "Capability check.");
    Check(g.Step("move key") == "That is not an exit.", "Exit check.");
    Check(g.Step("use key") == "That cannot be used.", "Interaction check.");
    Check(g.Step("dance") == "Use move/take/open/use NAME.", "Parser check.");
    g.Step("move arch");
    Check(g.Step("take map") == "No loose item by that name.", "Closed chest.");
    g.Step("open chest");
    g.Step("take map");
    Check(g.Step("take map") == "No loose item by that name.", "Item removed.");
    g.Step("move stairs");
    Check(g.Step("move hatch") == "The exit is locked." && g.RoomId == 3,
        "Locked movement must preserve room.");
    Check(g.Step("use hatch") == "You need the key.", "Key required.");
    Check(g.Step("move hatch") == "The exit is locked.", "Failed unlock.");
}

interface IExit { int? Destination { get; } }
interface IContainer
{
    List<Thing> Contents { get; }
    bool IsOpen { get; }
    void Open();
}
interface IInteractable { string Use(IReadOnlyCollection<string> inventory); }

abstract class Thing(string name) { public string Name { get; } = name; }
sealed class Item(string name) : Thing(name);
sealed class Passage(string name, int destination) : Thing(name), IExit
{
    public int? Destination => destination;
}
sealed class Chest(string name, params Thing[] contents) : Thing(name), IContainer
{
    public List<Thing> Contents { get; } = new(contents);
    public bool IsOpen { get; private set; }
    public void Open() => IsOpen = true;
}
sealed class Gate(string name, int destination) : Thing(name), IExit, IInteractable
{
    private bool unlocked;
    public int? Destination => unlocked ? destination : null;
    public string Use(IReadOnlyCollection<string> inventory)
    {
        if (!inventory.Contains("key")) return "You need the key.";
        unlocked = true;
        return "You unlock the hatch.";
    }
}
sealed class Scenery(string name, string response) : Thing(name), IInteractable
{
    public string Use(IReadOnlyCollection<string> inventory) => response;
}
sealed record Room(string Name, List<Thing> Things);

sealed class Game
{
    private readonly Dictionary<int, Room> rooms = new()
    {
        [1] = new("Foyer", new() { new Item("key"), new Passage("arch", 2) }),
        [2] = new("Gallery", new() { new Chest("chest", new Item("map")),
            new Passage("stairs", 3) }),
        [3] = new("Library", new() { new Gate("hatch", 4) }),
        [4] = new("Workshop", new() { new Passage("ladder", 5) }),
        [5] = new("Tower", new() { new Scenery("bell", "The bell rings."),
            new Chest("locker", new Item("coin")), new Passage("bridge", 6) }),
        [6] = new("Garden", new() { new Scenery("fountain", "The water sparkles.") })
    };
    public int RoomId { get; private set; } = 1;
    private readonly List<string> inventory = new();
    public IReadOnlyCollection<string> Inventory => inventory;
    public string Describe() => $"Room {RoomId}: {rooms[RoomId].Name}. Objects: " +
        string.Join(", ", rooms[RoomId].Things.Select(x => x.Name));

    public void Run(IEnumerable<string> commands)
    {
        foreach (string command in commands)
        {
            Console.WriteLine($"> {command}");
            Console.WriteLine(Step(command));
        }
    }

    public string Step(string command)
    {
        string[] parts = command.Trim().ToLowerInvariant()
            .Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length != 2) return "Use move/take/open/use NAME.";
        string verb = parts[0], name = parts[1].Trim();
        List<Thing> things = rooms[RoomId].Things;
        Thing? target = things.FirstOrDefault(x => x.Name == name);
        switch (verb)
        {
            case "move":
                if (target is not IExit exit) return "That is not an exit.";
                if (exit.Destination is not int next) return "The exit is locked.";
                RoomId = next;
                return $"Room {RoomId}: {rooms[RoomId].Name}.";
            case "open":
                if (target is not IContainer container) return "That cannot be opened.";
                container.Open();
                return $"Opened {name}: " + string.Join(", ", container.Contents.Select(x => x.Name));
            case "use":
                return target is IInteractable usable
                    ? usable.Use(inventory) : "That cannot be used.";
            case "take":
                List<Thing> source = things;
                Item? item = target as Item;
                if (item is null)
                {
                    foreach (Thing thing in things)
                    {
                        if (thing is IContainer box && box.IsOpen &&
                            box.Contents.FirstOrDefault(x => x.Name == name) is Item found)
                        { item = found; source = box.Contents; break; }
                    }
                }
                if (item is null) return "No loose item by that name.";
                source.Remove(item);
                inventory.Add(item.Name);
                return $"Taken {item.Name}.";
            default:
                return "Use move/take/open/use NAME.";
        }
    }
}

The default run performs the rejection checks, executes exactly twelve walkthrough commands, asserts the final room and inventory, and exits without reading console input. Expected stdout, matched exactly in the isolated run:

> take key
Taken key.
> move arch
Room 2: Gallery.
> open chest
Opened chest: map
> take map
Taken map.
> move stairs
Room 3: Library.
> use hatch
You unlock the hatch.
> move hatch
Room 4: Workshop.
> move ladder
Room 5: Tower.
> use bell
The bell rings.
> open locker
Opened locker: coin
> move bridge
Room 6: Garden.
> use fountain
The water sparkles.
Self-check passed: room 6; inventory key, map.

Follow a command through the interfaces

Step splits a command into its verb and target name, then finds that target in the current room. In the move branch, the declaration pattern target is not IExit exit rejects objects without the exit capability. After that guard, exit provides the interface members. A missing target also fails that check.

Microsoft’s declaration-pattern reference documents interface compatibility, the bound local variable, and the rejection of null. Its logical-pattern section describes not. For another application of patterns, see pattern matching for validation.

Opening similarly requires IContainer; using requires IInteractable. The command branches never ask whether the target is specifically a gate or a chest. Taking is deliberately narrower: only Item objects are portable. It first checks the room, then searches open containers one level deep. Removing the item from its source list prevents taking it again.

Interface membership is not permission to succeed. The hatch always implements IExit, but its destination remains null until the player uses it while holding the key. That second check keeps capability and current state separate. The key is retained, which is why the final inventory includes it.

Trace the route and check the rules

The route is Foyer → Gallery → Library → Workshop → Tower → Garden. Take the key in the foyer, open the gallery chest and take its map, then use the library hatch before moving through it. In the tower, ring the bell and open the locker. Leave its coin behind: collecting it would violate the final inventory assertion. Using the garden fountain supplies the final transcript line before the success message.

The endpoint checks compare the room ID with 6 and the sorted inventory with exactly two literal names. They do not just count commands. Before the walkthrough, a separate game checks unsupported capabilities, a malformed command, hidden chest contents, removal after taking, and locked movement without a key. A failed assertion throws instead of printing the success message. The compiler reported zero warnings and zero errors; the run exited successfully with the exact transcript above.

Play from the console, then extend one capability

dotnet run -- --play

This flag starts a fresh game after the automated checks, so you begin in the foyer with an empty inventory. Each turn lists the room and its objects. Enter move arch, take key, open chest, or use hatch when that object is present; enter quit to leave. End-of-input also stops live play. The automated verification exercised the no-argument path; it did not simulate a terminal session.

Run consumes an IEnumerable<string>. The walkthrough supplies an array; ReadCommands supplies console lines as they are requested. Both call the same Step method, keeping room changes and inventory rules in one place.

For a first extension, add another passage or an interactive statue to a room and update the expected route or transcript. A new interactable class can participate in use without adding a concrete-type branch. A new verb still needs its own command behavior.

This is a small, mutable teaching model: exits are one-way, object names are assumed unique within each searchable location, inventory stores names, and containers are searched only one level deep. IContainer intentionally exposes a mutable list so taking can remove an object. A larger game could give that contract an explicit removal operation and use stable item identities. Add checks for those rules as you expand the model.

Share This