为什么我的 for 循环不能找到正确的错误?

Why won't my for loop pick up the correct error?

我有一个网格和一个名为 Move(int s) 的成员函数,它应该将移动器图标移动到它当前面向的任何方向,'s' 个空间。如果在 mover 想要移动到的位置前面的任何位置有一个块字符 ('#'),则该函数应该失败并将光标留在正确的位置。似乎 bool 语句总是等于 true 但我似乎无法在我的代码中找到它的位置。

在我的示例输出中,移动函数从未失败,移动者似乎总是穿过墙壁或替换墙壁。

我不会 post 所有 4 个方向,但我会 post 北和西:

bool Grid::Move(int s) {
bool canMove = true;  //initialize the bool variable
if (direction == NORTH) {
    if ((mRow - s) >= 0) {
        for (int i = mRow; i >= (mRow - s); i--) {
            if (matrix[i][mCol] == '#') {
                canMove = false;
            } else if (matrix[i][mCol] != '#') {
                canMove = true;
            }
        }
        if (canMove == true) {
            matrix[mRow][mCol] = '.';
            mRow = (mRow - s);
            matrix[mRow][mCol] = '^';
            return true;
        }else{
            matrix[mRow][mCol] = '^';
        }
    } else
        return false;
} else if (direction == WEST) {
    if ((mCol - s) >= 0) {
        for (int i = mCol; i >= (mCol - s); i--){
            if (matrix[mRow][i] == '#'){
                canMove = false;
            } else if (matrix[mRow][i] != '#')
                canMove = true;
        }
        if (canMove == true) {
            matrix[mRow][mCol] = '.';
            mCol = (mCol - s);
            matrix[mRow][mCol] = '<';
            return true;
        }else
            matrix[mRow][mCol] = '<';
    }else
        return false;
} 

您在循环的每次迭代中设置 canMove。无论它最后一次获得什么价值,它都会有什么价值。

因为 objective 是为了查看移动是否在整个持续时间内有效,所以您不需要将 canMove 设置为 true 因为一旦它变为假应该保持这种状态。 (当发生这种情况时,您可以 break 跳出循环。)