Search code examples
c++if-statementrecursionartificial-intelligence

If statements causing program to crash with recursion


I am trying to make my program scan the board for move for an AI and the if statement works if I have the first statement by itself but if I add the else if statement and crashes.

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);
    }
}

I am assuming that it is due to the recursion, what would be a better way to do this?

I realize it is because board[x-1][y] causes x to become negative and won't work. Is there a way to stop this from happening?

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;

}

call for check for moves

void Foxes::foxesProcess(BoardSet& board)
{
    cout << "The foxes move: ";
    findFoxes(board);
    checkForPossibleMoves(board);

}

From Main

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);
    }
}

Solution

  • You are not doing any bounds checking in your function so assuming that board is just a standard array or a class that does not bound check then when x<=1 you will go out of bounds and right into undefined behavior.

    Without seeing more code the most obvious check and fix would be this:

    else if( x > 1 && (board[x-1][y] == 'S' && board[x-2][y] == '.') )
    

    You also have a bounds check issue on the if statement, if x >= 4 then you will be going outside the bounds as well:

    if( x <= 4 && (board[x+1][y] == 'S' && board[x+2][y] == '.') ) 
    

    having some sort of variable that defines max would be helpful in case you decided to change it.