How to add difficulty levels to a Guess The Number game using rand()?
User guesses a random number (between 1 and 100 or 5000 and 25,000 depending on difficulty) that the computer picks.
User selects difficulty from list, difficulty (1, 2, 3, 4) is assigned to int level. Using do while loops to check for difficulty.
Here is the current do while loop for level 1:
do
{
srand(time(0)); // seed the random number generator
int theNumber = rand() % 100 + 1; // random number between 1 and 100
int tries = 0, guess;
do
{
cout << "Enter a guess: ";
string str;
cin >> str;
istringstream iss(str);
iss >> guess ;
if (iss.eof() == false)
cout << "\n\nPlease enter only numbers.\n\n";
else
{
++tries;
if (guess > theNumber)
cout << "Too high!\n\n";
if (guess < theNumber)
cout << "Too low!\n\n";
}
} while (guess != theNumber);
cout << "\nThat's it! You got it in " << tries << " guesses!\n";
cout << "Play again? (y/n)\n";
cin >> playAgain;
} while (playAgain == 'y' && level == 1);
What I need help with is the int theNumber = rand() % 100 + 1; section. What do I need to change to allow the random number to be between 100 and 1000, 1000 and 5000, 5000 and 25000?
It would also be extremely valuable information to me if you could explain how rand() % x + y; works.
EDIT
I know that rand() = 32767 (for me). I'm just not sure as to how rand() % x + y works. I'm actually not sure what the modulo (%) operator does. If someone could explain that with an example, it would be extremely helpful.
User guesses a random number (between 1 and 100 or 5000 and 25,000 depending on difficulty) that the computer picks.
User selects difficulty from list, difficulty (1, 2, 3, 4) is assigned to int level. Using do while loops to check for difficulty.
Here is the current do while loop for level 1:
do
{
srand(time(0)); // seed the random number generator
int theNumber = rand() % 100 + 1; // random number between 1 and 100
int tries = 0, guess;
do
{
cout << "Enter a guess: ";
string str;
cin >> str;
istringstream iss(str);
iss >> guess ;
if (iss.eof() == false)
cout << "\n\nPlease enter only numbers.\n\n";
else
{
++tries;
if (guess > theNumber)
cout << "Too high!\n\n";
if (guess < theNumber)
cout << "Too low!\n\n";
}
} while (guess != theNumber);
cout << "\nThat's it! You got it in " << tries << " guesses!\n";
cout << "Play again? (y/n)\n";
cin >> playAgain;
} while (playAgain == 'y' && level == 1);
What I need help with is the int theNumber = rand() % 100 + 1; section. What do I need to change to allow the random number to be between 100 and 1000, 1000 and 5000, 5000 and 25000?
It would also be extremely valuable information to me if you could explain how rand() % x + y; works.
EDIT
I know that rand() = 32767 (for me). I'm just not sure as to how rand() % x + y works. I'm actually not sure what the modulo (%) operator does. If someone could explain that with an example, it would be extremely helpful.
No comments:
Post a Comment