# CECS 277 – Lab 6 – Composition solution

\$30.00

Original Work ?

5/5 - (1 vote)

## Yahtzee

Create a dice game similar to Lecture 10. Use the following class diagram for your program:
Die Class (Die.java) –

1. Constructor – assign the number of sides from the value passed in. Set value to 0.
2. roll – generate a random number 1-sides and assign it to value. Return the value.
3. equals – return true if both the sides and value are the same.

4. lessThan – return true if the implicit die is less than the explicit die.
5. difference – return the difference between the implicit and explicit dice values.
6. toString – return the value of the die as a String.

Player Class (Player.java) –
1. Constructor – construct an array of 3 dice, then use a loop to construct each Die object as
a 6-sided die.
2. getPoints – return the players points.

3. sort – sort the values of the three dice in ascending order (use the lessThan method in
Die). Note: swap the whole Die objects, not just their values.
4. pair – return true and add 1 to the player’s points if two of the dice values are the same
(use the equals method in Die).

5. threeOfAKind – return true and add 3 to the player’s points if all three of the dice values
are the same (use the equals method in the Die class).
6. series – return true and add 2 to the player’s points if the dice are in a series (ex. [1,2,3],
or [3,4,5]). Hint: your dice should already be sorted, so you can use the difference
method to find out if their values are only different by one.

7. roll – roll the three dice in the array, and then call the sort method.

8. toString – return a string in the format: D1=2, D2=4, D3=6.
Main Class (Main.java) – Create a method called takeTurn that passes in a Player object, calls
the roll method, displays the player’s dice, displays the results of the roll, and then displays the
player’s score. In the main method, construct a Player object and have a loop that calls the
takeTurn method until the user decides to quit. Display the final points when the user decides to
quit the program. Check that the user’s input is valid.

Example Output:
Yahtzee
Rolling Dice…D1=2,D2=3,D3=5
Score = 0 points.
Play again? (Y/N) X
Invalid input.
Play again? (Y/N) Y
Rolling Dice…D1=2,D2=3,D3=4
You got a series of 3!
Score = 2 points.
Play again? (Y/N) Y
Rolling Dice…D1=1,D2=1,D3=3
You got a pair!
Score = 3 points.
Play again? (Y/N) Y
Rolling Dice…D1=4,D2=4,D3=4
You got 3 of a kind!
Score = 6 points.
Play again? (Y/N) Y
Rolling Dice…D1=1,D2=3,D3=6