Zapoznaj się z rozwiązaniem, aby dodać metody umożliwiające odtwarzanie gry
Poniższy kod jest jednym z możliwych rozwiązań zadania z poprzedniej lekcji.
Random random = new Random();
Console.WriteLine("Would you like to play? (Y/N)");
if (ShouldPlay())
{
PlayGame();
}
bool ShouldPlay()
{
string response = Console.ReadLine();
return response.ToLower().Equals("y");
}
void PlayGame()
{
var play = true;
while (play) {
var target = GetTarget();
var roll = RollDice();
Console.WriteLine($"Roll a number greater than {target} to win!");
Console.WriteLine($"You rolled a {roll}");
Console.WriteLine(WinOrLose(roll, target));
Console.WriteLine("\nPlay again? (Y/N)");
play = ShouldPlay();
}
}
int GetTarget()
{
return random.Next(1, 6);
}
int RollDice()
{
return random.Next(1, 7);
}
string WinOrLose(int roll, int target)
{
if (roll > target)
{
return "You win!";
}
return "You lose!";
}
Ten kod jest po prostu "jednym z możliwych rozwiązań", ponieważ można było dodać podziały wiersza w różnych miejscach, zwrócić wartości inaczej lub sformatować kod w inny sposób.
Niezależnie od drobnych różnic w kodzie, po uruchomieniu kodu powinny zostać wyświetlone dane wyjściowe podobne do następujących:
Would you like to play? (Y/N)
Y
Roll a number greater than 2 to win!
You rolled a 1
You lose!
Play again? (Y/N)
Y
Roll a number greater than 3 to win!
You rolled a 5
You win!
Play again? (Y/N)
Y
Roll a number greater than 2 to win!
You rolled a 3
You win!
Play again? (Y/N)
N
Jeśli ukończysz to wyzwanie, gratulacje! Przejdź do testu wiedzy w następnej lekcji.
Ważne
Jeśli masz problemy z ukończeniem tego zadania, przed kontynuowaniem rozważ przejrzenie poprzednich lekcji. Wszystkie nowe koncepcje omawiane w innych modułach zależą od zrozumienia koncepcji przedstawionych w tym module.