我有一些麻烦让这个代码看起来整洁,因为有许多IF&需要评估的OR声明。
想法:你抛出五个骰子并挑出例如三个相同类型的1,1,1再次投掷骰子另外两个并去收集点。
棘手的是将dice1,dice2,dice3,dice4,dice5与规则集进行比较,以确定玩家得到的分数。如果dicex = 1& dicex = 1& dicex = 1"给球员1000分?
int player1points = 0;
int player2points = 0;
Scanner in = new Scanner(System.in);
Random n1 = new Random();
int dice1 = n1.nextInt(6) + 1;
int dice2 = n1.nextInt(6) + 1;
System.out.println("Dice 1 shows " +dice1);
System.out.println("Dice 2 shows " +dice2);
System.out.println("Dice 3 shows " +dice3);
System.out.println("Dice 4 shows " +dice4);
System.out.println("Dice 5 shows " +dice5);
if /* 1+1+1+1+1 = 2000 */ (dice1==1&&dice2==1&&dice3==1&&dice4==1&&dice5==1){
System.out.println("You got 2000 points! Throw again?");
int points2000 = 2000;
player1points = player1points + points2000;
System.out.print("You have ");
System.out.print(player1points);
System.out.print(" points. Do you want to throw again?");
System.out.println("Yes/No?");
s = in.nextLine();
}
else if /* 1+1+1 = 1000 */ (dice1==1&&dice2==1&&dice3==1||dice2==1&&dice3==1&&dice4==1||dice3==1&&dice4==1&&dice5==1|| dice4==1&&dice5==1&&dice1==1||dice5==1&&dice1==1&&dice2==1||dice1==1&&dice2==1&&dice4==1||d ice2==1&&dice3==1&&dice5==1||dice3==1&&dice4==1&&dice1==1||dice4==1&&dice5==1&&dice1==1||dice1==1&&dice3==1&&dice5==1){
System.out.println("You got 1000 points!");
int points1000 = 1000;
player1points = player1points + points1000;
System.out.print("You have ");
System.out.print(player1points);
System.out.print(" points. Do you want to throw again?");
System.out.println("Yes/No?");
s = in.nextLine();
}
答案 0 :(得分:2)
将roll的结果放入arrayList,然后只计算该数组列表中显示的相同数字的次数?如果有3个1,则给予1000分,否则如果有5分给出2000分。
因此,对于您的代码,您将在大多数情况下拥有相同的开头。添加方法来填充数组列表,并迭代/计算骰子滚动的结果并返回最常见的和显示的次数。
int player1points = 0;
int player2points = 0;
int count = 0;
int mostCommon = 0;
int maxCount = 0;
ArrayList<Integer> diceRolls = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
Random n1 = new Random();
//rollDice method (parameter would be number of dice to roll)
//checkResults method (count number of times each number 1-6 shows up)
if(maxCount == 3){
player1points += 1000;
//re-roll 2 dice if necessary
else if(maxCount == 5){
player2points += 2000;
//re-roll dice if wanted
这只是你可以做到的一种方式。将大块代码分解为更易于阅读的函数也是一种很好的做法,它使调试变得更容易!如果您需要帮助,请随时询问!