Write a C++ program to implement a three-player dice game with the following rules:
1. Begin with Player A and roll two dice: dice d1 and dice d2.
2. If the sum of the two dice is odd, then accumulate it as the score of Player A. If even, then the score is 0.
3. Then roll d1 and d2 for Player B.
4. If the sum of the two dice is odd, then accumulate it as the score of Player B. If even, then the score is 0.
5. Then roll d1 and d2 for Player C.
6. If the sum of the two dice is odd, then accumulate it as the score of Player C. If even, then the score is 0.
7. Repeat steps 1 to 6 for n rounds, where n is a positive integer provided as input by the user.
Things to keep in mind:
1. You have to implement three classes, namely Player class, Dice class, and Game class, and a driver program test class that contains the main function.
2. Function in the driver program is: i) Method: int main(). It is the main method in which an object of class Game is created and the method play() is invoked.
#include <iostream>
#include <string>
#include<ctime> //For time()
#include<cstdlib> //For rand() and srand()
using namespace std;
int isSumOdd(){
//1. Begin with Player A and roll two dice: dice d1 and dice d2.
int d1=rand()%6 +1;
int d2=rand()%6 +1;
int sum=d1+d2;
//2. If the sum of the two dice is odd, then accumulate it as the score of Player A. If even, then the score is 0.
if(sum%2==0){
return 0;
}else{
return 1;
}
}
int main() {
srand(time(NULL));
int scoreA=0;
int scoreB=0;
int scoreC=0;
int n=-1;
while(n<1){
cout<<"Enter the number of rounds >=1: ";
cin>>n;
}
for(int i=0;i<n;i++){
//1. Begin with Player A and roll two dice: dice d1 and dice d2.
//2. If the sum of the two dice is odd, then accumulate it as the score of Player A. If even, then the score is 0.
scoreA+=isSumOdd();
//3. Then roll d1 and d2 for Player B.
//4. If the sum of the two dice is odd, then accumulate it as the score of Player B. If even, then the score is 0.
scoreB+=isSumOdd();
//5. Then roll d1 and d2 for Player C.
//6. If the sum of the two dice is odd, then accumulate it as the score of Player C. If even, then the score is 0.
scoreC+=isSumOdd();
//7. Repeat steps 1 to 6 for n rounds, where n is a positive integer provided as input by the user.
}
cout<<"\nPlayer A scores is "<<scoreA<<"\n";
cout<<"\nPlayer B scores is "<<scoreB<<"\n";
cout<<"\nPlayer C scores is "<<scoreC<<"\n";
if(scoreA>scoreB && scoreA>scoreC){
cout<<"\nPlayer A is winner.\n\n";
}else if(scoreB>scoreA && scoreB>scoreC){
cout<<"\nPlayer B is winner.\n\n";
}else{
cout<<"\nPlayer C is winner.\n\n";
}
cin>>n;
return 0;
}
Comments
Leave a comment