From 4389ceae8a280f380e0a964caa30d427444e9f07 Mon Sep 17 00:00:00 2001 From: Arthur <78031901+Arthur7770@users.noreply.github.com> Date: Mon, 22 Feb 2021 10:57:07 +0100 Subject: [PATCH] NagamaxPlayer changed --- src/othello/Main.java | 3 ++- src/othello/players/NegamaxPlayer.java | 26 ++++++++++++++++++++------ src/othello/players/Player.java | 4 ++++ 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/othello/Main.java b/src/othello/Main.java index be78382..79f97f1 100644 --- a/src/othello/Main.java +++ b/src/othello/Main.java @@ -1,5 +1,6 @@ package othello; +import othello.players.NegamaxPlayer; import othello.players.Player; import othello.players.RandomPlayer; @@ -8,7 +9,7 @@ public class Main { public static void main(String[] args) { Player p1 = new RandomPlayer(1); - Player p2 = new RandomPlayer(-1); + Player p2 = new NegamaxPlayer(-1); Player[][] board = initialize(p1, p2); State game = new State(board, p1, p2); System.out.println("joueur 1: " + p1); diff --git a/src/othello/players/NegamaxPlayer.java b/src/othello/players/NegamaxPlayer.java index af98f46..d80a8e9 100644 --- a/src/othello/players/NegamaxPlayer.java +++ b/src/othello/players/NegamaxPlayer.java @@ -12,19 +12,33 @@ public class NegamaxPlayer extends Player { @Override public Pair play(State game) { - return game.getMove(this).get(negamax(game, 10, this.id)); + Integer bestValue = null; + Pair bestMove = null; + for(Pair move : game.getMove(game.getCurrentPlayer())) { + int v = negamax(game.play(move),10,-id); + if(bestValue == null || v > bestValue) { + bestValue = v; + bestMove = move; + } + } + return bestMove; } private int negamax(State game, int depth, int id) { if(depth == 0 || game.isOver()) { - return id; + if(game.getWinner() == game.getCurrentPlayer()) + return game.getWinner().getId(); + else if(game.getWinner() != null) + return game.getWinner().getId(); + return 0; } - int value = Integer.MIN_VALUE; + Integer value = null; Player player = game.getPlayerById(id); for(Pair move : game.getMove(player)) { - game = game.play(move); - game.setCurrentPlayer(player); - value = Math.max(value, -negamax(game, depth - 1, -id)); + int v = negamax(game.play(move),10,-id); + if(value == null || v>value){ + value = v; + } } return value; } diff --git a/src/othello/players/Player.java b/src/othello/players/Player.java index 41f68eb..f006216 100644 --- a/src/othello/players/Player.java +++ b/src/othello/players/Player.java @@ -8,6 +8,10 @@ public abstract class Player { protected final int id; + public int getId() { + return this.id; + } + public Player(int id) { this.id = id; }