2015-11-25 27 views
1

對於一個學校任務,我們正在執行java中的yahtzee遊戲,但是我在製作直線算法時存在一些問題(小直徑和大直線,這意味着4/5連續數字代表小直和5/5大)。yahtzee中的直線算法

我已經作出一個算法,我認爲應該是工作,但在現實中卻總是拿出0,所以我要失去了一些東西:

private void straights(int category) { 
    Arrays.sort(dices); 
    int nonConsecCount = 0; 
    for(int currDice = 0; currDice < N_DICE - 2; currDice++) { 
     if(dices[currDice] != dices[currDice + 1] + 1) { 
      nonConsecCount++; 
     } 
    } 
    if(nonConsecCount == 0 && category == LARGE_STRAIGHT) { 
     score[currPlayer - 1][category - 1] = 40; 
     display.updateScorecard(category, currPlayer, 40); 
    } else if(nonConsecCount <= 1 && category == SMALL_STRAIGHT) { 
     score[currPlayer - 1][category - 1] = 30; 
     display.updateScorecard(category, currPlayer, 30); 
    } else { 
     score[currPlayer - 1][category - 1] = 0; 
     display.updateScorecard(category, currPlayer, 0); 
    } 
} 

N_DICE等於5

我的理論這個算法背後是;每當你在沒有連續數字的(排序)排列數組中找到一個數字作爲下一個數字時,給非連續數加1,最後在向玩家發出分數時檢查這個計數器。

任何幫助,我們將不勝感激!

+1

'sort'是排序按*升序排列。 – Marco13

+0

是的,那麼爲什麼陣列的下一個元素不應該被認爲是連續的呢? – Perdite

+0

問題爲什麼你的for循環中有N_DICE - 2作爲條件?我敢打賭,應該是N_DICE - 1 – Raf

回答

1

根據遊戲的,我很快在wikipedia

Small Straight - Is 4 sequential dices (30 score) that is 
1,2,3,4 or 2,3,4,5 or 3,4,5,6 

Large Straight - Is 5 sequential dices (40 score) that is 
1,2,3,4,5 or 2,3,4,5,6 

如果小直通過文章脫脂的規則,那麼你應該有一個nonConsecCount等於1,因爲5 - 1 4,這給了我們連續四次的骰子。如果大直,那麼你應該有一個nonConseCount等於0,因爲5 - 0給我們所有五個元素連續。

如果我理解正確的遊戲(考慮到這樣的事實,我只是脫脂),你需要在你的代碼如下修改:

  • 您的循環條件應該是N_DICE - 1,這將產生的 for循環執行4倍,比數組大小小一,因此,您 保證不會讓ArrayOutOfBoundException
  • 你需要改變你的if條件,使得增加的條件左邊部分的價值 然後用前面一個條件的右邊部分的值來檢查。因此,交換可以使用N_DICE - 1而不是N_DICE - 2. N_DICE - 2跳過一個數組元素,只檢查3個連續元素(不是遊戲規則說的)。

令代碼以下更改:

int nonConsecCount = 0; 
     for(int currDice = 0; currDice < N_DICE - 1; currDice++) { 
      if(dices[currDice] + 1 != dices[currDice + 1]) { 
       System.out.println("failed consecutive match!"); 
       nonConsecCount++; 
      } else { 
       System.out.println("passed consecutive match for "+ dices[currDice]); 
      } 
     } 
     System.out.println(nonConsecCount); 

我提供的上述代碼下面的骰子,並得到nonConsecCount作爲表演註釋行:

int[] dices = new int[]{3,4,5,1,2}; 
//output 0 - this is largest straight 

int[] dices = new int[]{3,4,5,6,2}; 
//output 0 - this is largest straight too 

int[] dices = new int[]{3,4,5,2,2}; 
//output 1 - this is smallest straight 

int[] dices = new int[]{3,4,2,2,2}; 
//output 2 - this is none of the two 
+0

感謝您的詳細答案,我很愚蠢的把骰子[currDice]!= dices [currDice + 1] + 1而不是dices [currDice] + 1!= dices [currDice + 1]。好的趕上!再次感謝。 – Perdite

+0

不客氣,我也學到了遊戲!看起來很有趣。 – Raf

+0

它很接近,但有兩種情況,其中'nonConsecCount'爲1但不是小直:'[1,2,3,5,6]'和'[1,2,4,5,6]'。 – Jasha