76.5k views
4 votes
Your program Assignment This game is meant for tow or more players. In the same, each player starts out with 50 points, as each player takes a turn rolling the dice; the amount generated by the dice is subtracted from the player's points. The first player with exactly one point remaining wins. If a player's remaining points minus the amount generated by the dice results in a value less than one, then the amount should be added to the player's points. (As a alternative, the game can be played with a set number of turns. In this case the player with the amount of pints closest to one, when all rounds have been played, sins.) Write a program that simulates the game being played by two players. Use the Die class that was presented in Chapter 6 to simulate the dice. Write a Player class to simulate the player. Enter the player's names and display the die rolls and the totals after each round. I will attach the books code that must be converted to import javax.swing.JOptionPane; Example: Round 1: James rolled a 4 Sally rolled a 2 James: 46 Sally: 48 OK

1 Answer

2 votes

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);

}

User Digiarnie
by
3.0k points