I'm trying to write a minimax algorithm for connect 4 in Java, but am getting an error while trying to iterate through a list of possible moves.
It says that
Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.util.ArrayList$Itr.next(Unknown Source)
I've looked around online, and have found some things (about updating an object within the iterator), but am not quite sure what to do.
Here is my code.
public class AI {
public Move minimax(Board board, int depth, int alpha, int beta, String player, Move move) {
if(depth == 0 || board.getScore() >= 512) {
return move;
}
else if(player.equals("computer")) {
Move maxMove = new Move(0,0);
maxMove.moveScore = -1000000;
Iterator<Move> it = board.possibleMoves.iterator();
while(it.hasNext()) {
Move m = it.next();
board.putPiece(player, m.yMove);
m.moveScore = board.getScore();
if (board.getScore() < minimax(board, depth-1, alpha, beta, "human", m).moveScore) {
maxMove = m;
}
else {
maxMove = minimax(board, depth-1, alpha, beta, "human", m);
}
board.removePiece(m);
alpha = Math.max(alpha, maxMove.moveScore);
if (alpha >= beta) {
break;
}
}
return maxMove;
}
else {
Move minMove = new Move(100, 100);
minMove.moveScore = 1000000;
for(Move m : board.possibleMoves) {
board.putPiece(player, m.yMove);
m.moveScore = board.getScore();
if (m.moveScore < minimax(board, depth-1, alpha, beta, "computer", m).moveScore) {
minMove = m;
}
else {
minMove = minimax(board, depth-1, alpha, beta, "computer", m);
}
board.removePiece(m);
beta = Math.min(beta, minMove.moveScore);
if(alpha >= beta) {
break;
}
}
return minMove;
}
}
}
Any and all help is appreciated.
Thanks,