掷骰子游戏问题

问题描述 投票:0回答:2

该代码的目的是让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 ");


    }

}

}

java sum counter dice
2个回答
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循环结束后,您必须根据结果值或由您决定逻辑,因为两个都掷骰子,如何确定获胜者。


1
投票

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

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

[ab是否适用于一号或二号玩家,您也不一致。您应该移动所有代码以更新玩家并将骰子滚动到方法中。

© www.soinside.com 2019 - 2024. All rights reserved.