using System; namespace GuessANumberCS { class GuessANumber { private Random _Rnd; private bool IsAnInt(string input) { int output; return int.TryParse(input, out output); } private int GetNumericInput(string prompt) { while(true) { Console.Write("{0}: ", prompt); string ans = Console.ReadLine(); if (IsAnInt(ans)) return int.Parse(ans); Console.WriteLine("Your entry was not a number."); } } private string GetInput(string question) { while(true) { Console.WriteLine("{0}?", question); string ans = Console.ReadLine(); if (!string.IsNullOrWhiteSpace(ans)) return ans; Console.WriteLine("Your entry seems empty."); } } private bool AskToPlayAgain() { while(true) { string ans = GetInput("Would you like to play again? (\"YES\" or \"NO\")").ToUpper(); if (ans == "YES" || ans == "Y") return true; if (ans == "NO" || ans == "N") return false; Console.WriteLine("Please respond with \"YES\" or \"NO\""); } } private void Run() { _Rnd = new Random((int)DateTime.Now.Ticks); bool Running = true; bool GotMaxNumber = false; int MaxNumber = 0; int Answer = 0; bool GameOver = false; int Tries = 0; Console.WriteLine("*** GUESS A NUMBER : C#"); while(Running) { while (!GotMaxNumber) { MaxNumber = GetNumericInput("Please enter the maximum number you wish to use"); if (MaxNumber > 0) { GotMaxNumber = true; Answer = _Rnd.Next(1, MaxNumber); GameOver = false; Tries = 0; Console.WriteLine("Ok, I am thinking of a number between 1 and {0}", MaxNumber); } else Console.WriteLine("The maximum number should be greater than zero."); } int Guess = GetNumericInput(string.Format("Guess a number between 1 and {0}", MaxNumber)); Tries++; if (Guess > Answer) Console.WriteLine("Too high."); if (Guess < Answer) Console.WriteLine("Too low."); if (Guess == Answer) { Console.WriteLine("You got it in {0} {1}!", Tries, Tries == 1 ? "try" : "tries"); GameOver = true; } if(GameOver) { Running = AskToPlayAgain(); if (Running) GotMaxNumber = false; } } Console.WriteLine("Thanks for playing!"); Console.WriteLine("*** GAME OVER ***"); } static void Main(string[] args) { GuessANumber gan = new GuessANumber(); gan.Run(); } } }