Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <string>
- #include <ctime>
- #define LOW 0
- #define HIGH 100
- using namespace std;
- class Player {
- private:
- int low = LOW;
- int high = HIGH;
- public:
- virtual int getGuess() = 0;
- void setLow(int ip) { low = ip; }
- void setHigh(int ip) { high = ip; }
- int getLow() { return low; }
- int getHigh() { return high; }
- void ShowRange() { cout << low << "~" << high << endl; }
- void Clear(){
- low = LOW;
- high = HIGH;
- }
- };
- class HumanPlayer :public Player {
- public:
- int getGuess() {
- int temp;
- while (1) {
- //cout << "enter : ";
- cin >> temp;
- if (temp > getLow() && temp < getHigh()) {
- return temp;
- }
- else cout << "you guess out of range." << endl;
- }
- }
- };
- class ComputerPlayer :public Player {
- public:
- int getGuess() {
- int temp = rand() % (getHigh() - getLow() - 1) + 1 + getLow();
- cout << "computer guess " << temp << endl;
- return temp;
- }
- };
- int checkForWin(int guess, int answer)
- {
- if (answer == guess)
- {
- cout << "You're right! You win!" << endl;
- return 1;
- }
- else if (answer < guess) {
- cout << "Your guess is too high." << endl;
- return 0;
- }
- else {
- cout << "Your guess is too low." << endl;
- return -1;
- }
- }
- void play(Player &player1, Player &player2)
- {
- srand(time(NULL));
- int answer = 0, guess = 0;
- answer = rand() % 99 + 1;
- int win = 0;
- while (1)
- {
- cout << "Player 1's turn to guess." << endl;
- guess = player1.getGuess();
- win = checkForWin(guess, answer);
- if (win == 1) {
- player1.Clear();
- player2.Clear();
- return;
- }
- else if (win == 0) {
- player1.setHigh(guess);
- player2.setHigh(guess);
- }
- else {
- player1.setLow(guess);
- player2.setLow(guess);
- }
- player1.ShowRange();
- cout << "Player 2's turn to guess." << endl;
- guess = player2.getGuess();
- win = checkForWin(guess, answer);
- if (win == 1) {
- player1.Clear();
- player2.Clear();
- return;
- }
- else if (win == 0) {
- player1.setHigh(guess);
- player2.setHigh(guess);
- }
- else {
- player1.setLow(guess);
- player2.setLow(guess);
- }
- player1.ShowRange();
- }
- }
- int main()
- {
- HumanPlayer playerH1, playerH2;
- ComputerPlayer playerC1, playerC2;
- play(playerH1, playerH2);
- play(playerH1, playerC1);
- play(playerC1, playerC2);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment