Passer en revue la solution à l’activité de défi impliquant do et while
Le code suivant est une solution possible pour le défi de l’unité précédente.
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!");
Ce code est simplement « une solution possible », car il existe de nombreuses façons d’effectuer la logique d’attaque.
Quoi qu’il en soit, votre résultat doit être similaire à l’exemple de sortie suivant :
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!
Si vous avez réussi, félicitations ! Passez au défi suivant. Si vous avez rencontré des difficultés, prenez le temps de revoir la solution et essayez de comprendre comment elle fonctionne. Il se peut que vous souhaitiez revoir les unités précédentes et réessayer cette activité avant de continuer.