using System;
using System.Text;
namespace guess_the_number
{
class MainClass
{
private Random random = new Random();
int getRandomNumber()
{
return random.Next(1, 100);
}
void showStartText()
{
Console.Write("~~~Guess-The-Number~~~\n\n\n");
//
//
Console.Write("Instructions:\n\n\n");
//
//
Console.Write("You will attempt to guess a number, 1-100.\n");
Console.Write("To guess the number, type it, then press enter.\n");
Console.Write("After each guess, you will be told if the number is higher or lower than your \nguess.\n\n");
}
int getValidGuess()
{
while (true)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Please enter your guess:\n");
int result;
Console.ForegroundColor = ConsoleColor.Green;
if (int.TryParse(Console.ReadLine(), out result))
;
else
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("\nInvalid input.\n");
continue;
}
//parse is good, check if number is in desired range
if (!(result >= 1 && result <= 100))
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("\nInvalid input.\n");
continue;
}
return result;
}
}
bool quit()
{
while (true)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Would you like to play again? y/n\n");
Console.ForegroundColor = ConsoleColor.Green;
string input = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.Gray;
if (input.ToLowerInvariant() == "y")
return false;
else if (input.ToLowerInvariant() == "n")
return true;
else
{
Console.Write("\n\nInvalid input\n\n");
continue;
}
}
}
static void Main(string[] args)
{
MainClass main = new MainClass();
//current number that is being guessed
int randomNumber;
//users guess
int guess;
//starting text
main.showStartText();
//main game loop
while (true)
{
//get new random number
randomNumber = main.getRandomNumber();
//per-guess loop
while (true)
{
//get valid guess - parses to make return an int, always valid input
guess = main.getValidGuess();
if (guess == randomNumber)
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("Congratulations, you have guessed the number!\n\n");
if (main.quit())
return;
else
break;
}
else if (guess < randomNumber)
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("Your guess was lower than the number\n\n");
continue;
}
else
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("Your guess was higher than the number\n\n");
continue;
}
}
}
Console.Read();
}
}
}