2017-08-15 117 views
0

我試圖創建一個簡單的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

循環遍歷字符串中的字符。對於每個字符都是數字,找到它的整數值(0-4),並重新擲骰子。 – Thomas

+0

你可以讓你的'rollDice'方法更靈活一些,只讓它擲出一個骰子。然後你可以從'rollAllDices(int [] dices)'調用它來完成整個滾動,並從'rerollDice(int index,int [] dices)'調用它來只滾動一個骰子。 –

回答

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

這使得PROGRAMM多一點的模式,因爲你可以在任何需要它重用你rollDice()方法。您也可以通過交付允許在需要的情況下重新編輯的索引來擴展它。

編輯:風格

+0

感謝您的反饋。問題,它會幫助我爲這個項目創建一個單獨的Die類嗎? – Andpej

+0

你當然可以做到!學習OOP的概念可能會很好。我不會說這是必要的,因爲死亡現在只是一個「int」值。例如,如果您想在骰子中存儲更多信息而不是滾動值(例如'boolean alreadyRolled;'等),則可以這樣做。 edit:拼寫 –