掷骰子游戏问题

时间:2020-03-02 18:59:34

标签: java sum counter dice

该代码的目的是让2个玩家掷出一对骰子。首位总共掷出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 ");             
    }       
}

2 个答案:

答案 0 :(得分:2)

您在循环内的{em> 中设置了playerone=a+bplayertwo=c+d,这意味着总数仅基于最新的掷骰数。而是在循环之前执行该操作。

虽然,实际上,最好将所有掷骰子和循环中的骰子合并在一起,这样您才可以在更新后的新总计而不是之前输出新总计。

您还不确定ab是用于玩家一还是两名。您应该移动所有代码以更新玩家并将骰子滚动到方法中。

答案 1 :(得分:2)

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

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

在上面的代码中,我更正了几件事,其中条件1和a / b适用于播放器1,而c / d适用于播放器2。where循环结束后,您必须根据结果值或按您的逻辑如何确定赢家,因为两者都掷骰子。