C++ Guessing Game

I did not see anywhere to post the Guessing Game, but this was a fun assignement.


#include <iostream>

using namespace std;

int main()
{
   // string name;
   // cout << "...and what is your name?";
   // cin >> name;
   // cout << createGreeting(name);

   // game -create random number - pl2 guess random number
   // too high or too low - guess again
   // count tries

   int randomnumber = rand() % 100 + 1; // create a random number from 1-100
   cout << "Welcome the the Ivan guess a number game. Please guess a number from 1 to 100!" << endl;
   int tries = 1;
   int guess = 0;


   while (guess != randomnumber){
        cout << "Guess! ";
        cin >> guess;
            if (guess < randomnumber) {
                cout << "Woops - too low. Try again." << endl;
            }else if (guess > randomnumber) {
                cout << "Too high. Try again. "  << endl;
            }
        tries ++;
        }
        // added sass
        string comment;
        if (tries < 10) {
            comment = " - you are a superstar!";
        } else if (tries > 30) {
            comment = "Uhm.. That took you a long time.";
        }
        cout << "Great job you only took " << tries << " attempts!" << comment;

    return 0;
}
2 Likes

Nice. Yah that was a fun one. Your solution is considerably more compact than mine. I think I tried to over engineer it a bit :smile:

  • Supports 2 players
    • First player picks the number
    • Second player guesses
  • Sets the max number of guesses to 10
    • If player 2 guesses the number before they run out of guesses they win
    • Else player 1 wins
Guessing game solution
#include <iostream>

using namespace std;

void hideTheNumber() {
    for(int i=0;i<100;i++) {
        cout << "\n";
    }
    cout << "OK the number is hidden! Player 2 can open their eyes now.\n\n";
}

int pickNumber() {
    cout << "\nTHE RULES\n"
        << "1) Player 1 selects a random number (player 2 must not look!)\n"
        << "2) Player 2 needs to guess the number\n"
        << "3) The game will tell Player 2 if the guess is too high or too low\n"
        << "4) Play continues until Player 2 guesses the correct number\n\n";

    int n = 0;
    cout << "Player 1 ask Player 2 to close their eyes!\n"
        << "When their eyes are closed, enter the number to guess: ";
    cin >> n;

    hideTheNumber();

    return n;
}

int getGuess() {
    int guess = 0;
    cout << "\nPlayer 2, enter your guess: ";
    cin >> guess;
    return guess;
}

void giveHint(int theNumber, int guess, int numGuesses, int maxGusses) {
    if (theNumber > guess) {
        cout << "Your gues is too low!";
    } else {
        cout << "Your guess was too high!";
    }

    if (numGuesses < maxGusses) {
        cout << " Try again. You have " << maxGusses - numGuesses << " guesses remaining.\n";
    }
}

void playerTwoWins(int theNumber, int numGuesses) {
    cout << "\nPLAYER 2 WINS! " << theNumber << " was the number!\n"
        << "It took you " << numGuesses << " guesses.\n";
}

void playerOneWins(int maxGuesses) {
    cout << "PLAYER 1 WINS! You are only allowed " << maxGuesses << " guesses.\n";
}

bool playAgain() {
    string response;
    cout << "\nPlay again? (Y/N) ";
    cin >> response;

    if (response == "Y" || response == "y") {
        return true;
    }

    return false;
}

int main()
{
    cout << "Welcome to the Number Gussing Game!\n\n";

    do {
        int numGuesses = 0;
        int maxGuesses = 10;
        int theNumber = pickNumber();
        do {
            int guess = getGuess();
            numGuesses++;

            if (guess == theNumber) {
                playerTwoWins(theNumber, numGuesses);
                break;
            } else if (numGuesses >= maxGuesses) {
                playerOneWins(maxGuesses);
                break;
            } else {
                giveHint(theNumber, guess, numGuesses, maxGuesses);
            }
        } while (true);
    } while(playAgain());

    cout << "\nThanks for playing! See you next time.";
    return 0;
}

2 Likes

The solution provided by Ivan in the video does not included the code how to count the number of attempts. So this is my solution.

#include < iostream >

using namespace std;

int main()
{
/* Game : The rule
1. Player 1 selects a random numbers
2. Player 2 needs to guess the number
3. The game will tell player 2 whether the guess is too low or too high
4. The game will count the number of attempts player 2 made */

int selectNumber = 0;
int currentNumber = 0;
int numberOfAttempts = 0;
cout<<"Player 1 please enter the random number : "<<endl;
cin>> selectNumber;

while(true){
    numberOfAttempts++;
    cout<<"Player 2 please guess the number : "<<endl;
    cin>> currentNumber;
    if(currentNumber > selectNumber){
    cout<< currentNumber <<" is too high"<< endl;
    }
    else if(currentNumber < selectNumber){
    cout<< currentNumber <<" is too low"<< endl;
    }
    else{
        cout<< currentNumber<<" is the right answer"<< endl;
        break;
    }
}
cout<<"Player 2 you made "<<numberOfAttempts<<" Attemps!"<<endl;
return 0;

}

1 Like

Excellent sir, congratulations by completing it by yourself! :muscle:
I have tested the code and it’s runs perfect, you are counting the number of attempts of the player 2 perfectly!

Carlos Z.

1 Like

@thecil
Hi,

This was fun. I wrote my response, but it doesn’t work, error messages. If anyone can tell me where I went wrong…? Thanks!

#include

using namespace std;

int main()
{
bool guessAgain = true;

while (guessAgain == true){

int number = 0;
int guess = 0;
int guessAmount = 0;

cout<<"Player 1: Enter a number: "<<endl;
cin>>number;

cout<<"Player 2: Guess player 1 number: "<<endl;
cin>>guess;

if (int guess < int number)
{
    cout<<"Player 2: The number is too low."<<endl;
    guessAgain = true;
else if (int guess > int number)
{
    cout<<"Player 2: The number is too high."<<endl;
    guessAgain = true;
else
{
    cout<<"Player 2: You are correct! Congratulations!"<<endl;
    guessAgain = false;
}

}

}
guessAmount++;
}

cout<<"You have guessed "<<guessAmount<<"times";

return 0;

}

Hey, there are a bunch of errors in the code:

  • You tried to redeclare the variables in if statements, you should only do this the first time.
  • Then there were missing } at the end of if blocks.
  • You were also asking for the player 1 number in each loop iteration, you should only ask it once, at the beginning of the game.
  • Improvement: You didn’t really need the guessAgain boolean because you could just check if the guess value is not equal to the number.

I have updated your code that looks like this now:

int main()
{
    int number = 0;
    int guess = -1;
    int guessAmount = 0;
    
    cout<<"Player 1: Enter a number: "<<endl;
    cin>>number;
    
    while (number != guess){
    
        cout<<"Player 2: Guess player 1 number: "<<endl;
        cin>>guess;
        
        if (guess < number)
        {
            cout<<"Player 2: The number is too low."<<endl;
        }
        else if (guess > number)
        {
            cout<<"Player 2: The number is too high."<<endl;
        }
        else
        {
            cout<<"Player 2: You are correct! Congratulations!"<<endl;
        }

        guessAmount++;
    }

cout<<"You have guessed "<<guessAmount<<" times";

return 0;

}

You should have a look at the compiler errors, I got all the syntactical errors shown by the compiler and were easy to fix. The logical error like setting the number in each iteration was not, because it was syntactically correct :slight_smile:

1 Like

Hey thanks so much. I feel like these mistakes help me to learn. I’ll definitely check the compiler errors to try to work it out next time.

Would you mind giving me help with it, Al… how could I go to the second loop after the first one is done, it does print when “Tries is smaller than 3” but keeps printing the same message when “tries” is above 3? got stuck…tks…

#include <iostream>

using namespace std;

int main()
{
    int number = 0;
  int pickedNumber = 0;
  int tries = 0;
cout<<"Pick a number, Player 1: "<<endl;
cin>>pickedNumber;
cout<<"Guess a Number from 0 to 20, player 2" <<endl;

  while (true){

cin>>number;
tries++;

    if (number < pickedNumber){
        cout <<"The number you've choose is too low"<<endl;
    }
    else if (number > pickedNumber){
        cout <<"The number you've choose is too high"<<endl;

    }
    else if(number = pickedNumber){
        cout<<"Yep, that is the right number!"<<endl;
    }
    cout<<"You've had "<<tries<<" attempts" <<endl;

int tries = 0;
  while(tries<3){
        cout<<"That is not easy, try again"<<endl;
        break;
  }
  if(tries > 3  && tries <= 7)
    {
        cout<<"Come on!"<<endl;
        break;

  }
  else if (tries > 7){
  cout<<"You are way too slow, wake up"<<endl;
  break;
  }

}
    return 0;}

Why, in your example, did you use minus 1 in the Guess? tks a bunch mate…:smiley:

There are two problems I see. One is that you’re defining tries twice. Try defining it only the first time and increment that variable instead of redefining it inside the while statement.
Also the second while statement is redundant. For this purpose one while statement should suffice and use more if statements inside the wile loop.
Try updating your program according to these guides and let me know how you’re doing. You’re close :wink:

1 Like

Super thanks, Alko… You’re right, that was the problem… the only thing is the message is incomplete in the third try, all the other one seems to be working fine…


#include <iostream>

using namespace std;

int main()
{
  int number = 0;
  int pickedNumber = 0;
  int tries = 0;
cout<<"Pick a number, Player 1: "<<endl;
cin>>pickedNumber;
cout<<"Guess a Number from 0 to 20, player 2" <<endl;

  while (true){

cin>>number;
tries++;

    if (number < pickedNumber){
        cout <<"The number you've choose is too low"<<endl;
    }
    else if (number > pickedNumber){
        cout <<"The number you've choose is too high"<<endl;

    }
    else if(number = pickedNumber){
        cout<<"Yep, that is the right number!"<<endl;
        cout<<"You got it, congrats!"<<endl;

    }
    cout<<"You've had "<<tries<<" attempts" <<endl;

    if (tries<3){
        cout<<"That is not easy, try again"<<endl;
        }
  if (tries > 3 && tries <= 7)
    {
        cout<<"Come on!"<<endl;

  }
  else if (tries > 7 && number != pickedNumber){
  cout<<"You are way too slow, wake up!"<<endl;
    }

}
    return 0;}

Again, Thank you!

Great! :raised_hands: now you would have to exit the loop once the player gets the number. You can modify the while loop or add break in the if statement.
You should also print the stats at the end of the game :wink:

Hello! I saw also that Ivan forgot to add the number of attempts.
First time I started to write the code using for loop. I realized that it’s better to use while loop, but I decided to continue like that:

#include <iostream>
using namespace std;

int main()
{

    cout << "Do you wanna play a game?" << endl;
    cout << "1) Player 1 selects a number" << endl;
    cout << "2) Player 2 needs to guess the number" << endl;
    cout << "3) The game will tell player 2 whether the guess is too low or too high" << endl;
    cout << "4) The game will count the number of attempts player 2 made " << endl << endl;

int insertNumber = 0, guessNumber = 0;
cout <<"Player 1 - Insert number: ";
cin >> insertNumber;

for (int counter = 0; true; counter++){

cout << "Player 2 - Guess the number: ";
cin >> guessNumber;

    if (guessNumber == insertNumber)
    {
        cout << "Congrats!!! You guessed the number in " << (counter + 1) << " times!!" << endl;
       break;
    }
    else if (guessNumber > insertNumber){
        cout << "Please try again! Your number is higher than our number" << endl;
    }
    else{
        cout << "Please try again! Your number is smaller than our number" << endl;
    }
}
    return 0;
}

Also, I tried with while loop:

#include <iostream>
using namespace std;

int main()
{
    cout << "Do you wanna play a game?" << endl;
    cout << "1) Player 1 selects a number" << endl;
    cout << "2) Player 2 needs to guess the number" << endl;
    cout << "3) The game will tell player 2 whether the guess is too low or too high" << endl;
    cout << "4) The game will count the number of attempts player 2 made " << endl << endl;

int insertNumber = 0, guessNumber = 0, counter = 0;
cout <<"Player 1 - Insert number: ";
cin >> insertNumber;

while (true) {
  ++ counter;
cout << "Player 2 - Guess the number: ";
cin >> guessNumber;

    if (guessNumber == insertNumber)
    {
        cout << "Congrats!!! You guessed the number in " << counter << " times!!" << endl;
       break;
    }
    else if (guessNumber > insertNumber){
        cout << "Please try again! Your number is higher than the number we are looking for" << endl;
    }
    else{
        cout << "Please try again! Your number is smaller than the number we are looking for" << endl;
    }

}
    return 0;
}

I just wanted to ask you regarding the if loop. The first condition that I used is directly the case when we guess the number. Is Ivan example (letting this condition at the end) better, or it doesn’t have any importance?

Thank you!

If statement is not a loop, its a branching condition. Technically it doesn’t make a difference. As long as you get the desired result you can order the conditions any way you prefer. Its more of a choice of the developer. :slight_smile:

1 Like

If statement is not a loop, its a branching condition.

Indeed :smiley: .
Thanks for the answer!