Create a game where the goal is to guess a random number between 1 and 100 in c#
Assistant
Here's a simple implementation of the game:
using System;
class Program
{
static void Main()
{
Random random = new Random();
int secretNumber = random.Next(1, 101);
int guess;
Console.WriteLine("Guess the secret number between 1 and 100!");
do {
Console.Write("Enter your guess: ");
guess = int.Parse(Console.ReadLine());
if (guess < secretNumber) {
Console.WriteLine("Too low! Try again.");
} else if (guess > secretNumber) {
Console.WriteLine("Too high! Try again.");
} else {
Console.WriteLine("Congratulations! You guessed the secret number!");
}
} while (guess != secretNumber);
}
}
Explanation:
We start by creating an instance of the class, which allows us to generate random numbers.
Random
We use the Next method to generate a random integer between 1 and 100, and store it in the secretNumber variable.
We then enter a loop that will keep asking the user to enter a guess until they guess the correct number.
Within the loop, we prompt the user to enter their guess using Console.ReadLine, and parse the input as an integer using int.Parse.
We compare the guess to the secret number using a series of conditional statements (if, else if, and else). If the guess is too low, we tell the user to try again with a higher number. If the guess is too high, we tell the user to try again with a lower number. If the guess is correct, we congratulate the user and end the loop.
The loop continues until the user guesses the correct number, which causes the loop to exit and the program to end.