Skip to content

Instantly share code, notes, and snippets.

@spetroll
Last active December 10, 2015 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spetroll/4475657 to your computer and use it in GitHub Desktop.
Save spetroll/4475657 to your computer and use it in GitHub Desktop.
using System;
namespace GuessTheNumber
{
class Program
{
static Random rng = new Random();
static int min=0;
static int max=100;
static int guess = 0;
static int tries = 0;
private static void Main()
{
var number = rng.Next(1, 100);
Console.WriteLine("Do you want to [g]uess or [c]hoose?");
string choice = Console.ReadLine();
if (choice.StartsWith("c"))
{
Console.WriteLine("Insert your number between 1 and 100:");
int.TryParse(Console.ReadLine(), out number);
GuessAI(number);
}
else
GuessUser(number);
}
private static void GuessUser(int number)
{
Console.WriteLine("I generated a number between 1 and 100. Can you guess it?");
while (guess != number)
{
int.TryParse(Console.ReadLine(), out guess);
if (guess != number)
Console.WriteLine("No, it's {0} than {1}. Try again.", guess < number ? "higher" : "lower", guess);
tries++;
}
Console.WriteLine("Great, the answer was {0}. It took you {2} tries.", number, tries);
Console.ReadLine();
}
private static void GuessAI(int number)
{
Console.WriteLine("You generated a number between 1 and 100. Let me try");
while (guess != number)
{
Console.WriteLine("Is it {0}?", Pick(number, ref guess));
if (guess != number)
Console.WriteLine("No, it's {0} than {1}. Let my try again.", guess < number ? "higher" : "lower", guess);
tries++;
}
Console.WriteLine("Great, the answer was {0}. It took me {1} tries.", number, tries);
Console.ReadLine();
}
private static int Pick(int number, ref int guess)
{
if (guess > number)
max = guess;
else
min = guess;
return guess = rng.Next(min, max);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment