Connect4 MiniMax algorithm
This is a minimax algorithm designed to play the game of Connect Four. The algorithm searches to a depth of 9 and uses alpha-beta pruning for better performance. This ensures a very high probability of winning, as the algorithm is able to look ahead several moves and choose the best possible move. The minimax algorithm is a classic game-playing algorithm that can be used to play a variety of games, including chess, checkers, and tic-tac-toe. 1 It works by recursively exploring the game tree and choosing the move that leads to the best possible outcome for the player. Alpha-beta pruning is a technique that can be used to improve the performance of the minimax algorithm by eliminating branches of the game tree that are not worth exploring.
Code fragments
if(maxPlayer){
int value = -9999999;
int column = validSteps.get(new Random().nextInt(validSteps.size()));
for(int i: validSteps){
Board boardCopy = new Board(board);
boardCopy.step(this.playerIndex, i);
int newScore = miniMax(boardCopy, depth-1, alpha, beta, false)[1];
if(newScore > value){
value = newScore;
column = i;
}
alpha = max(alpha, value);
if(alpha >= beta){
break;
}
}
return new int[]{column, value};
}
The mentioned alpha/beta pruning can be seen in the marked section.
private int scoreOfFour(int[] four, int playerIndex){
int score = 0;
if(outOfFour(four, playerIndex) == 4) score += 100;
else if(outOfFour(four, playerIndex) == 3 && outOfFour(four, 0) == 1) score += 5;
else if(outOfFour(four, playerIndex) == 2 && outOfFour(four, 0) == 2) score += 2;
if(outOfFour(four, 1) == 3 && outOfFour(four, 0) == 1) score -= 100;
else if(outOfFour(four, 1) == 2 && outOfFour(four, 0) == 2) score -= 2;
return score;
}