Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <ctime>
- #include <cstdlib>
- using namespace std; // allows you to not have to type "std::" in front of members of the std library
- int generateRandomNumber(int randomMax) // generate a number between 1 and the max
- {
- srand(time(NULL)); // "seed" the random so it has somethgin ever changign to go off (for example, the time), otherwise it'll just draw the same number every time.
- return (rand() % randomMax) + 1; // generate a random number between 1 and the random max usign modulus magic
- }
- bool checkNumber(int randomNumber, int givenNumber) // checks if the number is correct or not
- {
- if (givenNumber == randomNumber)
- {
- return true;
- }
- else
- {
- return false;
- }
- return false;
- }
- string higherOrLower(int randomNumber, int givenNumber) // checks if the number is correct or not
- {
- if (givenNumber > randomNumber)
- {
- return "Your number was too high.\n";
- }
- else if (givenNumber < randomNumber)
- {
- return "Your number was too low.\n";
- }
- return "Error <higherOrLower>";
- }
- void main()
- {
- const int RANDOM_MAX = 100;
- const int PLAYER_TRIES = 10;
- string playerName = "";
- string getNumber = "";
- int givenNumber = 0;
- int randomNum = 0;
- int tries = 0;
- bool gamePlaying = true;
- randomNum = generateRandomNumber(RANDOM_MAX);
- cout << "Please enter your name: ";
- getline(cin, playerName);
- cout << "Hi " << playerName << ", you'll be guessing a number between 1 and " << RANDOM_MAX
- << ".\nYou have " << PLAYER_TRIES << " tries to get it right, good luck!" << endl;
- cout << randomNum << endl;
- while (gamePlaying == true) // a while loop keeps goign while the condition in its argument is true.
- {
- if (tries < PLAYER_TRIES)
- {
- cout << "Enter guess (Try: " << tries + 1 << "): "; //{
- getline(cin, getNumber); // All of this gets the number and converts it to an integer for comparisons
- givenNumber = stoi(getNumber); //}
- if (checkNumber(randomNum, givenNumber))
- {
- cout << "You guessed the right number!" << endl;
- gamePlaying = false;
- }
- else
- {
- cout << higherOrLower(randomNum, givenNumber);
- tries += 1;
- }
- }
- else
- {
- cout << "You ran out of tries, better luck next time!\n";
- gamePlaying = false;
- }
- }
- system("pause");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement