Reroll在yahtzee比赛中骰子

时间:2017-08-15 12:58:48

标签: java arrays

我正在尝试创建一个简单的yahtzee游戏,其中一个数组填充5个随机数,玩家可以选择再次滚动特定的骰子。但是,我无法弄清楚如何编写应该用新的随机数替换数组中的特定数字并返回它的方法。有任何建议如何处理这个?

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class YatzyGame {

    private final Integer NBROFDICE = 5;
    private final Integer DICEMAXVALUE = 6;
    Random rnd = new Random();
    Scanner keyboard = new Scanner(System.in);

    public void startGame() {
        int[] dice = new int[NBROFDICE];
        rollDice(dice);
        printDice(dice);

        System.out.println("Do you want to reroll any dices? " + "Y/N");
        String answer = keyboard.nextLine();
        if (answer.equalsIgnoreCase("y")) {
            rerollDice(dice);

        } else if (answer.equalsIgnoreCase("n")) {
            calculateSum(dice);

        } else {
            System.out.println("Wrong command!");
        }

    }

    public int[] rollDice(int[] dice) {
        for (int i = 0; i < dice.length; i++) {
            dice[i] = rnd.nextInt(DICEMAXVALUE) + 1;
        }
        return dice;
    }

    public int[] rerollDice(int[] dice) {
        System.out.println("What dices do you want to reroll? Dices index are 0-4");
        int diceToReroll = keyboard.nextInt();

        // Replace the numbers at the index the user specifies with new random numbers and return the array.

    }

    public void printDice(int[] dices) {

        System.out.println("Your dices show: " + Arrays.toString(dices));
    }

    public void calculateSum(int[] dices) {
        int sum = 0;
        for (int i : dices) {
            sum += i;
        }
        if (sum == 30) {
            System.out.println("YAHTZEE! Your total score is 50! Congratulations!");
        } else
            System.out.println("Your total score is: " + sum);
    }

    public static void main(String[] args) {
        new YatzyGame().startGame();
    }

}

1 个答案:

答案 0 :(得分:0)

public int[] rollDice(int[] dice) {

             System.out.println("What dice do you want to reroll? Dices index are 0-4");
             int diceToRoll = keyboard.nextInt();
             dice[diceToRoll] = rnd.nextInt(DICEMAXVALUE) + 1;
    }

像这样你可以创造一个功能:

public int[] reroll(int amountOfRerolls, int[] dices){

    for(int i =0;i<dicesToReroll;i++){
       this.rollDice(dices);
    }


return dices; 
}

这使得程序更加模态化,因为您可以在任何需要的地方重用rollDice()方法。此外,您可以通过交换允许在需要时重新注册的索引来扩展它。

编辑:风格