#include #include #include using namespace std; // horse class class Horse{ public: // constructor Horse(){ position = 0; } // access private position int getPosition(){ return position; } // flips a coin, advances ~50% of times void advance(){ if (rand() % 2){ // either 0 or 1 position++; } } private: int position; // position of horse on track }; // race as in event and race as in track class Race{ public: // constructors Race(){ length = 32; // default length numHorses = 4; // default number of horses horses = new Horse[numHorses]; // make some horses } Race(int length){ this->length = length; // defined length this->numHorses = 4; // default number of horses horses = new Horse[numHorses]; // make some horses } // get me those horses Horse *getHorses(){ return horses; } // prints one lane void printLane(int lane){ // which lane int i = 0; for (i = 0; i < length; i++){ // prints the horses number at its latest position if (i == horses[lane].getPosition()){ cout << lane; // prints a lane visual } else { cout << "."; } // end if } // end for cout << endl; // newline and stream flush } // all the horses flip a coin and advance accordingly void step(){ int i = 0; // all horses in the race for (i = 0; i < numHorses; i++){ horses[i].advance(); // horses know how to advance } } // prints each lane void printAllLanes(){ int i = 0; for (i = 0; i < numHorses; i++){ printLane(i); } } // checks if any horses have won or tied bool isFinished(){ int i = 0; // all horses in the race for (i = 0; i < numHorses; i++){ if (horses[i].getPosition() == length){ return true; // one or more winners } } return false; } // this function is not used // it was mentioned in the UML diagram // I prefer to include the run loop in the main function // start the race void start(){ while (!this->isFinished()){ // stop if there's a winner this->printAllLanes(); // update CLI this->step(); // all horses advance... cin.ignore(); // ...when the user presses enter } } // prints winner(s) void printWinners(){ cout << "horse(s)"; int i = 0; // check all the horses for (i = 0; i < numHorses; i++){ // if horse at i finished... if (horses[i].getPosition() == length){ cout << " " << i; // ...horse at i won! } } cout << " won (tied)!" << endl; } private: Horse *horses; // horses int numHorses; // number of horses (size of array) int length; // length of the track }; int main(){ // random number seed srand(time(NULL)); // crate a race Race race = Race(); // while the race is underway while(!race.isFinished()){ race.printAllLanes(); // update CLI race.step(); // all horses advance... // tell the user what to do cout << "Press enter for another turn:"; cin.ignore(); // ...when the user presses enter } race.printWinners(); // print the winners return EXIT_SUCCESS; } // end main