Files
BUT3ProjetJeuGroupe/javaAPI/fr/iut_fbleau/HexGame/MiniMaxBot.java

90 lines
3.1 KiB
Java
Raw Normal View History

2026-02-05 16:27:10 +01:00
package fr.iut_fbleau.HexGame;
import fr.iut_fbleau.GameAPI.*;
public class MiniMaxBot extends AbstractGamePlayer {
private int MAXDEPTH = 5;
public MiniMaxBot(Player me) {
super(me); // Correct constructor usage
}
@Override
public AbstractPly giveYourMove(IBoard board) {
HexBoard hb = (HexBoard) board;
float bestScore = -Float.MAX_VALUE;
HexPly bestMove = null;
for (int i = 0; i < hb.getSize(); i++) {
for (int j = 0; j < hb.getSize(); j++) {
HexPly move = new HexPly(hb.getCurrentPlayer(), i, j);
if (hb.isLegal(move)) {
hb.doPly(move);
float score = minimax(hb, MAXDEPTH, -Float.MAX_VALUE, Float.MAX_VALUE, true);
if (score > bestScore) {
bestScore = score;
bestMove = move;
}
hb.undoPly();
}
}
}
return bestMove;
}
private float minimax(HexBoard board, int depth, float alpha, float beta, boolean isMaximizing) {
if (depth == 0 || board.isGameOver()) {
return evaluateBoard(board);
}
if (isMaximizing) {
float bestScore = -Float.MAX_VALUE;
for (int i = 0; i < board.getSize(); i++) {
for (int j = 0; j < board.getSize(); j++) {
HexPly move = new HexPly(board.getCurrentPlayer(), i, j);
if (board.isLegal(move)) {
board.doPly(move);
float score = minimax(board, depth - 1, alpha, beta, false);
bestScore = Math.max(bestScore, score);
alpha = Math.max(alpha, bestScore);
if (beta <= alpha) break; // Pruning
board.undoPly();
}
}
}
return bestScore;
} else {
float bestScore = Float.MAX_VALUE;
for (int i = 0; i < board.getSize(); i++) {
for (int j = 0; j < board.getSize(); j++) {
HexPly move = new HexPly(board.getCurrentPlayer(), i, j);
if (board.isLegal(move)) {
board.doPly(move);
float score = minimax(board, depth - 1, alpha, beta, true);
bestScore = Math.min(bestScore, score);
beta = Math.min(beta, bestScore);
if (beta <= alpha) break; // Pruning
board.undoPly();
}
}
}
return bestScore;
}
}
private float evaluateBoard(HexBoard board) {
int size = board.getSize();
int center = size / 2;
int score = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
2026-02-06 11:00:03 +01:00
if (board.getCellPlayer(i, j) == Player.PLAYER1) {
2026-02-05 16:27:10 +01:00
score += Math.abs(i - center) + Math.abs(j - center); // Distance from center
}
}
}
return score;
}
}