首页 > 解决方案 > Java Connect4 游戏。我想检查列是否已满

问题描述

我正在尝试检查玩家想要投入硬币的栏是否已满。当我把柱子装满并且我把另一个硬币放在那里时,它超出了界限。我如何检查它是否已满并且没有超出债券。

for(int o = rows- 1;o>= 0; o--) {
    if (boards[o][nextColumn]=="- " ) {
        boards[o][nextColumn] = nextSymbol + " " ;
        break;
    }
    if (fullColumn > rows ) {
        System.out.println("The column is full!");
        break;
    }
}

标签: java

解决方案


您收到 IndexOutOfBoundsException 是因为当您初始化循环时,值为g0。

for(int g=0;g<rows;g++)

然后,当您在循环的同一迭代中时,您正在检查下一个单元格是否包含与当前单元格相同的符号,但您是通过递减来完成的g

boards[g][s].equals(boards[g-1][s+1])

如果 的值g从零开始,则 的值为g-1-1,这会产生错误,因为根据定义,您的数组从索引 0 开始。

当你检查你的对角线时,你不能只用一种方法——对角线是有方向的。不考虑这种方向性是导致您的测试失败的原因。

拿一张纸画你的板子

Diagonal 1

3 - - - o
2 - - o -
1 - o - -
0 o - - -
  0 1 2 3

Diagonal 2

3 o - - -
2 - o - -
1 - - o -
0 - - - o
  0 1 2 3

在对角线 1 的情况下,您需要同时递增g和递增s,但由于我们知道g == s对于第一条对角线上的每个点,我们只需要一个变量。

for(int g = 0; g < 4;g++)
{
    if(boards[g][g].equals(boards[g + 1][g + 1]))
    {
        // still matching. I have no idea how your code is tracking
        // matches, so you'll have to adapt this on your own
    }
    else
    {
        // no match, no need to continue the loop
        // break; or exit however you want
    }
}

对于对角线 2,就像我们知道g == s对角线 1 的所有点一样,我们知道g == 3 - s,所以你可以

for(int s = 0; s < 4;s++)
{
    if(boards[(3 - s)][s].equals(boards[2 - s][s + 1]))
    {
        // still matching. I have no idea how your code is tracking
        // matches, so you'll have to adapt this on your own
    }
    else
    {
        // no match, no need to continue the loop
        // break; or exit however you want
    }
}

每当您无法将头绕在某件事上时,请画一幅画并在纸上工作,直到您了解自己在处理什么。


推荐阅读