Codiqo

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

Project: Battle Report

The battle ends with a report. Work out a score, rank it with a switch expression, and pick the crowd's reaction with another.

What you'll learn

  • Rank a score with a switch expression, highest arm first
  • Test every band at its edge
  • Join patterns with or

The plan

1. The score is heroHp × 2, plus 20 if the Slime is down (left is 0)
2. The rank is Champion from 100, Hero from 80, Survivor from 60, and Rookie below that
3. Print the score and the rank
4. Pick the crowd's reaction: Champion gets The crowd goes wild!, Hero or Survivor gets A solid fight., and anything else gets Train harder.

A switch expression checks its arms from the top and uses the first one that matches, so put the highest band first and each arm only needs its lower edge.

Ranking a score

int heroHp = 30;
int left = 0;
int score = heroHp * 2 + (left == 0 ? 20 : 0);
string rank = score switch
{
    >= 100 => "Champion",
    >= 80 => "Hero",
    >= 60 => "Survivor",
    _ => "Rookie",
};
Console.WriteLine($"Score: {score}, Rank: {rank}");

Output

Score: 80, Rank: Hero

Test every edge

Each band starts at an exact score, so test those first: 100, 80 and 60, then a score just below each one. A rank that's wrong at its edge is the most common bug in code like this. C# helps with one mistake: an arm that can never match, because an arm above it already catches everything it would, doesn't compile.

Tip

Patterns join with or, so "Hero" or "Survivor" => ... gives two values one arm.

Now try it yourself

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