檢閱「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!
如果您成功,恭喜! 繼續進行下一個挑戰。 如果您遇到問題,請花時間檢閱解決方案,並嘗試了解其運作方式。 您可能想要檢閱先前的單元,然後在繼續之前重試此挑戰活動。