Yahtzee满屋

时间:2014-07-24 22:00:13

标签: java arrays

我正在尝试创建一个简单的yahtzee程序,并坚持检查是否有满屋。

显示的计数数组是骰子值的数组,例如count [1] = 3表示存在1对的3对。 count [3] = 2表示存在2对3值的死亡。

/**
 * If the category is not yet taken, scoreFullHouse
 * makes sure there are two of one kind and three
 * of another.  If there are, it puts a score
 * of 25 into the HOUSE category, marks the category as taken,
 * and adds 25 to the total score.
 *
 * @param count is the count array of all dice values
 */
private void scoreFullHouse(int[] count)
{
    if (!taken[Category.HOUSE.ordinal()]) //Checks if the house category is taken.
    {
        for (int i = 1; i < 7; ++i)
        {
          if (count[i]=2 || count[i]=3)
          {
            if (count[i+1]=3)
            {
                scores[Category.HOUSE.ordinal()] = HOUSE_VALUE; //Makes the HOUSE_VALUE(25) the score
                taken[Category.HOUSE.ordinal()] = true; //Sets category to taken
                total = total + HOUSE_VALUE;  //Adds the total
                break;
            }

        }
    }
}

我知道这不对,但它有我想要做的基本支柱。我不知道的是如何检查数组以查看是否同时存在2对和3对。满堂红是另一个骰子中的3个

会这样做吗?

if (count[i]=2 || count[i]=3)
{
  if (count[i+1]=3 && count[i]!=3 || count[i+1]=2 && count[i]!=2)
  {

2 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点。

int six = 6;
int values[] = new int[six+1]; // waste a byte so it indexes right
for(int i = 0; i < dice.length; i++) {
    values[dice[i]]++;  // keep counts
}

// now do...
boolean hasAThree = false;
boolean hasATwo = false;

for(int i = 1; i <= six; i++) {
    if(values[i] == 3) {
        hasAThree = true;
    }
    if(values[i] == 2) {
        hasATwo = true;
    }
}

if(hasAThree && hasATwo) {
    // full house
}

答案 1 :(得分:0)

需要注意的一些事项:

首先,&#34; count [i] = n&#34;分配&#34; n&#34;的值改变&#34;计数&#34;在索引&#34;我&#34;。另一方面,&#34; count [i] == n&#34;评估&#34; count [i]&#34;的布尔值。和&#34; n&#34;是相同的价值。因此,您的if语句应如下所示:

if(count[i] == 3){
    // do something
}

第二点并不是在语法上解决任何错误,但在Java(和许多其他语言)中,标准约定你从零开始,部分原因是数组和类似的数据结构将它们包含的第一个值计算为作为索引&#34; 0&#34;,第二个作为索引&#34; 1&#34;,依此类推。这有一个额外的好处,就是能够使条件小于你要循环的数组的长度。就目前而言,你的循环永远不会检查数组中的第一个值,从索引&#34; 1&#34;开始,当你试图访问索引&#34; 6&#34;时会抛出一个错误。 (假设计数的长度为6,每个骰子面都有一个指数)。这是一个非常标准的for循环的例子:

for(int i = 0; i < count.length; i++){
    // do something
}

(另请注意,i ++比++ i更常用,即使它们在这种情况下是相同的)

实际答案:

至于识别满屋的简单方法,请记住,总共只有五个骰子,所以满屋只有三三两种。这个事实,以及你不能添加最多五个骰子只有两个或三个一组的事实意味着你可以检查以确保没有骰子值发生多次而不是两个或三个:

for(int i = 0; i < 6; i++){
    if(count[i] != 2 && count[i] != 3){
        // any "count" which enters this body is not a full house.
        return;
    }
}
// any "count" that continues through the method beyond the loop will be a full house.

据我所知,实际得分部分看起来不错,但我不能100%肯定只看到这一部分。