Heuristic function for connect 4

  artificial-intelligence, c++

I am trying to create a 6×7 Connect 4 game in C++ using the minimax and alphabeta algorithms. The heuristic function I have created counts the number of consecutive symbols of the players and the score is increased if the symbols are ‘O’, which is the AI’s symbol, and decreased if the symbols are ‘X’, which is the player’s symbol. 2 consecutive symbols modify the score by 4, while 3 modify the score by 8 (Also I am aware that 3 consecutive symbols will be first counted as 2 consecutive symbols but I don’t think this affects the function negatively). If 4 consecutive symbols are found then the function returns INT_MIN or INT_MAX depending on who achieved the victory. If the board fills up and there is a tie the function returns -1. This is my implementation of the function:

int Score4::evaluate() {
//full check
bool full = true;
for(int j = 0;j < 7;j++) {
    if(board[0][j] == ' ') {
        full = false;
        break;
    }
}

if(full) {
    return -1;
}

int score = 0;

//rows check
for(int i = 0;i < 6;i++) {
    int same = 1;
    for(int j = 1;j < 7;j++) {
        if(board[i][j] != ' ' && board[i][j - 1] == board[i][j]) {
            same++;
        }
        else {
            same = 1;
        }

        if(same > 1) {
            if(board[i][j - 1] == 'O') {
                if(same == 4) { return INT_MAX; }
                score += pow(2, same);
            }
            else {
                if(same == 4) { return INT_MIN; }
                score -= pow(2, same);
            }
        }
    }
}

//columns check
for(int j = 0;j < 7;j++) {
    int same = 1;
    for(int i = 1;i < 6;i++) {
        if(board[i][j] != ' ' && board[i][j] == board[i - 1][j]) {
            same++;
        }
        else {
            same = 1;
        }

        if(same > 1) {
            if(board[i - 1][j] == 'O') {
                if(same == 4) { return INT_MAX; }
                score += pow(2, same);
            }
            else {
                if(same == 4) { return INT_MIN; }
                score -= pow(2, same);
            }
        }
    }
}

return score;

}

I still haven’t added the diagonal checks because I am having an issue with the rows and columns checks. For some reason my function ends the game even with 3 consecutive symbols and I can’t figure out why. Here is an example of a situation like that:

enter image description here

The number beneath the board is the number of states the algorithm checks in each move. Any help would be appreciated.

Source: Windows Questions C++

LEAVE A COMMENT