I am trying to create connect 4 game using JavaFX. When I try to implement the minimax algorithm, it gives giving stack overflow error.
When it comes the AI's turn it is invoking the movePiece(-1) . There are 6 Cols, and 5 Rows in the game. It is working fine after I send a random number between 0 - 5 fine, but the issue is on the minimax function.
Here is the code I am using on AI Player's class.
package lk.ijse.dep.service;
public class AiPlayer extends Player {
private final Board board;
public AiPlayer(Board board) {
this.board = board;
}
@Override
public void movePiece(int col) {
col = minimax(5, true);
board.updateMove(col, Piece.GREEN); //Placing the piece on the selected col.
board.getBoardUI().update(col, false);
Winner winner = board.findWinner();
if (winner.getWinningPiece() == Piece.GREEN) {
board.getBoardUI().notifyWinner(winner);
}
if (!board.existLegalMove()) {
board.getBoardUI().notifyWinner(new Winner(Piece.EMPTY));
}
}
private int minimax(int depth, boolean maximizingPlayer) {
if(depth == 0 || !board.existLegalMove()) return 0;
if (maximizingPlayer) {
int maxEval = (int) Double.NEGATIVE_INFINITY;
for (int i = 0; i < this.board.NUM_OF_COLS; i++) {
System.out.println(i);
int heuristicVal = minimax(depth + 1, false); //<< Getting StackOverFlow Error
maxEval = Math.max(heuristicVal, maxEval);
}
return maxEval;
} else {
int minEval = (int) Double.POSITIVE_INFINITY;
for (int i = 0; i < this.board.NUM_OF_COLS; i++) {
System.out.println(i);
int heuristicVal = minimax(depth + 1, true); //<< Getting StackOverFlow Error
minEval = Math.min(heuristicVal, minEval);
}
return minEval;
}
}
}
When the AI's turn came, it is automatically invoking the movePiece(-1); It is a illegal move, so need to modify before sending it to updateMove(int col, boolean isHuman);
Board's existLegalMove function;
public boolean existLegalMove() {
for (int i = 0; i < NUM_OF_COLS; i++) {
for (int j = 0; j < NUM_OF_ROWS; j++) {
if (pieces[i][j].equals(Piece.EMPTY)) {
return true;
}
}
}
return false;
}
