-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
106 lines (89 loc) · 2.76 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System.Diagnostics;
bool playAgain = true;
int highScore = int.MaxValue;
Console.WriteLine("Welcome to the Number Guessing Game!");
Console.WriteLine("I'm thinking of a number between 1 and 100.");
while (playAgain)
{
int attempts = 0;
int numberToGuess = new Random().Next(1, 101);
int chances = SetDifficulty();
bool isGuessed = false;
Console.WriteLine($"Great! Let's start the game! You have {chances} chances to guess the correct number.");
Stopwatch timer = Stopwatch.StartNew();
while (chances > 0 && !isGuessed)
{
attempts++;
Console.Write("Enter your guess: ");
int userGuess = GetValidNumber();
if (userGuess == numberToGuess)
{
timer.Stop();
Console.WriteLine($"Congratulations! You guessed the correct number in {attempts} attempts and took {timer.Elapsed.Seconds} seconds.");
if (attempts < highScore)
{
highScore = attempts;
Console.WriteLine($"New high score: {highScore} attempts!");
}
isGuessed = true;
}
else
{
chances--;
Console.WriteLine($"Incorrect! The number is {(userGuess < numberToGuess ? "greater" : "less")} than {userGuess}.");
Console.WriteLine($"{chances} chances remaining.");
if (chances == 1)
{
Console.WriteLine("Hint: The number is " + (numberToGuess % 2 == 0 ? "even." : "odd."));
}
}
}
if (!isGuessed)
{
Console.WriteLine($"You've run out of chances! The correct number was {numberToGuess}.");
}
playAgain = AskToPlayAgain();
}
Console.WriteLine("Thank you for playing! Goodbye.");
static int SetDifficulty()
{
Console.WriteLine("\nPlease select the difficulty level:");
Console.WriteLine("1. Easy (10 chances)");
Console.WriteLine("2. Medium (5 chances)");
Console.WriteLine("3. Hard (3 chances)");
Console.Write("Enter your choice: ");
int choice = GetValidNumber();
switch (choice)
{
case 1:
return 10;
case 2:
return 5;
case 3:
return 3;
default:
Console.WriteLine("Invalid choice. Defaulting to Medium difficulty.");
return 5;
}
}
static int GetValidNumber()
{
while (true)
{
string input = Console.ReadLine();
if (int.TryParse(input, out int number))
{
return number;
}
else
{
Console.Write("Invalid input. Please enter a number: ");
}
}
}
static bool AskToPlayAgain()
{
Console.WriteLine("\nDo you want to play again? (y/n): ");
string input = Console.ReadLine().ToLower();
return input == "y";
}