Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Convert this Dice Race C++ program into a class: #include <iostream> #include <s

ID: 3669219 • Letter: C

Question

Convert this Dice Race C++ program into a class:

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main()
{
   // initialize jack and jill to 0
   int roll, jack = 0, jill = 0;
   // initialize finished to false
   bool finished = false;
   string winner;
   // initializing random number generator
   srand(time(NULL));
  
   // loop until game is finished
   do
   {
       // Jack’s turn.
       // generate a random number in the range 1 to 6
       roll = (rand() % 6) + 1;
       // add it to jack
       jack += roll;
      
       // print roll value folowed by jack position
       cout << roll << " "<< jack << " ";
      
       // if jack equals jill, tumble jill
       if(jack == jill)
       {
           // generate random number in range 1 to 3 and deduct it from jill
           jill -= (rand() % 3) + 1;
           // if jill goes to negative position, set jill to 0
           if(jill < 0)
               jill = 0;
           // print jill position and Tumble Jill
           cout << jill << " " << "Tumble Jill!";
       }
       // feed new line
       cout << endl;
       // if jack reached the top of hill
       if(jack >= 20)
       {
           // Set finished to true
           finished = true;
           // Set winner to “Jack”
           winner = "Jack";
           // Skip Jill's turn if Jack already won
           break;
       }
      
       //Jill's turn
       // generate a random number in the range 1 to 6
       roll = (rand() % 6) + 1;
       // print roll value
       cout << roll << " ";
       // add it to Jill's position
       jill += roll;
      
       // if Jill equals Jack, tumble Jack
       if(jack == jill)
       {
           // generate random number in range 1 to 3 and deduct it from jack
           jack -= (rand() % 3) + 1;
           // if jack goes to negative position, set jack to 0
           if(jack < 0)
               jack = 0;
           // print jack and jill's positions and Tumble jack
           cout << jack << " " << jill << " " << "Tumble Jack!" << endl;
       }
       else
           // otherwise print only jill's position
           cout << " " << jill << endl;
       // if jack reached the top of hill
       if(jill >= 20)
       {
           // Set finished to true
           finished = true;
           // Set winner to “Jill”
           winner = "Jill";
       }
   } while(!finished); // loop until finished is true
   // print winner
   cout << winner << " wins!" << endl;
   return 0;
}

Side Note: Rules of the game above is it has two players, Jack and Jill, and a board with 20 squares. Players take turns by rolling a 6-sided die and move forward the number of squares shown. If a player lands on the same square as his or her opponent, the opponent tumbles back a random number of 1 – 3 squares. The first player to reach the "top" of the hill (square 20) wins.

I don't need anything fancy, but it needs:

Use only C++ language features with comments

Name the class Player since it will represent the game from the standpoint of a player.

You have some decisions to make. Name your methods with action words. For instance, you might have a move() method that makes a move for the player object passed in by reference.

Overload the “is equal to” operator ==. For example:  bool operator== (const Player& rhs) const;

Include a printBoard() or printTurn() method that prints output per the sample below. An output overload function is not a good fit for this program because it can only take one parameter.

Once the code is working, add the following. Ask the user to input an odd number N. Run the program for N games, keeping track of how many times Jack won and Jill won. Store this information as a private variable in the Player class. Update class constructors and methods to support this new field. After all games are complete, print total games won by each player and a statement declaring one Player as the Grand Champion. It should look like the sample output below.

Sample Output

Roll Jack Jill

------------------------           

5 5        

5 2 5 Tumble Jack!

6 8        

2 7   

4 12       

5 10 12   Tumble Jack!

2 12 11   Tumble Jill!

5 16  

1 13       

5 21            

Jill wins game 1!

… additional games printed here …

Jack wins game 7!

Jack won 5 games and Jill won 2 games.

Jack is the Dice Race Grand Champion!

Explanation / Answer


#include <iostream>
#include <string>
#include <vector>
#include <time.h>

class Player {
   std::string name;
   int wins;
   int position;
public:
   Player(std::string p_name) :
       name(p_name),
       position(1),
       wins(0)
   {
   };
   int getPosition() const
   {
       return position;
   };
   void setPosition(int p_position)
   {
       position = p_position;
   };
   void adjustPosition(int delta)
   {
       position += delta;
   };
   int getWins() const
   {
       return wins;
   };
   int setWins() const
   {
       return wins;
   };
   void adjustWins(int delta)
   {
       wins += delta;
   };
   std::string getName() const
   {
       return name;
   }
};

class DiceRace {
private:
   std::vector<Player> players;
   Player* winner;
   int total_players;
   bool has_winner;
   int winning_space;
   int dice_sides;
   int max_penalty_spaces;
   int min_penalty_spaces;
   int rollDice()
   {
       return std::rand() % dice_sides + 1;
   };
public:
   DiceRace(std::vector<Player> &p_players) :
       players(p_players),
       total_players(p_players.size()),
       has_winner(false),
       winning_space(20),
       dice_sides(6),
       max_penalty_spaces(3),
       min_penalty_spaces(1)
   {
   };
   Player& getWinner() const
   {
       return *winner;
   };
   std::vector<Player> getPlayers() const
   {
       return players;
   };
   void resetPositions() {
       for (int i = 0; i < total_players; ++i)
       {
           Player& player = players[i];
           player.setPosition(1);
       }
       has_winner = false;
   };
   void movePlayer(Player* player_ptr)
   {
       Player& current_player = *player_ptr;
       //cout << &current_player << " - test ";
       int spaces_to_move = rollDice();
       current_player.adjustPosition(spaces_to_move);
       int player_space = current_player.getPosition();

       if (player_space >= winning_space)
       {
           has_winner = true;
           winner = &current_player;
       }
       else
       {
           std::vector<Player*> playersTumbled;
           // Iterate through other players
           for (int i = 0; i < total_players; ++i)
           {
               Player& other_player = players[i];
               if (&other_player == player_ptr)
                   continue;

               if (player_space == other_player.getPosition())
               {
                   // Player lands on other player's position
                   int spaces_back = rand() % (max_penalty_spaces - min_penalty_spaces + 1) + min_penalty_spaces;
                   other_player.adjustPosition(-1 * spaces_back);
                   playersTumbled.push_back(&other_player);
               }
           }

           // Print
           std::cout << spaces_to_move << " ";
           for (int i = 0; i < total_players; ++i)
           {
               Player& other_player = players[i];
               std::cout << other_player.getPosition() << " ";
           };
           for (std::vector<Player*>::iterator it = playersTumbled.begin(); it < playersTumbled.end(); it++) {
               std::cout << "Tumble " << (**it).getName() << "! ";
           }
              
           //cout << current_player.getName() << current_player.getPosition() << " " << &current_player << " - test ";
           std::cout << std::endl;
       }
   };
   void play()
   {
       // Print header
       std::cout << "Roll ";
       for (int i = 0; i < total_players; ++i)
       {
           Player& other_player = players[i];
           std::cout << other_player.getName() << " ";
       };
       std::cout << std::endl << std::string((total_players + 1) * 8, '-') << std::endl;

       int turn_index = -1;
       while (!has_winner)
       {
           turn_index = (turn_index + 1) % total_players;
           movePlayer(&players[turn_index]);
       }
   }
};

int main() {
   std::srand(time(NULL));

   bool hasReceivedValidInput;
   int games_count;
   do
   {
       std::cout << "Input an odd number of Dice Race! games to play: ";

       std::string games_count_input;
       std::cin >> games_count_input;
       try
       {
           games_count = std::stoi(games_count_input);
           hasReceivedValidInput = games_count % 2 == 1;
           if (!hasReceivedValidInput)
               std::cout << "Please specify an odd integer."<< std::endl;
       }
       catch (std::invalid_argument)
       {
           hasReceivedValidInput = false;
           std::cout << "Invalid integer: " << games_count_input << std::endl;
       }
   } while (!hasReceivedValidInput);

   std::cout << "Going to play " << games_count << " games" << std::endl;

   DiceRace game{ std::vector<Player> {
       /*
       Player("Rob"),
       Player("Tom"),
       Player("Juliet"),
       Player("Sam"),//*/
       Player("Jack"),
       Player("Jill")
   } };
   for (int count = 0; count < games_count; ++count)
   {
       game.play();
       Player& winner = game.getWinner();

       std::cout << winner.getName() << " has won!" << std::endl << std::endl;

       winner.adjustWins(1);

       // Reset players
       game.resetPositions();
   }

   Player *grandWinner = NULL;
   std::vector<Player> &players = game.getPlayers();
   for (int i = 0; i < players.size(); ++i)
   {
       Player& player = players[i];
       int gamesWon = player.getWins();

       if (grandWinner == NULL || (*grandWinner).getWins() < gamesWon)
           grandWinner = &player;

       std::cout << player.getName() << " won " << gamesWon << (gamesWon == 1 ? " game" : " games");

       if (i == players.size() - 2)
       {
           std::cout << ", and ";
       }
       else if (i < players.size() - 1)
       {
           std::cout << ", ";
       }
   }
   std::cout << "." << std::endl << std::endl;

   std::cout << "The grand winner of the Dice Race! games is " << (*grandWinner).getName();


   std::string a;
   std::cin >> a;
   return 0;
}