Codiqo

Impara C# · lezione 49 di 61 · circa 10 minuti

Rifinitura

Stampa la ricevuta della fucina come una tabella ordinata e riassumi la visita.

Cosa imparerai

  • Leggere e smistare i comandi
  • Formattare una tabella del catalogo
  • Gestire con garbo l'input sbagliato

Lo scontrino

La visita finisce con una ricevuta che l'eroe legge con un'occhiata. Ogni pezzo di equipaggiamento è una riga della tabella, allineata con l'allineamento dell'interpolazione: {g.Name,-13} riempie il nome fino a 13 caratteri a destra, {g.Slot,-6} fa lo stesso con lo slot, e {g.Price,5} riempie il prezzo a sinistra così i numeri si allineano. L'equipaggiamento comprato ha (bought) dopo di sé. Poi un'espressione switch sul numero di cose comprate sceglie l'ultima riga: niente di nuovo, quell'unico oggetto o un elenco.

Il negozio finito

I comandi sono list, buy <item>, coins e quit.

  • Un'espressione switch associa ogni comando a un metodo
  • Il catalogo viene stampato come una tabella allineata, segnando quello che possiedi
  • I comandi sconosciuti ricevono un messaggio utile invece di un crash

Ripulire un comando digitato

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

Nell'ordine della fucina

bought è costruito a partire dalla fucina, forge.Where(g => shop.Owned.Contains(g.Name)), non dall'insieme stesso. Un HashSet non promette nessun ordine, la lista della fucina sì, quindi l'ultima riga nomina sempre l'equipaggiamento nello stesso ordine della tabella sopra.

Ora prova tu

Questa lezione è gratuita su Codiqo, con 9 domande su quello che hai appena letto. A programmare si impara programmando, quindi finisce con un breve programma che scrivi tu, che eseguiamo e controlliamo subito.