Roll the Dice
Learn to roll the dice randomly at start, on click, and on valid points.
We'll cover the following
Starting with random dice
Greedy should always use random dice.
- In the constructor, remove the code that created the six dice.
- Add code inside the for loop to create a random die using the Die constructor with no parameter values.
...
private void initGUI() {
...
diceRowPanel.add(dicePanel);
for(int i=0; i<6; i++) {
dice[i] = new Die();
dice[i].addMouseListener(new MouseAdapter() {
...
}
...
After including the above in your code, try running it. The program will roll random dice and will update the total points of the selected dice as each die is clicked. Points should be calculated correctly whenever the selected dice include ones, fives, three of a kind, four of a kind, five of a kind, six of a kind, or a straight.
Rolling remaining dice
When the user clicks the “Roll” button, update the points for the round, roll the remaining dice, and disable the “Roll” button, because no die is selected yet.
- Disable the
rollButton
using JButton’ssetEnabled()
method when it is first added to the window ininitGUI()
. - Add an Action Listener to
rollButton
. Use JButton’saddActionListener()
method, with a newActionListener
object as the parameter value. In theActionListener,
add a public method calledactionPerformed()
. TheactionPerformed()
method should take anActionEvent
as a parameter and return nothing. - In
actionPerformed()
, callupdatePoints()
, callrollRemainingDice()
, and disable the “Roll” button using JButton’ssetEnabled()
method.
Note: Do not execute it yet. The code will have a syntax error because updatePoints()
and rollRemainingDice()
do not exist yet.
...
private void initGUI() {
...
rollButton.setEnabled(_______);
rollButton.addActionListener(________________ {
________________ actionPerformed(__________) {
_____________();
_____________();
rollButton._____________;
}
});
buttonPanel.add(rollButton);
...
Get hands-on with 1200+ tech skills courses.