Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Microproject

Sub:- oop co-3i


Topic:-gussing game

#include <iostream>
#include <cstdlib>
#include <ctime>

class GuessingGame {
private:
int secret_number;
int guesses;

public:
GuessingGame(int min, int max) : guesses(0) {
srand(time(0));
secret_number = rand() % (max - min + 1) + min;
}

std::string guessNumber(int number) {


guesses++;
if (number < secret_number) {
return "Too low";
} else if (number > secret_number) {
return "Too high";
} else {
return "Congratulations!";
}
}

int getGuesses() const {


return guesses;
}

int getSecretNumber() const {


return secret_number;
}
};

int main() {
GuessingGame game(1, 100);
int userGuess;
do {
std::cout << "Guess the number: ";
std::cin >> userGuess;

if (userGuess == 0) {
std::cout << "Quitting the game. The secret number was " <<
game.getSecretNumber() << "." << std::endl;
break;
}

std::string result = game.guessNumber(userGuess);


std::cout << result << std::endl;

if (userGuess == game.getSecretNumber()) {
std::cout << "You guessed the number in " <<
game.getGuesses() << " guesses." << std::endl;
break;
}
} while (true);

return 0;

}
Output:-

Explanation:-

1. We create a class `GuessingGame` which represents the game. It has attributes


like `secret_number` (the number to guess) and `guesses` (number of attempts).

2. The `GuessingGame` constructor initializes the game by generating a random


`secret_number` within a specified range.
3. The `guessNumber` method takes a user's guess and provides feedback if it's
too high, too low, or correct.

4. In the `main` function, we create an instance of `GuessingGame` with a range


from 1 to 100.

5. The program uses a `do-while` loop to repeatedly prompt the user for a guess.

6. If the user enters 0, the program quits and reveals the secret number.

7. If the user guesses correctly, the program displays a congratulatory message


along with the number of guesses it took.

This program allows the user to interactively guess a randomly generated number
within a specified range.

You might also like