Java Dice Game: Defined a class named Die and provide necessary data fields (Mem
ID: 3872270 • Letter: J
Question
Java Dice Game:
Defined a class named Die and provide necessary data fields (Members) and methods, make sure all your classes overwrites toString mathod, then write a class called PairOfDice, composed of two Die objects. Include methods to set and get the individual die values, a method to roll the dice, and a method that returns the current sum of the two die values Using the PairOfDice class you wrote, design and implement a class to play a game called Pig. In this game, the user competes against the computer. On each turn, the current player rolls a pair of dice and accumulates points. The goal is to reach 100 points before your opponent does. If, on any turn, the player rolls a 1, all points accumulated for that round are forfeited and control of the dice moves to the other player. If the player rolls two 1s in one turn, the player loses all the points accumulated thus far in the game and loses control of the dice. The player may voluntarily turn over the dice after each roll. Therefore, the player must decide to either roll again (be a pig) and risk losing points, or relinquish control of the dice, possibly allowing the other player to win. Implement the computer player such that it always relinquishes the dice after accumulating 20 or more points in any given round.Explanation / Answer
Following is the class Die:
import java.util.Random;
public class Die {
private int value;
public String toString(){
return "Current die value is "+Integer.toString(value);
}
// Method to set the current value of die object
public void setDieValue(int x){
value = x;
}
// Method to get the current value of die object
public int getDieValue(){
return value;
}
// Method to roll the die and set the value field
public void roll(){
Random rn = new Random(); // Random-Class object
int rollNum = rn.nextInt(6)+1; // Generates a random number between 1 to 6
value = rollNum;
}
}
Following is the class PairOfDice:
public class PairOfDice {
private Die die1;
private Die die2;
public PairOfDice(){
die1 = new Die();
die2 = new Die();
}
public String toString(){
return "Value rolled on Die 1 is "+Integer.toString(die1.getDieValue())
+" Value rolled on Die 2 is "+Integer.toString(die2.getDieValue())+" ";
}
// Method to roll the pair of dice
public void rollDice(){
die1.roll();
die2.roll();
}
// Method to return sum of numbers rolled on both die
public int getSum(){
return die1.getDieValue()+die2.getDieValue();
}
// Method to return number of 1s in roll
public int numOfOnes(){
if(die1.getDieValue()==1 && die2.getDieValue()==1) // 2 ones
return 2;
if(die1.getDieValue()!=1 && die2.getDieValue()!=1) // 0 ones
return 0;
return 1; // 1 one
}
}
Following is the class Pig which contains method main():
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class Pig {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
/*********************************************************
* A variable int turn decides whose turn it is to play.
* turn = 0 implies its user's turn
* turn = 1 implies its computer's turn
*********************************************************/
int turn = 0;
int roundScorePerson = 0;
int roundScoreComputer = 0;
int totalScorePerson = 0;
int totalScoreComputer = 0;
int ch = 0;
System.out.println("Let us play Pig!");
PairOfDice pd = new PairOfDice();
while(totalScorePerson<100 && totalScoreComputer<100){ // If anyone's score exceeds 100, game stops
if(turn==0){ // Implement game for player
pd.rollDice();
System.out.println("Total Score- Person: "+Integer.toString(totalScorePerson)+
" Comp: "+Integer.toString(totalScoreComputer));
System.out.println("Player turn");
System.out.println("Current round score of player: "+Integer.toString(roundScorePerson));
System.out.println(pd.toString());
if(pd.numOfOnes()==2){ // If 2 ones are rolled
turn = turn^1;
// ^ (XOR) operator toggles the value of turn (changes it to 0 of it is 1 and vice versa)
totalScorePerson = 0;
// Reduce total score of person to 0
continue;
// Continue to next turn
}
if(pd.numOfOnes()==1){ // If 2 ones are rolled
turn = turn^1;
// ^ (XOR) operator toggles the value of turn (changes it to 0 of it is 1 and vice versa)
roundScorePerson = 0;
// Reduce round score of person to 0
continue;
// Continue to next turn
}
// If no ones are rolled following code is executed
roundScorePerson += pd.getSum();
System.out.print("Enter 1 to roll again and 0 to change turn :");
ch = input.nextInt();
if(ch == 0){
totalScorePerson += roundScorePerson;
roundScorePerson = 0;
turn = turn^1;
continue;
}
}
if(turn==1){ // Implement game for computer
try{
TimeUnit.SECONDS.sleep(2);
}
catch(Exception e){
}
pd.rollDice();
System.out.println("Total Score- Person: "+Integer.toString(totalScorePerson)+
" Comp: "+Integer.toString(totalScoreComputer));
System.out.println("Computer turn");
System.out.println("Current round score of comp: "+Integer.toString(roundScoreComputer));
System.out.println(pd.toString());
if(pd.numOfOnes()==2){
turn = turn^1;
// ^ (XOR) operator toggles the value of turn (changes it to 0 of it is 1 and vice versa)
totalScoreComputer = 0;
// Reduce total score of computer to 0
continue;
// Continue to next turn
}
if(pd.numOfOnes()==1){ // If 2 ones are rolled
turn = turn^1;
// ^ (XOR) operator toggles the value of turn (changes it to 0 of it is 1 and vice versa)
roundScoreComputer = 0;
// Reduce round score of person to 0
continue;
// Continue to next turn
}
// If no ones are rolled following code is executed
roundScoreComputer += pd.getSum();
if(roundScoreComputer >= 20){ // If round score of computer exceeds 20, change turn
ch = 0;
}
else
ch = 1;
if(ch == 0){
totalScoreComputer += roundScoreComputer;
roundScoreComputer = 0;
turn = turn^1;
continue;
}
}
}
// Display message of result
if(totalScorePerson>=100){
System.out.println("Congratulations! You won!");
}
if(totalScoreComputer>=100){
System.out.println("Bad luck. Computer won.");
}
input.close(); // Close the scanner object
}
}
Few important notes:
1) the program uses TimeUnit.SECONDS.sleep(2) method to pause execution for a 2 seconds so you can see what the computer is getting as the dice are rolled
2) A variable turn is used to decide if its turn of player or computer. It is player's turn if turn=0 and comp's turn if turn=1. We can change turn from 0 to 1 or 1 to 0 by simply applying XOR operator on turn with 1 (i.e. turn = turn^1). You can read more about the xor operator.
I have tried and commented all possible points of doubt.
Hope this helps.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.