Vatsal Rajyaguru
Vatsal Rajyaguru

Reputation: 51

How to roll 2 dice simultaneously and keep recording its sum

Need to write a program that simulates a game of dice. 2 players take alternate turns rolling 2 dice. On each turn, they record the sum of the two dice and add this to their total. If a player rolls a doublet (both dice have the same value), then the player gets to roll again. The first player to reach a total of 75 will win

import java.util.*;

public class DieGame {

    public static void main (String[] args) {

        Random generator = new Random ();

        int die1;
        int die2;
        int sum;

        int sum = 0;

        if (die1==die2)
        {     
            do 
            {
            die1 = generator.nextInt(6) + 1;
            die2 = generator.nextInt(6) + 1;
            sum = die1 + die2;
            }
            while (sum>=75)
        }
    }
}

Upvotes: 0

Views: 993

Answers (1)

Abs
Abs

Reputation: 300

Couple of quick remarks (some already spotted in the comments): the if is not doing much since out of the loop, the loop condition is inverted and incomplete, and finally the sum should be kept for both of the two players, not only 1.

A basic option could be :

Random generator = new Random();    
int die1, die2;
int[] sumForPlayers = { 0, 0 };

int currentPlayerIndex = 0;

do {
    die1 = generator.nextInt(6) + 1;
    die2 = generator.nextInt(6) + 1;

    sumForPlayers[currentPlayerIndex] += die1 + die2;

    if (die1 != die2) {
        currentPlayerIndex = (currentPlayerIndex + 1) % 2;
    }
} while ((sumForPlayers[0] < 75) && (sumForPlayers[1] < 75));

You can then check which player wins and display the scores along with some messages after the loop :

if (sumForPlayers[0] >= 75) {
    // Player 1 has won! let the world know
} else {
    // Player 2 has won! Show the score details if needed
}

Cheers!

Upvotes: 1

Related Questions