对于学校作业我们正在努力在java中实现yahtzee游戏,但我在为直道制作算法时遇到一些问题(小直和大直,这意味着4/5连续数字为小直和5 / 5为大)。
我制作了一个我认为应该有效的算法,但实际上它总是输出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.
我的算法背后的理论是;每当你在骰子价值的(已排序)数组中找到一个不具有连续数字作为下一个数字的数字时,在非连续数中添加一个数字,最后在将分数分配给该计数器时检查此计数器玩家。
任何帮助我们都非常感谢!
答案 0 :(得分: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给我们所有五个元素作为连续。
如果我理解游戏正确(考虑到我只是略过了它),您需要在代码中进行以下修改:
对您的代码进行以下更改:
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