检查所有8个方向的Reversi中的有效移动

时间:2015-11-03 01:26:30

标签: c arrays 2d reversi

我有一个功能来检查我的reversi游戏中的有效动作。我看着空置的空间,检查任何8个方向的相邻空间是否相反。 (如果我是黑色的,我会搜索白色)现在,如果我找到一块相邻的部分,我应该继续向那个方向看,看看我自己的作品是否在最后,然后我回归真实,否则如果它是空的空间或离开边界,我返回假。

当我打印出错误的动作时,我的功能似乎无法正常工作。

bool checkLegalInDirection(char boardgame[26][26], int size, int row, int col, char color) {

int currentRow, currentCol;
for (int deltaRow = -1; deltaRow < 2; deltaRow++) {
    for (int deltaCol = -1; deltaCol < 2; deltaCol++) {
        if (deltaRow == 0 && deltaCol == 0) {
            break; 
        } else {
        row = row + deltaRow;
        col = col + deltaCol;
        if (positionInBounds(size, row, col)) {
            while (boardgame[row][col] == OppositeColor(color)) {
                currentRow = row + deltaRow;
                currentCol = col + deltaCol;

                if (positionInBounds(size, currentRow, currentCol)) {
                    if (boardgame[currentRow][currentCol] == color) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        }
    }
}
}
}

deltaRow和deltaCol是每个方向的增量,并添加一次以在指定位置继续搜索。 PositioninBounds是我必须确保我的搜索在板边界内的函数。我的deltarow和deltacol不能同时为0,所以我不得不跳过那一步(我可能做错了)。相反颜色是一种功能,它让我的颜色与我自己的颜色相反。

1 个答案:

答案 0 :(得分:0)

我认为您的代码有多处错误。

当您继续下一次迭代时(如chux所述),您的代码错误地破坏了for循环。

更改...

if (deltaRow == 0 && deltaCol == 0) {
    break;
} else {
    ...
}

要么是chux的建议......

if (deltaRow == 0 && deltaCol == 0) {
    continue;
} else {
    ...
}

或更简单的解决方案......

if (deltaRow != 0 || deltaCol != 0) {
   ...
}

在deltaRow / deltaCol循环中,您的代码错误地修改了代码在以后的循环迭代中需要的原始行/列值。

你可以改变......

row = row + deltaRow;
col = col + deltaRow;

为...

currentRow = row + deltaRow;
currentCol = col + deltaRow;

在while循环中,您的代码错误地返回false。在完成所有for循环之前,不能返回false。

在进入while循环之前,您需要检查相邻空间是否为边界且颜色相反...

if (positionInBounds(size, currentRow, currentCol) && boardgame[currentRow][currentCol] == OppositeColor(color)) {

如果是这样,那么跳过所有相邻的相反颜色......

while (positionInBounds(size, currentROw, currentColor) && boadgame[currentRow][currentCol] == OppositeColor(color)) {
{
    currentRow = currentRow + deltaRow;
    currentCol = currentCol + deltaCol;
}

跳过相反的颜色后,您需要检查相同的颜色。如果是,则返回true。

    if (positionInBOunds(size, currentRow, currentCol) && boardgame[currentRow][currentCol] == color) {
        return true;
    }

您的代码只应在检查所有路线后返回false ...

for (int deltaRow = -1; deltaRow < 2; deltaRow++) {
    for (int deltaCol = -1; deltaCol < 2; deltaCol++) {
        ....
    }
}
return false;
相关问题