Answer:
The code is given below in Java with appropriate comments
Step-by-step explanation:
//Simulation of first to one game
import java.util.Random;
public class DiceGame {
// Test method for the Dice game
public static void main(String[] args) {
// Create objects for 2 players
Player player1 = new Player("P1", 50);
Player player2 = new Player("P2", 50);
// iterate until the end of the game players roll dice
// print points after each iteration meaning each throw
int i = 0;
while (true) {
i++;
player1.rollDice();
System.out.println("After " + (i) + "th throw player1 points:"
+ player1.getPoints());
if (player1.getPoints() == 1) {
System.out.println("Player 1 wins");
break;
}
player2.rollDice();
System.out.println("After " + (i) + "th throw player2 points:"
+ player2.getPoints());
if (player2.getPoints() == 1) {
System.out.println("Player 2 wins");
break;
}
}
}// end of main
}// end of the class DiceGame
// Player class
class Player {
// Properties of Player class
private String name;
private int points;
// two argument constructor to store the state of the Player
public Player(String name, int points) {
super();
this.name = name;
this.points = points;
}
// getter and setter methods
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
// update the points after each roll
void rollDice() {
int num = Die.rollDice();
if (getPoints() - num < 1)
setPoints(getPoints() + num);
else
setPoints(getPoints() - num);
}
}// end of class Player
// Die that simulate the dice with side
class Die {
static int rollDice() {
return 1 + new Random().nextInt(6);
}