// RygGame.cpp // Program description: Program to generate a random // number b/n 100 and 999 and accept users guess. // The user keeps guessing untill he guesses the random // number. The program gives the user a hint if he gueesed // one of the digits but its one wrong place. #include #include #include #include #include using namespace std; class RygGame { public: //RygGame constructor RygGame(bool exit_flag); //Method to set the random number void setRandom(); //Method to accept users guess and return true if correct bool guessedNumber(const string& guessed); private: int MIN; //Minimum value of the random number int MAX; //Maximum value of the random number int randomNumber; //Splits the random number into a array of single int's int randomArray[3]; }; int main() { string g; bool exit_flag = false; RygGame game(exit_flag); game.setRandom(); // Keeps asking the user to guess until he is correct while(exit_flag != true) { cout << "Please enter a guess(100-999)?" << endl; cin >> g; cout << endl; exit_flag = game.guessedNumber(g); } cin >> g; // This just keeps the program from exiting. } RygGame::RygGame(bool exit_flag) { MIN = 100; MAX = 999; } void RygGame::setRandom() { int i = 0; //Genrates the random number int lowest=MIN, highest=MAX; int range=(highest-lowest)+1; srand (time (0)); rand( ); randomNumber = lowest+int(range*rand()/(RAND_MAX + 1.0)); //Splits the random number into a array of three while(randomNumber >= 100) { randomNumber = randomNumber - 100; i++; } randomArray[0] = i; i = 0; while(randomNumber >= 10) { randomNumber = randomNumber - 10; i++; } randomArray[1] = i; randomArray[2] = randomNumber; } bool RygGame::guessedNumber(const string& guessed) { int green = 0; int yellow = 0; int red = 0; bool exit; //Splits the users input into three integer variables int one = (guessed[0] - '0'); int two = (guessed[1] - '0'); int three = (guessed[2] - '0'); //Compares the imput to the random number if(one == randomArray[0]) green++; else if (one == randomArray[1] && randomArray[1] != two) yellow++; else if (one == randomArray[2] && randomArray[2] != three) yellow++; else red++; if(two == randomArray[1]) green++; else if (two == randomArray[0] && randomArray[0] != one) yellow++; else if (two == randomArray[2] && randomArray[2] != three) yellow++; else red++; if(three == randomArray[2]) green++; else if (three == randomArray[0] && randomArray[0] != one) yellow++; else if (three == randomArray[1] && randomArray[1] != two) yellow++; else red++; //If all three are correct them exit the while loop and print message if(green == 3) { cout << "CONGRATILATOINS YOU HAVE GUESSED THE NUMBER!" << endl; exit = true; } //Otherwise just print how close you were else { cout << " You have " << red << "red" << endl; cout << " " << green << "green" << endl; cout << " " << yellow << "yellow" << endl; exit = false; } return exit; }