我試圖創建一個簡單的yahtzee遊戲,其中一個數組中充滿了5個隨機數字,玩家可以選擇再次擲骰子。但我不知道如何編寫應該用新的隨機數字替換數組中特定數字的方法並將其返回。任何建議如何處理這個?yahtzee遊戲中的雷鳥骰子
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();
}
}
循環遍歷字符串中的字符。對於每個字符都是數字,找到它的整數值(0-4),並重新擲骰子。 – Thomas
你可以讓你的'rollDice'方法更靈活一些,只讓它擲出一個骰子。然後你可以從'rollAllDices(int [] dices)'調用它來完成整個滾動,並從'rerollDice(int index,int [] dices)'調用它來只滾動一個骰子。 –