NagamaxPlayer changed

This commit is contained in:
Arthur 2021-02-22 10:57:07 +01:00
parent a81709ef84
commit 4389ceae8a
3 changed files with 26 additions and 7 deletions

View File

@ -1,5 +1,6 @@
package othello; package othello;
import othello.players.NegamaxPlayer;
import othello.players.Player; import othello.players.Player;
import othello.players.RandomPlayer; import othello.players.RandomPlayer;
@ -8,7 +9,7 @@ public class Main {
public static void main(String[] args) { public static void main(String[] args) {
Player p1 = new RandomPlayer(1); Player p1 = new RandomPlayer(1);
Player p2 = new RandomPlayer(-1); Player p2 = new NegamaxPlayer(-1);
Player[][] board = initialize(p1, p2); Player[][] board = initialize(p1, p2);
State game = new State(board, p1, p2); State game = new State(board, p1, p2);
System.out.println("joueur 1: " + p1); System.out.println("joueur 1: " + p1);

View File

@ -12,19 +12,33 @@ public class NegamaxPlayer extends Player {
@Override @Override
public Pair<Point, Point> play(State game) { public Pair<Point, Point> play(State game) {
return game.getMove(this).get(negamax(game, 10, this.id)); Integer bestValue = null;
Pair<Point, Point> bestMove = null;
for(Pair<Point, Point> 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) { private int negamax(State game, int depth, int id) {
if(depth == 0 || game.isOver()) { 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); Player player = game.getPlayerById(id);
for(Pair<Point, Point> move : game.getMove(player)) { for(Pair<Point, Point> move : game.getMove(player)) {
game = game.play(move); int v = negamax(game.play(move),10,-id);
game.setCurrentPlayer(player); if(value == null || v>value){
value = Math.max(value, -negamax(game, depth - 1, -id)); value = v;
}
} }
return value; return value;
} }

View File

@ -8,6 +8,10 @@ public abstract class Player {
protected final int id; protected final int id;
public int getId() {
return this.id;
}
public Player(int id) { public Player(int id) {
this.id = id; this.id = id;
} }