-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathguessGame.cpp
81 lines (67 loc) · 1.56 KB
/
guessGame.cpp
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
#include <iostream>
#include <ctime>
#include <cstdlib>
//gets the random number to be guessed
int getRand(int min, int max)
{
static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0);
return static_cast<int>(rand() * fraction * (max - min + 1) + min);
}
//lets users choose if they want yo keep playing
bool getPlay()
{
char play;
while(true)
{
std::cout << "keep playing? [y/n]" << '\n';
std::cin >> play;
std::cin.ignore(32767, '\n');
if(play == 'y')
return true;
else if(play == 'n')
return false;
else if(play != 'y' || 'n')
std::cout << "INVALID INPUT"<<'\n';
}
}
int main()
{
srand(static_cast<unsigned int>(time(0)));
bool play(true);
do
{
std::cout << "I'm thinking of a number from 1 to 100" << '\n';
int target = getRand(1, 100);
int guess(0);
//game loop
for(int attempt = 0; attempt <= 7; ++attempt)
{
std::cout << "guess #" << attempt << ": ";
std::cin >> guess;
//error correction for non integer input
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(32767, '\n');
std::cout << "INVALID INPUT" << '\n';
}
//checks if the guess is correct
else if(guess < target)
std::cout << "too low" << '\n';
else if(guess > target)
std::cout << "too high" << '\n';
else if(guess == target)
{
std::cout << "YOU WIN!" << '\n';
break;
}
//let's player know they lost after 7 attempts
if(attempt == 7)
std::cout << "You loose" << '\n';
}
play = getPlay();
}
while(play);
std::cout << "Thanks for playing!" << '\n';
return 0;
}