Problem #1: Create a data structure for the die.
This die object should store AT LEAST the number of sides and the current face value. You can implicitly assume that each side has a unique value ranging from 1 to NUM_SIDES. You could create dice with different number of sides, or you could mutate the same dice collection to alter the value of NUM_SIDES. Regardless, the face values will still range from 1 to NUM_SIDES.
public class Die {
private int currentValue;
private int numberOfSides;
public int getCurrentValue() { return currentValue;}
public int roll() {currentValue = getRandomInteger();}
}
Problem #2: Rolling the dice
First of all, store the dice into an array of die (or some other collection that allow duplicates). Your die object should have a roll()
function that will change the current value. Your getRandomInteger()
should be called from this method and the result of this call should be stored in the currentValue
field.
Problem #3: Adding the values
Iterate through the array of die and add get their current values. This means that your Die
class should have a getCurrentValue()
method. Accumulate the sum of the dice.
Things to consider
- Should all die have the same number of sides? I don't think this matters one bit. In fact, I will argue that you could use the same implementation for a game like Yahtzee where the dice are the same number of sides or AD&D where you have dice of different number of sides.
- Re-roll Rules. In a game like Yahtzee, you don't always roll the entire collection. You need to consider a strategy where the user could pick SOME of the dice to reroll. I don't remember if this is true for AD&D but if it is, you need to consider how to differentiate between each die and partially accumulate the current values of each roll.
- Randomization. For a more realistic randomization, consider seeding your randomizer with something like the current time. Also, you need to set your boundaries for the possible roll values to be between 1 and NUM_SIDES (inclusive).
- Setting the number of sides. Assuming the number of sides could change, you will need to add a setter method to set the number of sides. You will also need to pass this parameter via the constructor so that the dice are set to some valid number upon instantiation of a die object.