#c# #random
#c# #Случайный
Вопрос:
Я создаю игру в угадывание случайных чисел, в которой пользователь устанавливает максимальное число, которое он хочет угадать. Я разобрался с большей частью кода, проблема, с которой я, похоже, сталкиваюсь, заключается в том, что после установки максимального числа и начала угадывания ответ всегда равен 0. Любые советы о том, как настроить мой код так, чтобы ответ был числом в пределах диапазона, а не 0?
class Program
{
public static int SelectedNumber = 0;
public static Random ran = new Random();
public static bool GameOver = false;
public static int UserMaxValue = 0;
public static string decision;
static void Main(string[] args)
{
int UserNumber;
SelectedNumber = ran.Next(0, UserMaxValue);
do
{
Console.WriteLine("What is the maximum number you want to guess from?");
UserMaxValue = Convert.ToInt32(Console.ReadLine());
do
{
Console.WriteLine("Select a number between 1 and {0}!", UserMaxValue);
UserNumber = Convert.ToInt32(Console.ReadLine());
GuessNumber(UserNumber);
} while (GameOver == false);
} while (GameOver == false);
}
public static void GuessNumber(int UserNumber)
{
if (UserNumber < SelectedNumber)
Console.WriteLine("Your number is wrong, please try again!");
else if (UserNumber > SelectedNumber)
Console.WriteLine("Your Number is wrong, please try again!");
//else if (UserNumber == 0)
// Console.WriteLine("Your Number is wrong, please try again!");
else
{
Console.WriteLine("Yay! You got the right number. Do you want to play again? (y/n) ", decision);
decision = Console.ReadLine();
if (decision == "n")
GameOver = true;
else
do
{
Console.WriteLine("What is the maximum number you want to guess from?");
UserMaxValue = Convert.ToInt32(Console.ReadLine());
do
{
Console.WriteLine("Select a number between 1 and {0}!", UserMaxValue);
UserNumber = Convert.ToInt32(Console.ReadLine());
GuessNumber(UserNumber);
} while (GameOver == false);
} while (GameOver == false);
}
}
}
}
Ответ №1:
У вас есть следующие строки в этом порядке (я опускаю остальные между ними):
public static int UserMaxValue = 0;
// ...
SelectedNumber = ran.Next(0, UserMaxValue);
// ...
Console.WriteLine("What is the maximum number you want to guess from?");
UserMaxValue = Convert.ToInt32(Console.ReadLine());
Вы должны запросить у пользователя значение UserMaxValue, прежде чем сможете правильно установить SelectedNumber.
Комментарии:
1. Кроме того, ran. Next вызывается только один раз, он должен вызываться каждый раз, когда пользователь просит повторить игру.
Ответ №2:
Пришлось внести некоторые исправления в ваш код. Добавлены некоторые комментарии к изменениям. Вам лучше добавить обработку ошибок при вводе пользователем.
ОБНОВЛЕНИЕ: добавлена обработка ошибок при неверном вводе.
class Program
{
public static int SelectedNumber = 0;
public static Random ran = new Random();
public static bool GameOver = false;
public static int UserMaxValue = 0;
static void Main(string[] args)
{
int UserNumber = 0;
bool playAgain = false;
do
{
bool isUserMaxValueValid = false;
do
{
Console.WriteLine("What is the maximum number you want to guess from?");
isUserMaxValueValid = int.TryParse(Console.ReadLine(), out UserMaxValue);
} while (!isUserMaxValueValid);
SelectedNumber = ran.Next(1, UserMaxValue); // Re-assign SelectedNumber for every new max number input. Random number start changed to 1 to avoid 0 value for SelectedNumber
do
{
bool isUserNumberValid = false;
do
{
Console.WriteLine("Select a number between 1 and {0}!", UserMaxValue);
isUserNumberValid = int.TryParse(Console.ReadLine(), out UserNumber);
} while (!isUserNumberValid);
playAgain = GuessNumber(UserNumber);
// I changed GameOver to see if the guessing portion is finished or not
} while (!GameOver); // You don't need to use GameOver == false
} while (playAgain); // Check if user wants to play again or not
}
public static bool GuessNumber(int UserNumber)
{
if (UserNumber != SelectedNumber)
{
GameOver = false;
Console.WriteLine("Your number is wrong, please try again!");
}
else
{
GameOver = true;
bool isPlayAgainValid = false;
Console.WriteLine("Yay! You got the right number. Do you want to play again? (y/n)");
do
{
string decision = Console.ReadLine();
if (decision.Equals("n", StringComparison.InvariantCultureIgnoreCase))
{
return false;
}
else if (decision.Equals("y", StringComparison.InvariantCultureIgnoreCase))
{
break;
}
if(!isPlayAgainValid)
{
Console.WriteLine("Please enter y or n only.");
}
} while (!isPlayAgainValid);
// I removed redundant code
}
return true;
}
}
Комментарии:
1. Проверки на большее / меньшее число кажутся избыточными, если в конечном итоге они показывают одно и то же сообщение (если случай в «числе» не является преднамеренным). Либо дайте явно другое сообщение, чтобы направлять пользователя с помощью двоичного поиска, либо присоединитесь к ним в != условие. Кроме того, использование decision в качестве второго параметра в ConsoleWriteLine ничего не делает, поскольку строка не имеет составного формата
2. Я предпочитаю иметь guessNumber для возврата значения GameOver и вместо этого принимать решение playAgain вне цикла GameOver. Также вы можете сократить
return decision != "n"
для воспроизведения снова3. Я думаю, мне также нужно использовать TryParse где-нибудь в коде, чтобы выдать сообщение об ошибке, если пользователь вводит что-то другое, кроме числа. Я просто не уверен, где и как это должно быть написано?
4. @j_1311 Я обновил свой ответ и добавил пример обработки ошибок.