Codiqo

Learn C# · lesson 13 of 61 · about 9 minutes

Project: Treasure Chest

Read the hero's item and decide whether the treasure chest opens: a rule built from ==, ||, &&, ! and ? :.

What you'll learn

  • Translate rules into conditions
  • Compare typed text with ==
  • Report the result with ?:

The chest rule

After the fight, a treasure chest appears. The rule:

1. It opens if the Slime is out of HP, or if the hero has a key
2. But never while the hero is guarding: both hands are on the shield

The player types the item the hero carries. In C#:

(left == 0 || hasKey) && !guard

Picking a message

condition ? a : b picks one of two values: a when the condition is true, b when it's false. It's perfect for the final message: chest ? "The chest opens!" : "The chest stays shut".

The rule on its own

string item = Console.ReadLine() ?? "";
int left = 1;
bool guard = false;
bool hasKey = item == "key";
bool chest = (left == 0 || hasKey) && !guard;
Console.WriteLine(chest ? "The chest opens!" : "The chest stays shut");

Output

The chest opens!

Test the edges

Rules break at their edges. A beaten Slime opens the chest and a Slime on 1 HP doesn't, a key opens it either way, and a guarding hero keeps it shut even when the Slime is beaten. Check each one before you trust the rule.

Tip

The brackets matter: without them && is worked out first, so a guarding hero would open the chest whenever the Slime is beaten. C# doesn't warn you about this, so the brackets are up to you.

Now try it yourself

This lesson is free in Codiqo, with 11 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.