do と while の課題アクティビティの解決策を確認する
次のコードは、前のユニットの課題に対して考えられる解決策の 1 つです。
int hero = 10;
int monster = 10;
Random dice = new Random();
do
{
int roll = dice.Next(1, 11);
monster -= roll;
Console.WriteLine($"Monster was damaged and lost {roll} health and now has {monster} health.");
if (monster <= 0) continue;
roll = dice.Next(1, 11);
hero -= roll;
Console.WriteLine($"Hero was damaged and lost {roll} health and now has {hero} health.");
} while (hero > 0 && monster > 0);
Console.WriteLine(hero > monster ? "Hero wins!" : "Monster wins!");
攻撃ロジックを実行するには多種多様な方法があるため、このコードは単に "1 つの考えられる解答" です。
いずれにしても、出力は次の出力例のようになります。
Monster was damaged and lost 1 health and now has 9 health.
Hero was damaged and lost 2 health and now has 8 health.
Monster was damaged and lost 1 health and now has 8 health.
Hero was damaged and lost 4 health and now has 4 health.
Monster was damaged and lost 7 health and now has 1 health.
Hero was damaged and lost 6 health and now has -2 health.
Monster wins!
成功した場合は、おめでとうございます。 次の課題に進んでください。 問題が発生した場合は、時間を取ってソリューションを確認し、そのしくみを理解するようにしてください。 先に進む前に、ここまでのユニットを確認してから、このチャレンジ アクティビティを再試行してください。