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
|
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "keep_window_open.h"
int getRandomNumber(int min, int max);
void playHiLo(char answer, int count, int guess, int randomNumber);
char playAgainOrNot();
int main()
{
using namespace std;
srand(time(0));
rand();
char answer = ' ';
int count = 0;
int guess = 0;
int randomNumber = 0;
cout << "Let's play a game. I'm thinking of a number. You have 7 tries to guess what it is.\n";
playHiLo(answer, count, guess, randomNumber);
keep_window_open();
return 0;
}
int getRandomNumber(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);
}
void playHiLo(char answer, int count, int guess, int randomNumber)
{
using namespace std;
do
{
randomNumber = getRandomNumber(1, 100);
cout << "Guess # " << ++count << ": ";
cin >> guess;
cin.ignore(32767, '\n');
if (guess == randomNumber)
{
cout << "Correct! You win!\n";
answer = playAgainOrNot();
if (answer == 'n')
{
break;
}
}
else if (guess > randomNumber)
{
cout << "Your guess is too high.\n";
}
else if (guess < randomNumber)
{
cout << "Your guess is too low.\n";
}
if (count == 7)
{
cout << "Sorry, you lose. The correct number was " << randomNumber << ".\n";
}
} while (guess != randomNumber && count < 7);
}
char playAgainOrNot()
{
using namespace std;
char answer;
do
{
cout << "Would you like to play again (y/n)?";
cin >> answer;
cin.ignore(32767, '\n');
} while (answer != 'y' || answer != 'n');
if (answer == 'y')
{
cout << "Let's play a game. I'm thinking of a number. You have 7 tries to guess what it is.\n";
}
return answer;
}
|