檢閱「do」和 「while」挑戰活動的解決方案
下列程式碼是先前單元中挑戰的其中一個可能解決方案。
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!");
此程式碼只是「一種可能的解決方案」,因為有許多不同的方式可執行攻擊邏輯。
無論如何,您的輸出看起來應會類似下列範例輸出:
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!
如果成功,恭喜您! 請繼續進行下一個單元中的知識檢定。
重要
如果您無法順利完成此挑戰,您應該在繼續之前先複習上一個單元中的內容。 我們在其他課程模組中討論的所有新想法,都取決於您對此課程模組中所呈現之想法的了解。