【问题标题】:How to roll 2 dice simultaneously and keep recording its sum如何同时掷 2 个骰子并记录其总和
【发布时间】:2019-10-23 01:43:45
【问题描述】:

需要编写一个模拟骰子游戏的程序。 2 名玩家轮流掷 2 个骰子。在每一回合,他们记录两个骰子的总和并将其添加到总数中。如果玩家掷出双骰子(两个骰子的值相同),则玩家可以再次掷骰子。第一个达到 75 的玩家将获胜

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

【问题讨论】:

  • 那么你的问题是什么。为什么没有实现所有要求?
  • 对于一位用户,sum = die1 + die2; 也应该是 sum += die1 + die2;
  • 条件应该是while (sum<75)而不是while (sum>=75)
  • 初始if 声明在这里没有任何用途。您还需要跟踪两个不同的总和,每个玩家一个。让每个玩家继续滚动,直到其中一个总和达到 75,然后结束游戏。

标签: java dice


【解决方案1】:

几个简短的评论(一些已经在 cmets 中发现):if 没有做太多,因为在循环之外,循环条件是反转的和不完整的,最后应该为两个玩家保留总和,不只是 1.

一个基本的选择可能是:

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

然后您可以检查哪个玩家获胜并在循环后显示分数以及一些消息:

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

干杯!

【讨论】:

    猜你喜欢
    • 2020-06-06
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多