2016-10-12 2 views
1

Я создаю игру с угадыванием случайных чисел, в которой пользователь устанавливает максимальное количество, которое они хотят угадать. Я выяснил большую часть кода, проблема, которую я, похоже, получаю, заключается в том, что после установки максимального числа и начала угадывать ответ всегда равен 0. Любые советы о том, как настроить мой код, чтобы ответ был числом внутри диапазон, а не 0?Случайное число Guessing Ответы на вопросы 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); 
      } 
     } 
    } 
} 

ответ

2

У вас есть следующие строки, в этом порядке (я опускаю остальное между ними):

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.

+0

Кроме того, run.Next только когда-либо вызывается один раз, он должен вызываться каждый раз, когда пользователь просит повторить игру. – Martheen

1

Придется внести исправления в свой код. Добавлены комментарии к изменениям. Вам лучше добавить обработку ошибок на пользовательский ввод.

ОБНОВЛЕНИЕ: Добавлена ​​обработка ошибок для недопустимого ввода.

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; 
    } 
} 
+0

Проверки большего/меньшего числа кажутся излишними, если они отображают одно и то же сообщение (если случай в «Число» не преднамерен). Либо укажите явно другое сообщение, чтобы направлять пользователя с помощью бинарного поиска или присоединяться к ним в состоянии = =. Кроме того, использование решения в качестве второго параметра в ConsoleWriteLine ничего не делает, поскольку строка не имеет составного формата – Martheen

+0

Я предпочитаю, чтобы GuessNumber возвращал значение GameOver и вместо этого принимал решение PlayAgain за пределами цикла GameOver. Также вы можете укоротить 'return decision! =" N "для PlayAgain – kurakura88

+0

Думаю, мне также нужно использовать TryParse где-то в коде, чтобы дать сообщение об ошибке - пользователь вводит нечто, отличное от числа. Я просто не знаю, где и как это должно быть написано? –

Смежные вопросы