Repository navigation
Expand file tree
/
Copy pathNumberGuessingGame.cpp
More file actions
105 lines (87 loc) · 2.97 KB
/
Copy pathNumberGuessingGame.cpp
File metadata and controls
105 lines (87 loc) · 2.97 KB
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
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <limits>
#include <string>
using namespace std;
void printHeader(const string& title) {
cout << "\n";
cout << " " << title << "\n";
cout << "\n";
}
int getValidInt(const string& prompt) {
int input;
while (true) {
cout << prompt;
if (cin >> input) {
return input;
} else {
cout << " [!] Invalid input. Please enter a whole number.\n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
}
void playGame() {
printHeader("NUMBER GUESSING GAME");
cout << "Choose your difficulty level:\n";
cout << " 1. Easy (1 to 50, Unlimited tries)\n";
cout << " 2. Medium (1 to 100, 10 tries)\n";
cout << " 3. Hard (1 to 500, 7 tries)\n\n";
int choice = 0;
int maxNumber = 100;
int maxAttempts = -1;
while (true) {
choice = getValidInt("Enter choice (1-3): ");
if (choice == 1) { maxNumber = 50; maxAttempts = -1; break; }
else if (choice == 2) { maxNumber = 100; maxAttempts = 10; break; }
else if (choice == 3) { maxNumber = 500; maxAttempts = 7; break; }
else { cout << " [!] Please enter 1, 2, or 3.\n\n"; }
}
int targetNumber = rand() % maxNumber + 1;
int attempts = 0;
int guess = 0;
printHeader("GAME STARTED");
cout << "I have chosen a number between 1 and " << maxNumber << ".\n";
if (maxAttempts != -1) {
cout << "You have " << maxAttempts << " attempts to guess it. Good luck!\n";
}
cout << "\n";
while (true) {
guess = getValidInt("Enter your guess: ");
attempts++;
if (guess == targetNumber) {
cout << "\n >>> BINGO! <<<\n";
cout << " You guessed the number in " << attempts << " attempts!\n";
break;
} else if (guess < targetNumber) {
cout << " -- Too low! Try a higher number.\n";
} else {
cout << " ++ Too high! Try a lower number.\n";
}
if (maxAttempts != -1 && attempts >= maxAttempts) {
cout << "\n >>> GAME OVER! <<<\n";
cout << " You've run out of attempts.\n";
cout << " The correct number was: " << targetNumber << "\n";
break;
}
if (maxAttempts != -1) {
cout << " (Attempts remaining: " << maxAttempts - attempts << ")\n";
}
cout << "\n";
}
}
int main() {
srand(static_cast<unsigned int>(time(0)));
char playAgain = 'y';
while (tolower(playAgain) == 'y') {
playGame();
cout << "\n";
cout << "Would you like to play again? (y/n): ";
cin >> playAgain;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "\nThanks for playing! Goodbye.\n";
return 0;
}