我正在尝试让我的程序为AI扫描棋盘以寻找移动方式。如果我只使用第一个if语句,它能够正常工作,但当我添加else if语句时,程序就会崩溃。
void BoardSet::foxNextToSheep(int x, int y, int& moves){ if(board[x+1][y] == 'S' && board[x+2][y] == '.') { x = x + 2; moves++; foxNextToSheep(x, y, moves); } else if(board[x-1][y] == 'S' && board[x-2][y] == '.') { x = x - 2; moves++; foxNextToSheep(x, y, moves); }}
我猜测这是由于递归引起的,有没有更好的方法来实现这个功能?
我意识到问题出在board[x-1][y]
会导致x变为负数而无法正常工作。有没有办法阻止这种情况发生?
class BoardSet {public://Functions used for foxes bool findFox(int x, int y); void foxNextToSheep(int x, int y, int& moves);private: char board[7][8]; int sheep; int foxes;};class Foxes {public:void foxesProcess(BoardSet& board);void findFoxes(BoardSet& board);void checkForPossibleMoves(BoardSet& board);void print();private: int foxes[2][2];};void Foxes::checkForPossibleMoves(BoardSet& board){ int moves1 = 0; int foxOneX = foxes[0][0]; int foxOneY = foxes[0][1]; board.foxNextToSheep(foxOneX, foxOneY, moves1); cout << moves1 << endl;}
调用检查移动的函数
void Foxes::foxesProcess(BoardSet& board){ cout << "The foxes move: "; findFoxes(board); checkForPossibleMoves(board);}
从主函数中
void processGame(istream& in){ int repeat = 1; BoardSet board; Sheep sheep; Foxes foxes; initalizeBoard(in, board); while(repeat) { board.checkForWin(repeat); if(repeat == 0) break; sheep.sheepProcess(board); board.print(); board.checkForWin(repeat); if(repeat == 0) break; foxes.foxesProcess(board); }}
回答:
你的函数中没有进行边界检查,因此假设board
只是一个标准数组或一个不进行边界检查的类,那么当x<=1
时,你将超出边界并进入未定义行为。
在没有看到更多代码的情况下,最明显的检查和修复方法是这样的:
else if( x > 1 && (board[x-1][y] == 'S' && board[x-2][y] == '.') )
你也在if
语句中存在边界检查问题,如果x >= 4
,你也会超出边界:
if( x <= 4 && (board[x+1][y] == 'S' && board[x+2][y] == '.') )
如果决定更改边界,拥有一个定义最大值的变量会很有帮助。