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

60 lines
1.7 KiB
Java
Raw Normal View History

2026-02-05 16:27:10 +01:00
package fr.iut_fbleau.HexGame;
import fr.iut_fbleau.GameAPI.*;
import java.util.Random;
public class MonteCarloBot extends AbstractGamePlayer {
private static final int SIMULATION_COUNT = 1000;
public MonteCarloBot(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 = monteCarloSimulation(hb);
if (score > bestScore) {
bestScore = score;
bestMove = move;
}
hb.undoPly();
}
}
}
return bestMove;
}
private float monteCarloSimulation(HexBoard board) {
RandomBot simBot = new RandomBot(Player.PLAYER1, new Random().nextLong());
2026-02-06 11:00:03 +01:00
HexBoard simBoard = (HexBoard) board.safeCopy();
2026-02-05 16:27:10 +01:00
int wins = 0;
int simulations = 0;
for (int i = 0; i < SIMULATION_COUNT; i++) {
while (!simBoard.isGameOver()) {
AbstractPly move = simBot.giveYourMove(simBoard);
simBoard.doPly(move);
}
if (simBoard.getResult() == Result.WIN) {
wins++;
}
simulations++;
2026-02-06 11:00:03 +01:00
simBoard = (HexBoard) board.safeCopy(); // Reset the board for the next simulation
2026-02-05 16:27:10 +01:00
}
return (float) wins / simulations;
}
}