Codiqo

Learn C# · lesson 49 of 61 · about 10 minutes

Polishing

Print the forge's receipt as a tidy table and sum up the visit.

What you'll learn

  • Read and dispatch commands
  • Format a catalogue table
  • Handle bad input gracefully

The receipt

The visit ends with a receipt the hero can read at a glance. Each piece of gear is one row of a table, lined up with alignment in the interpolation: {g.Name,-13} pads the name to 13 characters on the right, {g.Slot,-6} does the same for the slot, and {g.Price,5} pads the price on the left so the numbers line up. Gear the hero bought gets (bought) after it. Then one switch expression on how many were bought chooses the closing line: nothing new, the one thing, or a list.

The finished shop

Commands: list, buy <item>, coins and quit.

  • A switch expression maps each command to a method
  • The catalogue prints as an aligned table, marking items you own
  • Unknown commands get a helpful message instead of a crash

Tidying a typed command

string typed = "  Buy Scarf ";
string[] parts = typed.Trim().Split(' ', 2);
Console.WriteLine($"{parts[0].ToLower()} [{parts[1]}]");

Output

buy [Scarf]

Phoebe's Shop

var shop = new Shop(150);
Console.WriteLine("Welcome to Phoebe's Shop! Type list, buy <item>, coins or quit.");
while (true)
{
    string[] parts = (Console.ReadLine() ?? "quit").Trim().Split(' ', 2);
    string command = parts[0].ToLower();
    if (command == "quit") break;
    string reply = command switch
    {
        "list" => shop.Catalogue(),
        "buy" when parts.Length == 2 => shop.Buy(parts[1]),
        "buy" => "Buy what? Try: buy scarf",
        "coins" => $"You have {shop.Coins} coins",
        _ => $"Unknown command '{command}'",
    };
    Console.WriteLine(reply);
}
Console.WriteLine($"Goodbye! Phoebe is wearing: {shop.Wearing()}");

record Item(string Name, int Price);

class Shop(int coins)
{
    private readonly List<Item> _items = new() { new("Scarf", 60), new("Bow tie", 40), new("Top hat", 120) };
    private readonly List<Item> _owned = new();
    public int Coins { get; private set; } = coins;

    public string Catalogue() => string.Join("\n", _items.Select(i =>
        $"{i.Name,-8}{i.Price,4}{(_owned.Contains(i) ? "  (owned)" : "")}"));

    public string Buy(string name)
    {
        Item? item = _items.FirstOrDefault(i => i.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
        if (item is null) return $"No item called {name}";
        if (_owned.Contains(item)) return $"Phoebe already has the {item.Name}";
        if (item.Price > Coins) return $"Not enough coins: the {item.Name} costs {item.Price}";
        Coins -= item.Price;
        _owned.Add(item);
        return $"Bought the {item.Name}! {Coins} coins left";
    }

    public string Wearing() => _owned.Count == 0 ? "nothing yet" : string.Join(" and ", _owned.Select(i => i.Name.ToLower()));
}

Output

Welcome to Phoebe's Shop! Type list, buy <item>, coins or quit.
Scarf     60
Bow tie   40
Top hat  120
Bought the Scarf! 90 coins left
Not enough coins: the Top hat costs 120
Phoebe already has the Scarf
Unknown command 'dance'
Bought the Bow tie! 50 coins left
Scarf     60  (owned)
Bow tie   40  (owned)
Top hat  120
Goodbye! Phoebe is wearing: scarf and bow tie

In the forge's own order

bought is built from the forge, forge.Where(g => shop.Owned.Contains(g.Name)), rather than from the set itself. A HashSet doesn't promise any order, but the forge's list does, so the closing line always names the gear in the same order as the table above it.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.