/* An object-oriented version of "Master-Mind." Now, the game is bundled up into "Class." The class has two variables -- "answer," which is the answer, and "nguesses", which is the number of guesses that the user has made. There is a method, "play_game()", which is how you play a game, and two other methods: "get_legal_guess()," where the user is repeatedly prompted to make a guess until he/she makes a legal guess, and "is_legal_answer(n)", which takes on parameter, n, and returns whether it is legal. Note, now the main() function does very little. Note also the syntax of implementing the methods. */ #include using namespace std; class MasterMind { public: int is_legal_answer(int n); int get_legal_guess(); void play_game(); private: int answer; int nguesses; }; int MasterMind::get_legal_guess() { int guess; while(1) { cout << "Player 2: Make a guess, please: "; cin >> guess; if (is_legal_answer(guess)) return guess; cout << guess << " is not a legal answer. "; } } /* This checks to see whether n is a legal answer -- that is, is it between 0 and 999, and does it have no repeated digits? */ int MasterMind::is_legal_answer(int n) { int dr, dl, dm; if (n < 0 || n > 999) return 0; dr = n % 10; dl = n / 100; dm = (n / 10) % 10; if (dl == dr || dl == dm || dm == dr) return 0; return 1; } /* Note that play_game now uses a do/while loop to have player one enter the answer */ void MasterMind::play_game() { int guess; int right; int dr, dm, dl; int ar, am, al; int correct_number; int correct_position; do { cout << "Player 1 -- Enter an answer: "; cin >> answer; if (!is_legal_answer(answer)) { cout << "Not a legal answer\n"; } } while (!is_legal_answer(answer)); ar = answer % 10; al = answer / 100; am = (answer / 10) % 10; nguesses = 1; while (1) { guess = get_legal_guess(); if (guess == answer) { cout << "Right! You took " << nguesses << " move"; if (nguesses != 1) cout << "s" ; cout << "." << endl; return; } else { dr = guess % 10; dl = guess / 100; dm = (guess / 10) % 10; correct_position = 0; if (dr == ar) correct_position++; if (dl == al) correct_position++; if (dm == am) correct_position++; correct_number = 0; if (dr == ar || dr == am || dr == al) correct_number++; if (dm == ar || dm == am || dm == al) correct_number++; if (dl == ar || dl == am || dl == al) correct_number++; cout << "Correct position: " << correct_position << endl; cout << "Correct number: " << correct_number << endl; } nguesses++; } return; } int main() { MasterMind game; game.play_game(); return 0; }