需要编写一个模拟骰子游戏的程序。 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)
}
}
}
答案 0 :(得分:1)
快速备注(在注释中已经有些注释)的组合: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
}
干杯!