掷骰子游戏问题



代码的目的是让两名玩家掷一对骰子。第一个总共掷了20个球的玩家赢得了比赛。我很难弄清楚如何正确地跟踪滚动的总和;它只给我当前回合的总和,然后当每个玩家滚动10次时,游戏结束。

如何正确计算每个玩家游戏的总和,然后在其中一个玩家的总和等于20时停止循环?

int a, b, c, d;
int playerone=0, playertwo=0;
Random gen = new Random();
a=gen.nextInt(6)+1;
b=gen.nextInt(6)+1;
c=gen.nextInt(6)+1;
d=gen.nextInt(6)+1;
while(playerone!=20 || playertwo!=20) {
playerone=a+b;
playertwo=c+d;
System.out.println("Player 1 rolled " + a + " and a " + b );
System.out.println("Player 1 now has " + playerone);
System.out.println("Player 2 rolled " + c + " and a " + d );
System.out.println("Player 2 now has " + playertwo);
a=gen.nextInt(6)+1;
b=gen.nextInt(6)+1;
c=gen.nextInt(6)+1;
d=gen.nextInt(6)+1;
playertwo+=a+b;
playerone+=c+d;
if(playerone==20) 
System.out.println("player one wins ");
else if (playertwo==20)
System.out.println("player two wins ");             
}       
}

请看一看,并将其与您的代码片段进行比较:

int playerone = 0, playertwo = 0;
while(playerone < 20 && playertwo < 20) {
a=gen.nextInt(6)+1;
b=gen.nextInt(6)+1;
c=gen.nextInt(6)+1;
d=gen.nextInt(6)+1;
System.out.println("Player 1 rolled " + a + " and a " + b );
System.out.println("Player 1 now has " + playerone);
System.out.println("Player 2 rolled " + c + " and a " + d );
System.out.println("Player 2 now has " + playertwo);
playerone+=a+b;
playertwo+=c+d;
}
if(playerone >= playertwo) { // here you have to choose how
System.out.println("player one wins with " + playerone + " over " + playertwo);
} else {
System.out.println("player two wins with " + playertwo + " over " + playerone);
}

在上面的代码中,我纠正了一些事情,其中条件和a/b分别用于播放器1和播放器2。在where循环结束后,您必须根据结果值或您的逻辑来决定如何确定赢家,因为两者都掷骰子。

在循环内设置playerone=a+bplayertwo=c+d,这意味着总数仅基于最新的滚动。相反,在循环之前执行此操作。

不过,实际上,最好合并循环内的所有骰子滚动和输出,这样你就可以在更新后输出新的总数,而不是之前。

ab是用于玩家一还是用于玩家二方面,您也不一致。您应该将所有用于更新玩家和掷骰子的代码移动到方法中。

最新更新