Your task this week is to create a \'Dice\' class which contains a collection of
ID: 3747928 • Letter: Y
Question
Your task this week is to create a 'Dice' class which contains a collection of 'Die' as a private variable and simulates the rolling of multiple dice.
You should include your 'Die' class in the code, in the same namespace as the 'Dice' class, and make a private variable to store an array of these 'Die' in the 'Dice' class.
The 'Dice' class must have 2 constructors:
public Dice(int dice)
This constructor creates an instance of Dice with the specified number of dice. These dice should have the same default number of faces as the 'Die' class (6), and the same default face value (1).
public Dice(int dice, int faces)
This constructor creates an instance of Dice with the specified number of dice, each with faces number of faces, and the same default face value as the 'Die' class (1). As with the 'Die' class, the minimum number of faces is 3.
The class must also have two other methods, which are similar to the methods of the 'Die' class:
public void RollDice()
This method must roll the dice.
public int GetFaceValue()
This method must return the total face value of all the dice (e.g. if there was 2 dice with face values 3 and 6, this should return 9)
Now, given the defaults, the code Dice myDice = new Dice(1); should create a single six-sided die, and rolling this should produce values between 1 and 6.
Dice myDice = new Dice(2, 4);, however, should create two four-sided dice. Rolling these dice should produce values between 2 and 8.
USE CODE BELOW! (DO NOT REPOST ANSWERS)
Explanation / Answer
#include <iostream>
#include <stdlib.h> /* rand */
using namespace std;
const int MAX_SIZE = 6;
namespace DiceRoller{
public class Die {
// You should include your Die class from the previous exercise here
int size = MAX_SIZE;
public Die(int size){
this.size=size;
}
}// end class Die
public class Dice {
// Implement your 'Dice' class here
// ...
Die dice[MAX_SIZE];
int faceValue = 0;
int max = 0;
int min = 0;
public Dice(int dice){
dice[dice];
for(i=0;i<dice;i++){
Die die= new Die(6);
dice[i]=die;
}
}
public Dice(int dice, int faces){
dice[dice];
for(i=0;i<dice;i++){
Die die= new Die(faces);
dice[i]=die;
}
}
public void RollDice(){
for(int i=0;i<sizeof(dice);i++){
max = max + dice[i].size;
}
min = sizeof(dice);
faceValue = rand() % max + min
}
public void GetFaceValue(){
return this.faceValue;
}
}// end class Dice
int main()
{
Dice myDice = new Dice(2, 4);
myDice.RollDice();
cout<<myDice.GetFaceValue();
return 0;
}
}
If you are getting some error please remove this namespace DiceRoller{ along with closing }. I have added it just because you have given in your question.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.