Let's create a number guessing game.
class NumberGuessingGame
{
static void Main()
{
Random random = new Random();
int targetNumber = random.Next(1, 101); // Generates a random number between 1 and 100
int guess = 0;
int attempts = 0;
Console.WriteLine("Welcome to the 'Guess the Number' game!");
Console.WriteLine("I have chosen a number between 1 and 100. Try to guess it!");
while (guess != targetNumber)
{
Console.Write("Enter your guess: ");
string input = Console.ReadLine();
if (int.TryParse(input, out guess))
{
attempts++;
if (guess < targetNumber)
{
Console.WriteLine("The number is higher.");
}
else if (guess > targetNumber)
{
Console.WriteLine("The number is lower.");
}
else
{
Console.WriteLine($"Congratulations! You guessed the number {targetNumber} in {attempts} attempts.");
}
}
else
{
Console.WriteLine("Please enter a valid number.");
}
}
}
}
That's the code for this game.
Now let me explain the whole code.
Generates a random number between 1 and 100.
Prompts the user to guess the number.
Provides hints if the guessed number is higher or lower than the target number.
Notifies the user of the number of attempts when the correct number is guessed.
- Random Number Generation:
Random random = new Random(); creates a new instance of the Random class.
int targetNumber = random.Next(1, 101); generates a random integer between 1 and 100.
-
Initial Setup:
- int guess = 0; initializes the guess variable.
- int attempts = 0; initializes the attempts counter.
-
Welcome Messages:
- Console.WriteLine("Welcome to the 'Guess the Number' game!"); prints a welcome message.
- Console.WriteLine("I have chosen a number between 1 and 100. Try to guess it!"); prints instructions for the game.
-
Guessing Loop:
- The while loop continues until the user guesses the correct number (guess != targetNumber).
- Inside the loop, the user is prompted to enter a guess with Console.Write("Enter your guess: ");.
- The input is read using string input = Console.ReadLine();.
-
Input Validation and Feedback:
- if (int.TryParse(input, out guess)) checks if the input is a valid integer.
- If the input is valid, the number of attempts is incremented (attempts++;).
- The program then checks if the guess is less than, greater than, or equal to the target number and provides feedback accordingly:
- Console.WriteLine("The number is higher."); if the guess is less than the target number.
- Console.WriteLine("The number is lower."); if the guess is greater than the target number.
- Console.WriteLine($"Congratulations! You guessed the number {targetNumber} in {attempts} attempts."); if the guess is correct.
- If the input is not valid, the user is prompted to enter a valid number with Console.WriteLine("Please enter a valid number.");.
Top comments (0)