Skip to content

Commit c8eaaf7

Browse files
authored
Create guessGame.cpp
1 parent 04cb07f commit c8eaaf7

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

guessGame.cpp

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#include <iostream>
2+
#include <ctime>
3+
#include <cstdlib>
4+
5+
//gets the random number to be guessed
6+
int getRand(int min, int max)
7+
{
8+
static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0);
9+
10+
return static_cast<int>(rand() * fraction * (max - min + 1) + min);
11+
}
12+
13+
//lets users choose if they want yo keep playing
14+
bool getPlay()
15+
{
16+
char play;
17+
while(true)
18+
{
19+
std::cout << "keep playing? [y/n]" << '\n';
20+
std::cin >> play;
21+
std::cin.ignore(32767, '\n');
22+
23+
if(play == 'y')
24+
return true;
25+
else if(play == 'n')
26+
return false;
27+
else if(play != 'y' || 'n')
28+
std::cout << "INVALID INPUT"<<'\n';
29+
}
30+
}
31+
32+
int main()
33+
{
34+
srand(time(0));
35+
bool play(true);
36+
do
37+
{
38+
std::cout << "I'm thinking of a number from 1 to 100" << '\n';
39+
40+
int target = getRand(1, 2);
41+
int guess(0);
42+
43+
//game loop
44+
for(int attempt = 0; attempt <= 7; ++attempt)
45+
{
46+
std::cout << "guess #" << attempt << ": ";
47+
std::cin >> guess;
48+
49+
//error correction for non integer input
50+
if (std::cin.fail())
51+
{
52+
std::cin.clear();
53+
std::cin.ignore(32767, '\n');
54+
std::cout << "INVALID INPUT" << '\n';
55+
}
56+
57+
//checks if the guesd is correct
58+
else if(guess < target)
59+
std::cout << "too low" << '\n';
60+
else if(guess > target)
61+
std::cout << "too high" << '\n';
62+
else if(guess == target)
63+
{
64+
std::cout << "YOU WIN!" << '\n';
65+
break;
66+
}
67+
68+
//let's player know they lost after 7 attempts
69+
else if(attempt == 7)
70+
std::cout << "You loose" << '\n';
71+
}
72+
73+
play = getPlay();
74+
75+
}
76+
while(play);
77+
78+
std::cout << "Thanks for playing!";
79+
80+
return 0;
81+
}

0 commit comments

Comments
 (0)