For this assignment, create a dice game that uses at least two classes. One will
ID: 3579412 • Letter: F
Question
For this assignment, create a dice game that uses at least two classes. One will be a Die class that will simulate a 6-sided die. The program should simulate a dice game that rolls 5 dice for a player and 5 dice for the computer - the player's opponent. Use an array to keep track of the dice. If the player rolls 5 of a kind, they win. Otherwise, the scoring is as follows:
straight
(all numbers in sequence)
For both the computer and the player, display the value of the dice, the points earned by each and who won.
Roll Points 4 of a kind 40 3 of a kind 30 2 of a kind 20straight
(all numbers in sequence)
Explanation / Answer
Code:
Game.java:
public class Game {
public static void main(String[] args) {
// array to store user's score
int playerScore[]=new int[5];
//variable to store player's total score
int playerTotal;
//array to store computer's score
int computerScore[]=new int[5];
//variable to store computer's total score
int computerTotal;
//instantiating an object of Die class
Die die=new Die();
//Rollin 5 dice for player
for(int i=0;i<5;i++){
playerScore[i]=die.roll();
}
//Rollin 5 dice for computer
for(int i=0;i<5;i++){
computerScore[i]=die.roll();
}
System.out.println("Player's dice ");
for(int i=0;i<5;i++){
System.out.print(playerScore[i] +" ");
}
System.out.println(" Computer's dice ");
for(int i=0;i<5;i++){
System.out.print(computerScore[i]+" ");
}
playerTotal=calculatePoints(playerScore);
computerTotal=calculatePoints(computerScore);
System.out.println(" Player's total= "+ playerTotal);
System.out.println("Computer's total= "+ computerTotal);
if(playerTotal>computerTotal){
System.out.println("Player won!");
}
else if(playerTotal<computerTotal){
System.out.println("Computer won!");
}
else{
System.out.println("It's a tie");
}
}
static int calculatePoints(int array[]){
//this array will score the count of respective values;
int possibleValues[]=new int[6];
for(int i=0;i<5;i++){
possibleValues[array[i]-1]++;
}
//count will store the maximum count for which any value is repeated
int count=0;
for(int i=0;i<6;i++){
if(possibleValues[i]>count)
count=possibleValues[i];
}
switch(count){
case 1: return 35;
case 2: return 20;
case 3:return 30;
case 4:return 40;
case 5: return 50;
default: return 0;
}
}
}
Die.java:
package Model;
public class Die {
private int value;
public int roll(){
value=1 + (int)(Math.random() * 6);
return value;
}
}
Sample Run:
Player's dice
5 2 4 4 6
Computer's dice
1 2 5 1 3
Player's total= 20
Computer's total= 20
It's a tie
Player's dice
1 4 1 1 4
Computer's dice
1 4 1 4 3
Player's total= 30
Computer's total= 20
Player won!
Player's dice
4 6 4 1 4
Computer's dice
5 2 4 3 1
Player's total= 30
Computer's total= 35
Computer won!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.