15 Commits

Author SHA1 Message Date
3aba1312fb Diagramme Avalam (simplifié) 2026-02-06 11:33:16 +01:00
c44e7495a4 Actualiser Diagrammes/Diagramme_Bot.mmd 2026-02-05 23:25:57 +01:00
86a86f598c Upload files to "/" 2026-02-05 23:25:27 +01:00
2766fa7632 Actualiser README.md 2026-02-05 23:21:51 +01:00
c5d01dd2bb Actualiser fr/iut_fbleau/Bot/DivineBot.java 2026-02-05 23:13:31 +01:00
f40f3daa1d Bot Divin (plus performant) 2026-02-05 23:12:03 +01:00
ebfc9d7d78 Actualiser fr/iut_fbleau/Bot/DivineBot.java 2026-02-05 22:35:06 +01:00
88df11dc03 Bot Divin corrigé (plus performant) 2026-02-05 22:23:07 +01:00
af70986edd Merge pull request 'makefile_compilation_erreur' (#28) from makefile_compilation_erreur into master
Reviewed-on: #28
2026-02-05 20:53:18 +01:00
felix-vi
d94b95fa36 erreur de création dans l'arène 2026-02-05 20:50:23 +01:00
felix-vi
2db0212b31 bug sur la référence des tour dans avalamboard 2026-02-05 20:13:37 +01:00
felix-vi
43e44bf7d2 ajout d'une fenetre arene et bug divinebot 2026-02-05 19:46:02 +01:00
023aa9d419 Mise à jour des diagrammes + SVG 2026-02-05 19:45:44 +01:00
2cf929e024 Merge pull request 'modification du makefile pour séparer la compilation du jeu et des test et automatiser l'installation des dépendance' (#27) from makefile_compilation_erreur into master
Reviewed-on: #27
2026-02-05 16:39:42 +01:00
felix-vi
ee374a9221 modification du makefile pour séparer la compilation du jeu et des test et automatiser l'installation des dépendance 2026-02-05 16:37:57 +01:00
14 changed files with 357 additions and 179 deletions

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 128 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 22 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 40 KiB

View File

@@ -3,6 +3,28 @@ title: Avalam - Diagramme de classes (complet)
--- ---
classDiagram classDiagram
class ArenaGame{
+ArenaGame(IBoard board, AbstractGamePlayer bot1, AbstractGamePlayer bot2)
-createPlayerMap(AbstractGamePlayer bot1, AbstractGamePlayer bot2): EnumMap<Player, AbstractGamePlayer>
}
class ArenaWindow{
-resultsTable: JTable
-tableModel: DefaultTableModel
-results: List<string>
+ArenaWindows()
-createConfigPanel(): JPanel
-createResultsTable()
-showConfigDialog()
-runArena(String bot1Type, String bot2Type, int depth, int nbParties)
-createBot(String botType, Player player, int depth): AbstractGamePlayer
-getWinnerName(Result result, String bot1Type, String bot2Type): String
}
ArenaWindow *-- AvalamBoard
ArenaWindow *-- ArenaGame
class AvalamBoard{ class AvalamBoard{
+SIZE: int +SIZE: int
-MAX_HEIGHT: int -MAX_HEIGHT: int
@@ -43,8 +65,6 @@ classDiagram
+toString(): String +toString(): String
} }
class AvalamWindow{ class AvalamWindow{
-board : AvalamBoard -board : AvalamBoard
-scoreView : ScoreView -scoreView : ScoreView
@@ -70,14 +90,19 @@ classDiagram
AvalamWindow *-- BoardView AvalamWindow *-- BoardView
AvalamWindow *-- ScoreView AvalamWindow *-- ScoreView
AvalamWindow *-- TurnView AvalamWindow *-- TurnView
AvalamWindow *-- EndGameDialog
AvalamWindow --> GameMode AvalamWindow --> GameMode
class BackgroundLayer{
-img: Image
+BackgroundLayer(String resourcePath)
#paintComponent(Graphics g): void
}
class BoardLoader{ class BoardLoader{
+loadFromFile(String resourcePath): Tower[][] +loadFromFile(String resourcePath): Tower[][]
} }
class BoardView{ class BoardView{
-board: AvalamBoard -board: AvalamBoard
-backgroundLayer: BackgroundLayer -backgroundLayer: BackgroundLayer
@@ -105,14 +130,6 @@ classDiagram
BoardView *-- InteractionController BoardView *-- InteractionController
BoardView --> AvalamBoard BoardView --> AvalamBoard
class BackgroundLayer{
-img: Image
+BackgroundLayer(String resourcePath)
#paintComponent(Graphics g): void
}
class Color{ class Color{
-YELLOW(int r, int g, int b) -YELLOW(int r, int g, int b)
-RED(int r, int g, int b) -RED(int r, int g, int b)
@@ -122,11 +139,17 @@ classDiagram
+toPlayer(): fr.iut_fbleau.GameAPI.Player +toPlayer(): fr.iut_fbleau.GameAPI.Player
} }
class EndGameDialog{
+EndGameDialog(JFrame parent, Result result, int scoreJaune, int scoreRouge, GameMode mode, int depth, Runnable onReplay, Runnable onMenu, Runnable onQuit)
-modeToString(GameMode mode, int depth): String
}
class GameMode{ class GameMode{
PVP PVP
PVBOT PVBOT
PVALPHA PVALPHA
PVGOD PVGOD
ARENA
} }
class HighlightLayer{ class HighlightLayer{
@@ -165,6 +188,7 @@ classDiagram
Main ..> AvalamWindow Main ..> AvalamWindow
Main ..> GameMode Main ..> GameMode
Main ..> ArenaWindow
class PieceButton{ class PieceButton{
-color: java.awt.Color -color: java.awt.Color

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 100 KiB

View File

@@ -16,8 +16,18 @@ classDiagram
-listMoves(IBoard board): List<AbstractPly> -listMoves(IBoard board): List<AbstractPly>
} }
class DivineBot{ class DivineBot {
-me : Player
-maxDepth : int
-rng : Random
+DivineBot(Player p, int maxDepth)
+giveYourMove(IBoard board) : AbstractPly
-alphaBeta(IBoard board, int depth, int alpha, int beta) : int
-evaluate(IBoard board) : int
-isIsolated(AvalamBoard b, int r, int c) : boolean
-isVulnerable(AvalamBoard b, int r, int c, Color enemyColor) : boolean
-listMoves(IBoard board) : List~AbstractPly~
} }
class IdiotBot{ class IdiotBot{

View File

@@ -1,5 +1,7 @@
# === Environnements === # === Environnements ===
TEST_ENV = "bin:/usr/share/java/junit.jar:/usr/share/java/hamcrest-core.jar" JUNIT_JAR = /usr/share/java/junit.jar
HAMCREST_JAR = /usr/share/java/hamcrest-core.jar
TEST_ENV = "bin:$(JUNIT_JAR):$(HAMCREST_JAR)"
# === Répertoires === # === Répertoires ===
SRC_DIR = fr SRC_DIR = fr
@@ -9,8 +11,11 @@ BIN_DIR = bin
RES_SRC = fr/iut_fbleau/Res RES_SRC = fr/iut_fbleau/Res
RES_BIN = bin/fr/iut_fbleau/Res RES_BIN = bin/fr/iut_fbleau/Res
# === Recherche automatique des fichiers .java dans tous les sous-dossiers === # === Recherche automatique des fichiers .java ===
SOURCES := $(shell find $(SRC_DIR) -name "*.java") # SOURCES : uniquement le code de l'application (sans les fichiers de tests)
SOURCES := $(shell find $(SRC_DIR) -name "*.java" -not -path "$(SRC_DIR)/iut_fbleau/Tests/*")
# TEST_SOURCES : uniquement les fichiers de tests
TEST_SOURCES := $(shell find $(SRC_DIR)/iut_fbleau/Tests -name "*.java" 2>/dev/null)
# === Classe principale === # === Classe principale ===
MAIN_CLASS = fr.iut_fbleau.Avalam.Main MAIN_CLASS = fr.iut_fbleau.Avalam.Main
@@ -20,7 +25,10 @@ TEST_CLASS = fr.iut_fbleau.Tests.AvalamBoardTest
# === Commandes Java === # === Commandes Java ===
JC = javac JC = javac
JCFLAGS = -d $(BIN_DIR) -cp $(TEST_ENV) # Compilation normale (application uniquement)
JCFLAGS = -d $(BIN_DIR)
# Compilation des tests (application + JUnit)
JCFLAGS_TESTS = -d $(BIN_DIR) -cp $(TEST_ENV)
JAVA = java JAVA = java
JAVAFLAGS = -cp $(BIN_DIR) JAVAFLAGS = -cp $(BIN_DIR)
@@ -38,6 +46,35 @@ compile:
@mkdir -p $(BIN_DIR) @mkdir -p $(BIN_DIR)
@$(JC) $(JCFLAGS) $(SOURCES) @$(JC) $(JCFLAGS) $(SOURCES)
compile_tests: compile
@echo "===> Compilation des tests..."
@mkdir -p $(BIN_DIR)
ifneq ($(TEST_SOURCES),)
@$(JC) $(JCFLAGS_TESTS) $(TEST_SOURCES)
else
@echo "Aucun fichier de test trouvé dans $(SRC_DIR)/iut_fbleau/Tests"
endif
# === Vérification / installation des dépendances de tests ===
check_test_deps:
@echo "===> Vérification des dépendances de tests (JUnit / Hamcrest)..."
@if [ ! -f "$(JUNIT_JAR)" ] || [ ! -f "$(HAMCREST_JAR)" ]; then \
echo " JUnit ou Hamcrest manquant, tentative d'installation (sudo requis)..."; \
if command -v sudo >/dev/null 2>&1; then \
sudo apt-get update && sudo apt-get install -y junit4 libhamcrest-java; \
else \
apt-get update && apt-get install -y junit4 libhamcrest-java; \
fi; \
if [ ! -f "$(JUNIT_JAR)" ] || [ ! -f "$(HAMCREST_JAR)" ]; then \
echo "✖ Impossible de trouver/installer $(JUNIT_JAR) ou $(HAMCREST_JAR). Vérifiez manuellement vos paquets JUnit/Hamcrest."; \
exit 1; \
else \
echo "✔ Dépendances de tests installées."; \
fi; \
else \
echo "✔ JUnit et Hamcrest trouvés."; \
fi
# === Copie des ressources (.txt) dans bin === # === Copie des ressources (.txt) dans bin ===
resources: resources:
@echo "===> Copie des ressources..." @echo "===> Copie des ressources..."
@@ -51,7 +88,7 @@ run:
@$(JAVA) $(JAVAFLAGS) $(MAIN_CLASS) @$(JAVA) $(JAVAFLAGS) $(MAIN_CLASS)
# === Tests === # === Tests ===
test: test: check_test_deps compile_tests
@echo "===> Lancement des tests..." @echo "===> Lancement des tests..."
@$(JAVA) $(JAVAFLAGS_TESTS) org.junit.runner.JUnitCore $(TEST_CLASS) @$(JAVA) $(JAVAFLAGS_TESTS) org.junit.runner.JUnitCore $(TEST_CLASS)
@echo "... Fin des tests." @echo "... Fin des tests."

View File

@@ -12,37 +12,55 @@ Dans un second temps, nous développerons des bots les plus efficaces possible,
Le jeu de notre groupe est **Avalam**. Le jeu de notre groupe est **Avalam**.
## Compilation et exécution ## Compilation, exécution et tests
### Compilation ### Compilation (sans tests)
```bash ```bash
make build make build
``` ```
ou simplement :
### Tests
```bash ```bash
make test make
``` ```
Cette commande :
- compile uniquement le code de l'application (sans les fichiers du dossier `fr/iut_fbleau/Tests`) ;
- copie les ressources dans `bin/`.
### Exécution ### Exécution du jeu
```bash ```bash
make run make run
``` ```
Lance la fenêtre de jeu Avalam après compilation.
### Lancer les tests
```bash
make test
```
Cette commande :
- vérifie d'abord la présence de **JUnit** et **Hamcrest** dans `/usr/share/java` ;
- si nécessaire, tente de les installer automatiquement via `apt-get` (sudo requis sur Debian/Ubuntu) ;
- compile ensuite les fichiers de tests (`fr/iut_fbleau/Tests`) ;
- lance enfin la suite de tests JUnit (`AvalamBoardTest`).
Si l'installation automatique échoue (autre OS, pas de droits sudo, pas d'accès réseau, etc.), un message l'indiquera et il faudra installer JUnit/Hamcrest manuellement.
### Nettoyage ### Nettoyage
```bash ```bash
make clean make clean
``` ```
Supprime le répertoire `bin/` (classes compilées et ressources copiées).
### Recompiler et exécuter ### Recompiler puis exécuter
```bash ```bash
make re make re
``` ```
Équivaut à `make clean` puis `make build` puis `make run`.
### Générer la Javadoc ### Générer la Javadoc
```bash ```bash
make javadoc make javadoc
``` ```
Génère la documentation dans le dossier `doc/`.
## Architecture du projet ## Architecture du projet
@@ -105,3 +123,8 @@ Tans qu'un joueur peut effectuer un mouvement il a l'obligation de jouer, la par
On compte alors combien de pions de chaque couleur occupent le sommet des tours restantes, le vainqueur étant évidemment celui qui en totalise le plus. On compte alors combien de pions de chaque couleur occupent le sommet des tours restantes, le vainqueur étant évidemment celui qui en totalise le plus.
Attention! Qu'une tour comporte 1,2,... ou 5 pions, elle vaut toujours UN point. Attention! Qu'une tour comporte 1,2,... ou 5 pions, elle vaut toujours UN point.
## Arène de bots
Dans ce mode de jeu, deux bots s'affrontent pour certains nombre de partie choisit, afin de voir quel bot gagne le plus.
### Lancer parties
Lancer parties permet de faire fonctionner l'arène. On choisit le premier bot pour le joueur1, et le deuxième pour le joueur deux. On choisit la profondeurs de recherches pour les bots intelligent, puis enfin le nombre de partie que doivent effectués les bots. Enfin il suffit pour voir l'entièreté des résultats, si y a beaucoup de parties, sinon, on peut voir les parties se déroulé pendant la session.

BIN
Rapport_Avalam.pdf Normal file

Binary file not shown.

View File

@@ -192,24 +192,55 @@ public class ArenaWindow extends JFrame {
* @param nbParties nombre de parties à jouer * @param nbParties nombre de parties à jouer
*/ */
private void runArena(String bot1Type, String bot2Type, int depth, int nbParties) { private void runArena(String bot1Type, String bot2Type, int depth, int nbParties) {
// Créer les bots
AbstractGamePlayer bot1 = createBot(bot1Type, Player.PLAYER1, depth);
AbstractGamePlayer bot2 = createBot(bot2Type, Player.PLAYER2, depth);
if (bot1 == null || bot2 == null) {
JOptionPane.showMessageDialog(this, "Erreur lors de la création des bots.");
return;
}
// Vider le tableau // Vider le tableau
tableModel.setRowCount(0); tableModel.setRowCount(0);
results.clear(); results.clear();
// Charger le plateau initial // Créer un dialogue de progression
Tower[][] initialGrid = BoardLoader.loadFromFile("fr/iut_fbleau/Res/Plateau.txt"); JDialog progressDialog = new JDialog(this, "Parties en cours...", true);
JLabel progressLabel = new JLabel("Préparation des parties...", JLabel.CENTER);
progressLabel.setBorder(BorderFactory.createEmptyBorder(20, 40, 20, 40));
progressDialog.add(progressLabel);
progressDialog.setSize(300, 100);
progressDialog.setLocationRelativeTo(this);
progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
// Exécuter les parties dans un thread séparé pour ne pas bloquer l'interface
Thread arenaThread = new Thread(() -> {
SwingUtilities.invokeLater(() -> progressDialog.setVisible(true));
// Statistiques pour déboguer
int bot1Wins = 0;
int bot2Wins = 0;
int draws = 0;
int errors = 0;
// Lancer les parties
for (int i = 1; i <= nbParties; i++) { for (int i = 1; i <= nbParties; i++) {
final int partieNum = i;
SwingUtilities.invokeLater(() -> {
progressLabel.setText("Partie " + partieNum + " / " + nbParties + " en cours...");
});
// Recréer les bots à chaque partie pour garantir l'indépendance complète
// (notamment pour réinitialiser les générateurs aléatoires)
AbstractGamePlayer bot1 = createBot(bot1Type, Player.PLAYER1, depth);
AbstractGamePlayer bot2 = createBot(bot2Type, Player.PLAYER2, depth);
if (bot1 == null || bot2 == null) {
errors++;
SwingUtilities.invokeLater(() -> {
tableModel.addRow(new Object[]{
"Partie " + partieNum,
bot1Type,
bot2Type,
"Erreur: Impossible de créer les bots"
});
});
continue;
}
// Recharger le plateau à chaque partie pour garantir l'indépendance complète
Tower[][] initialGrid = BoardLoader.loadFromFile("fr/iut_fbleau/Res/Plateau.txt");
AvalamBoard board = new AvalamBoard(initialGrid, Player.PLAYER1); AvalamBoard board = new AvalamBoard(initialGrid, Player.PLAYER1);
ArenaGame game = new ArenaGame(board, bot1, bot2); ArenaGame game = new ArenaGame(board, bot1, bot2);
@@ -217,28 +248,64 @@ public class ArenaWindow extends JFrame {
Result result = game.run(); Result result = game.run();
String winner = getWinnerName(result, bot1Type, bot2Type); String winner = getWinnerName(result, bot1Type, bot2Type);
// Ajouter au tableau // Mettre à jour les statistiques
if (result == Result.WIN) {
bot1Wins++;
} else if (result == Result.LOSS) {
bot2Wins++;
} else if (result == Result.DRAW) {
draws++;
}
// Ajouter au tableau dans le thread EDT
SwingUtilities.invokeLater(() -> {
tableModel.addRow(new Object[]{ tableModel.addRow(new Object[]{
"Partie " + i, "Partie " + partieNum,
bot1Type, bot1Type,
bot2Type, bot2Type,
winner winner
}); });
});
} catch (Exception e) { } catch (Exception e) {
errors++;
SwingUtilities.invokeLater(() -> {
tableModel.addRow(new Object[]{ tableModel.addRow(new Object[]{
"Partie " + i, "Partie " + partieNum,
bot1Type, bot1Type,
bot2Type, bot2Type,
"Erreur: " + e.getMessage() "Erreur: " + e.getMessage()
}); });
});
} }
} }
// Afficher un message de fin avec possibilité de quitter directement // Afficher les statistiques finales
final int finalBot1Wins = bot1Wins;
final int finalBot2Wins = bot2Wins;
final int finalDraws = draws;
final int finalErrors = errors;
// Fermer le dialogue et afficher le message de fin avec statistiques
SwingUtilities.invokeLater(() -> {
progressDialog.dispose();
String statsMessage = String.format(
"Toutes les parties sont terminées !\n\n" +
"Statistiques :\n" +
"- %s (Bot 1) : %d victoires\n" +
"- %s (Bot 2) : %d victoires\n" +
"- Matchs nuls : %d\n" +
"- Erreurs : %d",
bot1Type, finalBot1Wins,
bot2Type, finalBot2Wins,
finalDraws,
finalErrors
);
Object[] options = {"OK", "Quitter le jeu"}; Object[] options = {"OK", "Quitter le jeu"};
int choice = JOptionPane.showOptionDialog( int choice = JOptionPane.showOptionDialog(
this, this,
"Toutes les parties sont terminées !", statsMessage,
"Arène terminée", "Arène terminée",
JOptionPane.DEFAULT_OPTION, JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE, JOptionPane.INFORMATION_MESSAGE,
@@ -250,6 +317,10 @@ public class ArenaWindow extends JFrame {
if (choice == 1) { if (choice == 1) {
System.exit(0); System.exit(0);
} }
});
});
arenaThread.start();
} }
/** /**

View File

@@ -51,9 +51,16 @@ public class AvalamBoard extends AbstractBoard {
super(startingPlayer, new ArrayDeque<>()); super(startingPlayer, new ArrayDeque<>());
this.grid = new Tower[SIZE][SIZE]; this.grid = new Tower[SIZE][SIZE];
// Copie profonde : créer de nouvelles tours pour éviter que toutes les parties partagent les mêmes objets
for (int r = 0; r < SIZE; r++) for (int r = 0; r < SIZE; r++)
for (int c = 0; c < SIZE; c++) for (int c = 0; c < SIZE; c++) {
this.grid[r][c] = initialGrid[r][c]; Tower t = initialGrid[r][c];
if (t == null) {
this.grid[r][c] = null;
} else {
this.grid[r][c] = new Tower(t.getHeight(), t.getColor());
}
}
} }
/** /**

View File

@@ -233,7 +233,6 @@ public class AvalamWindow extends JFrame {
} else if (mode == GameMode.PVALPHA) { } else if (mode == GameMode.PVALPHA) {
botMove = alphaBot.giveYourMove(board.safeCopy()); botMove = alphaBot.giveYourMove(board.safeCopy());
} else { } else {
// A FAIRE PLUS TARD (PVGOD)
botMove = divineBot.giveYourMove(board.safeCopy()); botMove = divineBot.giveYourMove(board.safeCopy());
} }

View File

@@ -2,74 +2,53 @@ package fr.iut_fbleau.Bot;
import fr.iut_fbleau.Avalam.*; import fr.iut_fbleau.Avalam.*;
import fr.iut_fbleau.GameAPI.*; import fr.iut_fbleau.GameAPI.*;
import java.util.*; import java.util.*;
/** /**
* Bot "Divin" (alpha-beta + évaluateur pondéré). * Bot expert pour le jeu Avalam utilisant l'algorithme Alpha-Beta.
* * Idée : * * Ce bot évalue le plateau en fonction du contrôle des tours,
* - Utilise l'algorithme Alpha-Beta pour anticiper les coups. * de leur isolation (points sécurisés) et de leur vulnérabilité.
* - Évalue les plateaux non terminaux en accordant plus d'importance aux tours hautes.
*/ */
public class DivineBot extends AbstractGamePlayer { public class DivineBot extends AbstractGamePlayer {
// Attributs /** Joueur contrôlé par le bot. */
/** Joueur contrôlé par ce bot (PLAYER1 ou PLAYER2). */
private final Player me; private final Player me;
/** Profondeur maximale de recherche avant évaluation. */ /** Profondeur de recherche dans l'arbre des coups. */
private final int maxDepth; private final int maxDepth;
/** Générateur aléatoire pour choisir parmi les meilleurs coups équivalents. */ /** Générateur aléatoire pour choisir entre des coups d'égale valeur. */
private final Random rng = new Random(); private final Random rng = new Random();
// Constructeur
/** /**
* Construit le bot Divine. * Constructeur du DivineBot.
* * @param p le joueur (P1 ou P2).
* @param p joueur contrôlé par ce bot * @param maxDepth la profondeur d'anticipation.
* @param maxDepth profondeur de l'arbre de recherche
*/ */
public DivineBot(Player p, int maxDepth) { public DivineBot(Player p, int maxDepth) {
super(p); super(p);
this.me = p; this.me = p;
this.maxDepth = Math.max(1, maxDepth); this.maxDepth = maxDepth;
} }
// Méthodes
/** /**
* Méthode principale de décision du bot. * Calcule et retourne le meilleur coup possible.
* Explore le premier niveau de l'arbre et lance les appels Alpha-Beta. * @param board l'état actuel du jeu.
* * @param board état actuel du jeu * @return le coup sélectionné.
* @return le meilleur coup calculé (AbstractPly)
*/ */
@Override @Override
public AbstractPly giveYourMove(IBoard board) { public AbstractPly giveYourMove(IBoard board) {
if (board == null || board.isGameOver()) return null; if (board == null || board.isGameOver()) return null;
List<AbstractPly> moves = listMoves(board); List<AbstractPly> moves = listMoves(board);
if (moves.isEmpty()) return null; int bestValue = Integer.MIN_VALUE;
boolean isMax = board.getCurrentPlayer() == me;
int bestValue = isMax ? Integer.MIN_VALUE : Integer.MAX_VALUE;
List<AbstractPly> bestMoves = new ArrayList<>(); List<AbstractPly> bestMoves = new ArrayList<>();
int alpha = Integer.MIN_VALUE;
int beta = Integer.MAX_VALUE;
for (AbstractPly m : moves) { for (AbstractPly m : moves) {
IBoard next = board.safeCopy(); IBoard next = board.safeCopy();
next.doPly(m); next.doPly(m);
int value = alphaBeta(next, maxDepth - 1, Integer.MIN_VALUE, Integer.MAX_VALUE);
// Appel récursif pour évaluer la suite du coup
int value = alphaBeta(next, maxDepth - 1, alpha, beta);
if (isMax) {
if (value > bestValue) { if (value > bestValue) {
bestValue = value; bestValue = value;
bestMoves.clear(); bestMoves.clear();
@@ -77,73 +56,48 @@ public class DivineBot extends AbstractGamePlayer {
} else if (value == bestValue) { } else if (value == bestValue) {
bestMoves.add(m); bestMoves.add(m);
} }
alpha = Math.max(alpha, bestValue);
} else {
if (value < bestValue) {
bestValue = value;
bestMoves.clear();
bestMoves.add(m);
} else if (value == bestValue) {
bestMoves.add(m);
} }
beta = Math.min(beta, bestValue);
}
}
// Retourne un coup au hasard parmi les meilleurs ex-aequo
return bestMoves.get(rng.nextInt(bestMoves.size())); return bestMoves.get(rng.nextInt(bestMoves.size()));
} }
/** /**
* Algorithme récursif de recherche avec élagage Alpha-Beta. * Algorithme Alpha-Beta pour optimiser la recherche du meilleur score.
*/ */
private int alphaBeta(IBoard board, int depth, int alpha, int beta) { private int alphaBeta(IBoard board, int depth, int alpha, int beta) {
if (board.isGameOver()) {
Result r = board.getResult();
if (r == Result.DRAW) return 0;
return (r == Result.WIN == (me == Player.PLAYER1)) ? 1000000 : -1000000;
}
// Cas de base : fin de partie ou limite de profondeur atteinte
if (board.isGameOver()) return terminalValue(board);
if (depth == 0) return evaluate(board); if (depth == 0) return evaluate(board);
boolean isMax = board.getCurrentPlayer() == me; boolean isMax = (board.getCurrentPlayer() == me);
int best = isMax ? Integer.MIN_VALUE : Integer.MAX_VALUE;
for (AbstractPly m : listMoves(board)) { for (AbstractPly m : listMoves(board)) {
IBoard next = board.safeCopy(); IBoard next = board.safeCopy();
next.doPly(m); next.doPly(m);
int val = alphaBeta(next, depth - 1, alpha, beta); int val = alphaBeta(next, depth - 1, alpha, beta);
if (isMax) { if (isMax) {
alpha = Math.max(alpha, val); best = Math.max(best, val);
if (alpha >= beta) break; // Coupure Beta alpha = Math.max(alpha, best);
} else { } else {
beta = Math.min(beta, val); best = Math.min(best, val);
if (alpha >= beta) break; // Coupure Alpha beta = Math.min(beta, best);
} }
if (alpha >= beta) break;
} }
return best;
return isMax ? alpha : beta;
} }
/** /**
* Calcule la valeur de l'état final (Victoire / Défaite). * Analyse la situation actuelle et attribue un score au plateau.
*/ * @param board le plateau à analyser.
private int terminalValue(IBoard board) { * @return le score (positif si avantageux pour le bot).
Result r = board.getResult();
if (r == null) return 0;
if (r == Result.DRAW) return 0;
boolean botIsP1 = (me == Player.PLAYER1);
// Si le bot gagne, valeur positive élevée, sinon valeur négative
return ((r == Result.WIN) == botIsP1) ? 100000 : -100000;
}
/**
* Heuristique évoluée pour Avalam :
* Calcule un score basé sur le contrôle des tours et leur hauteur.
* Les tours de hauteur 5 sont prioritaires car elles sont bloquées.
*/ */
private int evaluate(IBoard board) { private int evaluate(IBoard board) {
if (!(board instanceof AvalamBoard)) return 0; if (!(board instanceof AvalamBoard)) return 0;
AvalamBoard b = (AvalamBoard) board; AvalamBoard b = (AvalamBoard) board;
@@ -151,35 +105,76 @@ public class DivineBot extends AbstractGamePlayer {
Color oppColor = (myColor == Color.YELLOW) ? Color.RED : Color.YELLOW; Color oppColor = (myColor == Color.YELLOW) ? Color.RED : Color.YELLOW;
int score = 0; int score = 0;
for (int r = 0; r < AvalamBoard.SIZE; r++) { for (int r = 0; r < AvalamBoard.SIZE; r++) {
for (int c = 0; c < AvalamBoard.SIZE; c++) { for (int c = 0; c < AvalamBoard.SIZE; c++) {
Tower t = b.getTowerAt(r, c); Tower t = b.getTowerAt(r, c);
if (t == null) continue; if (t == null || t.getHeight() == 0) continue;
int h = t.getHeight(); int h = t.getHeight();
int weight = 0;
// Pondération selon la hauteur (heuristique "Divine") // Points sécurisés (isolation ou hauteur max)
int value = if (h == 5 || isIsolated(b, r, c)) {
(h == 5) ? 1000 : weight = 1000;
(h == 4) ? 300 : } else {
(h == 3) ? 120 : // Gestion de la vulnérabilité face à l'ennemi
(h == 2) ? 40 : 10; if (isVulnerable(b, r, c, oppColor)) {
weight = -200;
} else {
switch (h) {
case 4: weight = 400; break;
case 3: weight = 150; break;
case 2: weight = 60; break;
default: weight = 10; break;
}
}
}
if (t.getColor() == myColor) score += value; if (t.getColor() == myColor) score += weight;
else score -= value; else score -= weight;
} }
} }
return score; return score;
} }
/** /**
* Génère la liste de tous les coups possibles sur le plateau donné. * Vérifie si une tour n'a plus de voisins (point bloqué).
*/
private boolean isIsolated(AvalamBoard b, int r, int c) {
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
if (dr == 0 && dc == 0) continue;
Tower n = b.getTowerAt(r + dr, c + dc);
if (n != null && n.getHeight() > 0) return false;
}
}
return true;
}
/**
* Vérifie si l'adversaire peut capturer la tour au prochain coup.
*/
private boolean isVulnerable(AvalamBoard b, int r, int c, Color enemyColor) {
int myHeight = b.getTowerAt(r, c).getHeight();
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
if (dr == 0 && dc == 0) continue;
Tower n = b.getTowerAt(r + dr, c + dc);
if (n != null && n.getColor() == enemyColor && (n.getHeight() + myHeight <= 5)) {
return true;
}
}
}
return false;
}
/**
* Liste tous les coups possibles sur le plateau actuel.
*/ */
private List<AbstractPly> listMoves(IBoard board) { private List<AbstractPly> listMoves(IBoard board) {
List<AbstractPly> moves = new ArrayList<>(); List<AbstractPly> moves = new ArrayList<>();
board.iterator().forEachRemaining(moves::add); Iterator<AbstractPly> it = board.iterator();
while (it.hasNext()) moves.add(it.next());
return moves; return moves;
} }
} }