12 Commits

Author SHA1 Message Date
1022be4ecd yes 2025-04-19 14:17:39 +02:00
52d043b888 fix pgn winner 2025-04-19 14:15:59 +02:00
c289546914 multithreading 2025-04-19 14:15:53 +02:00
13b61ad71c big refactor 2025-04-19 12:56:08 +02:00
031d3d94ec pretty convincing 2025-04-18 23:51:42 +02:00
dd6e033528 working 2025-04-18 22:19:47 +02:00
4a58136afe almost working 2025-04-18 18:42:28 +02:00
b83726925e fix console 2025-04-18 10:33:10 +02:00
30eb12145d add hungry ai 2025-04-17 08:53:21 +02:00
17ef882d44 remove board from constructor 2025-04-16 19:29:31 +02:00
bee5e613bb refactor dumb ai castling 2025-04-16 19:25:04 +02:00
923ace22f1 add general ai 2025-04-16 19:21:47 +02:00
26 changed files with 923 additions and 226 deletions

View File

@@ -5,26 +5,17 @@ package chess;
import chess.controller.CommandExecutor;
import chess.controller.commands.NewGameCommand;
import chess.model.ChessBoard;
import chess.model.Game;
import chess.simulator.PromoteTest;
import chess.view.consolerender.Console;
public class ConsoleMain {
public static void main(String[] args) {
Game game = new Game(new ChessBoard());
Game game = new Game();
CommandExecutor commandExecutor = new CommandExecutor(game);
PromoteTest promoteTest = new PromoteTest(commandExecutor);
commandExecutor.addListener(promoteTest);
Console console = new Console(commandExecutor);
commandExecutor.addListener(console);
promoteTest.onComplete.connect(() -> {
console.setCaptureInput(true);
});
commandExecutor.executeCommand(new NewGameCommand());
}
}

View File

@@ -1,10 +1,10 @@
package chess;
import chess.ai.DumbAI;
import chess.ai.AI;
import chess.ai.minimax.AlphaBetaAI;
import chess.controller.CommandExecutor;
import chess.controller.commands.NewGameCommand;
import chess.controller.event.GameAdaptator;
import chess.model.ChessBoard;
import chess.model.Color;
import chess.model.Game;
import chess.pgn.PgnExport;
@@ -12,18 +12,21 @@ import chess.view.simplerender.Window;
public class SwingMain {
public static void main(String[] args) {
Game game = new Game(new ChessBoard());
Game game = new Game();
CommandExecutor commandExecutor = new CommandExecutor(game);
Window window = new Window(commandExecutor, false);
commandExecutor.addListener(window);
DumbAI ai = new DumbAI(commandExecutor, Color.Black);
AI ai = new AlphaBetaAI(commandExecutor, Color.White, 3);
commandExecutor.addListener(ai);
DumbAI ai2 = new DumbAI(commandExecutor, Color.White);
AI ai2 = new AlphaBetaAI(commandExecutor, Color.Black, 3);
commandExecutor.addListener(ai2);
// Window window2 = new Window(ai2.getSimulation(), false);
// ai2.getSimulation().addListener(window2);
commandExecutor.addListener(new GameAdaptator(){
@Override
public void onGameEnd() {

View File

@@ -0,0 +1,81 @@
package chess.ai;
import java.util.List;
import chess.controller.Command;
import chess.controller.CommandExecutor;
import chess.controller.Command.CommandResult;
import chess.controller.commands.GetPieceAtCommand;
import chess.controller.commands.GetPlayerMovesCommand;
import chess.controller.commands.GetAllowedCastlingsCommand;
import chess.controller.commands.GetAllowedCastlingsCommand.CastlingResult;
import chess.controller.event.GameAdaptator;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
import chess.model.Piece;
public abstract class AI extends GameAdaptator{
protected final CommandExecutor commandExecutor;
protected final Color color;
public AI(CommandExecutor commandExecutor, Color color) {
this.commandExecutor = commandExecutor;
this.color = color;
}
protected abstract void play();
protected abstract void promote(Coordinate pawnCoords);
@Override
public void onPlayerTurn(Color color, boolean undone) {
if (this.color != color || undone)
return;
play();
}
@Override
public void onPromotePawn(Coordinate pieceCoords) {
Piece pawn = pieceAt(pieceCoords);
if (pawn.getColor() != this.color)
return;
promote(pieceCoords);
}
protected Piece pieceAt(Coordinate coordinate) {
GetPieceAtCommand command = new GetPieceAtCommand(coordinate);
sendCommand(command);
return command.getPiece();
}
protected List<Move> getAllowedMoves() {
return getAllowedMoves(this.commandExecutor);
}
protected List<Move> getAllowedMoves(CommandExecutor commandExecutor) {
GetPlayerMovesCommand cmd = new GetPlayerMovesCommand();
sendCommand(cmd, commandExecutor);
return cmd.getMoves();
}
protected CastlingResult getAllowedCastlings() {
GetAllowedCastlingsCommand cmd2 = new GetAllowedCastlingsCommand();
sendCommand(cmd2);
return cmd2.getCastlingResult();
}
protected CommandResult sendCommand(Command command) {
return sendCommand(command, this.commandExecutor);
}
protected CommandResult sendCommand(Command command, CommandExecutor commandExecutor) {
CommandResult result = commandExecutor.executeCommand(command);
if(result == CommandResult.NotAllowed){
System.out.println("eeeeee");
}
return result;
}
}

View File

@@ -3,46 +3,28 @@ package chess.ai;
import java.util.List;
import java.util.Random;
import chess.controller.Command;
import chess.controller.CommandExecutor;
import chess.controller.commands.CastlingCommand;
import chess.controller.commands.GetAllowedCastlingsCommand;
import chess.controller.commands.GetPieceAtCommand;
import chess.controller.commands.GetPlayerMovesCommand;
import chess.controller.commands.GetAllowedCastlingsCommand.CastlingResult;
import chess.controller.commands.MoveCommand;
import chess.controller.commands.PromoteCommand;
import chess.controller.commands.GetAllowedCastlingsCommand.CastlingResult;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.controller.event.GameAdaptator;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
import chess.model.Piece;
public class DumbAI extends GameAdaptator {
public class DumbAI extends AI {
private final Color player;
private final CommandExecutor commandExecutor;
private final Random random = new Random();
public DumbAI(CommandExecutor commandExecutor, Color color) {
this.player = color;
this.commandExecutor = commandExecutor;
super(commandExecutor, color);
}
@Override
public void onPlayerTurn(Color color) {
if (color != player)
return;
GetPlayerMovesCommand cmd = new GetPlayerMovesCommand();
sendCommand(cmd);
GetAllowedCastlingsCommand cmd2 = new GetAllowedCastlingsCommand();
sendCommand(cmd2);
CastlingResult castlings = cmd2.getCastlingResult();
List<Move> moves = cmd.getMoves();
protected void play() {
CastlingResult castlings = getAllowedCastlings();
List<Move> moves = getAllowedMoves();
switch (castlings) {
case Both: {
@@ -53,20 +35,12 @@ public class DumbAI extends GameAdaptator {
return;
}
case Small: {
int randomMove = this.random.nextInt(moves.size() + 1);
if (randomMove != moves.size())
break;
this.commandExecutor.executeCommand(new CastlingCommand(false));
return;
}
case Small:
case Big: {
int randomMove = this.random.nextInt(moves.size() + 1);
if (randomMove != moves.size())
break;
this.commandExecutor.executeCommand(new CastlingCommand(true));
this.commandExecutor.executeCommand(new CastlingCommand(castlings == CastlingResult.Big));
return;
}
@@ -76,27 +50,12 @@ public class DumbAI extends GameAdaptator {
int randomMove = this.random.nextInt(moves.size());
this.commandExecutor.executeCommand(new MoveCommand(moves.get(randomMove)));
}
@Override
public void onPromotePawn(Coordinate pieceCoords) {
Piece pawn = pieceAt(pieceCoords);
if (pawn.getColor() != this.player)
return;
protected void promote(Coordinate pawnCoords) {
int promote = this.random.nextInt(PromoteType.values().length);
this.commandExecutor.executeCommand(new PromoteCommand(PromoteType.values()[promote]));
}
private Piece pieceAt(Coordinate coordinate) {
GetPieceAtCommand command = new GetPieceAtCommand(coordinate);
sendCommand(command);
return command.getPiece();
}
private void sendCommand(Command command) {
this.commandExecutor.executeCommand(command);
}
}

View File

@@ -0,0 +1,61 @@
package chess.ai;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import chess.controller.CommandExecutor;
import chess.controller.commands.MoveCommand;
import chess.controller.commands.PromoteCommand;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
import chess.model.Piece;
public class HungryAI extends AI {
private final PieceCost pieceCost;
private final Random random;
public HungryAI(CommandExecutor commandExecutor, Color color) {
super(commandExecutor, color);
this.pieceCost = new PieceCost(color);
this.random = new Random();
}
private int getMoveCost(Move move) {
Piece piece = pieceAt(move.getDeadPieceCoords());
return - (int) pieceCost.getCost(piece);
}
private List<Move> getBestMoves() {
List<Move> moves = getAllowedMoves();
List<Move> bestMoves = new ArrayList<>();
int bestCost = 0;
for (Move move : moves) {
int moveCost = getMoveCost(move);
if (moveCost == bestCost) {
bestMoves.add(move);
} else if (moveCost > bestCost) {
bestMoves.clear();
bestMoves.add(move);
bestCost = moveCost;
}
}
return bestMoves;
}
@Override
protected void play() {
List<Move> bestMoves = getBestMoves();
int randomMove = this.random.nextInt(bestMoves.size());
this.commandExecutor.executeCommand(new MoveCommand(bestMoves.get(randomMove)));
}
@Override
protected void promote(Coordinate pawnCoords) {
sendCommand(new PromoteCommand(PromoteType.Queen));
}
}

View File

@@ -0,0 +1,67 @@
package chess.ai;
import chess.model.Color;
import chess.model.Piece;
import chess.model.PieceVisitor;
import chess.model.pieces.Bishop;
import chess.model.pieces.King;
import chess.model.pieces.Knight;
import chess.model.pieces.Pawn;
import chess.model.pieces.Queen;
import chess.model.pieces.Rook;
public class PieceCost implements PieceVisitor<Float> {
private final Color player;
public static final float BISHOP = 30;
public static final float KING = 900;
public static final float KNIGHT = 30;
public static final float PAWN = 10;
public static final float QUEEN = 90;
public static final float ROOK = 50;
public PieceCost(Color color) {
this.player = color;
}
public float getCost(Piece piece) {
if (piece == null)
return 0;
float cost = visit(piece);
if (piece.getColor() != player)
cost = -cost;
return cost;
}
@Override
public Float visitPiece(Bishop bishop) {
return BISHOP;
}
@Override
public Float visitPiece(King king) {
return KING;
}
@Override
public Float visitPiece(Knight knight) {
return KNIGHT;
}
@Override
public Float visitPiece(Pawn pawn) {
return PAWN;
}
@Override
public Float visitPiece(Queen queen) {
return QUEEN;
}
@Override
public Float visitPiece(Rook rook) {
return ROOK;
}
}

View File

@@ -0,0 +1,129 @@
package chess.ai;
import java.util.Arrays;
import java.util.List;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Piece;
import chess.model.PieceVisitor;
import chess.model.pieces.Bishop;
import chess.model.pieces.King;
import chess.model.pieces.Knight;
import chess.model.pieces.Pawn;
import chess.model.pieces.Queen;
import chess.model.pieces.Rook;
public class PiecePosCost implements PieceVisitor<List<Float>> {
private final Color color;
private static final List<Float> BISHOP = Arrays.asList(
-2.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -2.0f,
-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f,
-1.0f, 0.0f, 0.5f, 1.0f, 1.0f, 0.5f, 0.0f, -1.0f,
-1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -1.0f,
-1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, -1.0f,
-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f,
-1.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, -1.0f,
-2.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -2.0f);
private static final List<Float> KING = Arrays.asList(
-3.0f, -4.0f, -4.0f, -5.0f, -5.0f, -4.0f, -4.0f, -3.0f,
-3.0f, -4.0f, -4.0f, -5.0f, -5.0f, -4.0f, -4.0f, -3.0f,
-3.0f, -4.0f, -4.0f, -5.0f, -5.0f, -4.0f, -4.0f, -3.0f,
-3.0f, -4.0f, -4.0f, -5.0f, -5.0f, -4.0f, -4.0f, -3.0f,
-2.0f, -3.0f, -3.0f, -4.0f, -4.0f, -3.0f, -3.0f, -2.0f,
-1.0f, -2.0f, -2.0f, -2.0f, -2.0f, -2.0f, -2.0f, -1.0f,
2.0f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, 2.0f,
2.0f, 3.0f, 1.0f, 0.0f, 0.0f, 1.0f, 3.0f, 2.0f);
private static final List<Float> KNIGHT = Arrays.asList(
-5.0f, -4.0f, -3.0f, -3.0f, -3.0f, -3.0f, -4.0f, -5.0f,
-4.0f, -2.0f, 0.0f, 0.0f, 0.0f, 0.0f, -2.0f, -4.0f,
-3.0f, 0.0f, 1.0f, 1.5f, 1.5f, 1.0f, 0.0f, -3.0f,
-3.0f, 0.5f, 1.5f, 2.0f, 2.0f, 1.5f, 0.5f, -3.0f,
-3.0f, 0.0f, 1.5f, 2.0f, 2.0f, 1.5f, 0.0f, -3.0f,
-3.0f, 0.5f, 1.0f, 1.5f, 1.5f, 1.0f, 0.5f, -3.0f,
-4.0f, -2.0f, 0.0f, 0.5f, 0.5f, 0.0f, -2.0f, -4.0f,
-5.0f, -4.0f, -3.0f, -3.0f, -3.0f, -3.0f, -4.0f, -5.0f);
private static final List<Float> PAWN = Arrays.asList(
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f,
1.0f, 1.0f, 2.0f, 3.0f, 3.0f, 2.0f, 1.0f, 1.0f,
0.5f, 0.5f, 1.0f, 2.5f, 2.5f, 1.0f, 0.5f, 0.5f,
0.0f, 0.0f, 1.0f, 2.0f, 2.0f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f,
0.5f, 1.0f, 1.0f, -2.0f, -2.0f, 1.0f, 1.0f, 0.5f,
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
private static final List<Float> QUEEN = Arrays.asList(
-2.0f, -1.0f, -1.0f, -0.5f, -0.5f, -1.0f, -1.0f, -2.0f,
-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f,
-1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.5f, 0.0f, -1.0f,
-0.5f, 0.0f, 0.5f, 0.5f, 0.5f, 0.5f, 0.0f, -0.5f,
0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.5f, 0.0f, -0.5f,
-1.0f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.0f, -1.0f,
-1.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f,
-2.0f, -1.0f, -1.0f, -0.5f, -0.5f, -1.0f, -1.0f, -2.0f);
private static final List<Float> ROOK = Arrays.asList(
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f,
-0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f,
-0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f,
-0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f,
-0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f,
-0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f,
0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f);
public PiecePosCost(Color color) {
this.color = color;
}
public float getEvaluation(Piece piece, Coordinate coordinate) {
if (piece == null)
return 0;
List<Float> positions = visit(piece);
int x = piece.getColor() == Color.Black ? (Coordinate.VALUE_MAX - 1 - coordinate.getX()) : coordinate.getX();
int y = piece.getColor() == Color.Black ? (Coordinate.VALUE_MAX - 1 - coordinate.getY()) : coordinate.getY();
Coordinate newCoords = new Coordinate(x, y);
assert newCoords.isValid();
float result = positions.get(newCoords.toIndex());
if (piece.getColor() != color)
return -result;
return result;
}
@Override
public List<Float> visitPiece(Bishop bishop) {
return BISHOP;
}
@Override
public List<Float> visitPiece(King king) {
return KING;
}
@Override
public List<Float> visitPiece(Knight knight) {
return KNIGHT;
}
@Override
public List<Float> visitPiece(Pawn pawn) {
return PAWN;
}
@Override
public List<Float> visitPiece(Queen queen) {
return QUEEN;
}
@Override
public List<Float> visitPiece(Rook rook) {
return ROOK;
}
}

View File

@@ -0,0 +1,88 @@
package chess.ai.minimax;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import chess.ai.AI;
import chess.controller.CommandExecutor;
import chess.controller.commands.MoveCommand;
import chess.controller.commands.PromoteCommand;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
public class AlphaBetaAI extends AI {
private final int searchDepth;
private static final float MAX_FLOAT = Float.MAX_VALUE;
private static final float MIN_FLOAT = -MAX_FLOAT;
private final ExecutorService threadPool;
public AlphaBetaAI(CommandExecutor commandExecutor, Color color, int searchDepth) {
super(commandExecutor, color);
this.searchDepth = searchDepth;
int threadCount = Runtime.getRuntime().availableProcessors() - 1;
this.threadPool = Executors.newFixedThreadPool(threadCount, new AlphaBetaThreadCreator(commandExecutor, color, threadCount));
System.out.println();
}
private Move getBestMove() {
List<Move> moves = getAllowedMoves();
List<Future<Float>> moveEvaluations = new ArrayList<>(50);
float bestMoveValue = MIN_FLOAT;
Move bestMove = null;
System.out.println("Evaluating " + moves.size() + " moves ...");
for (Move move : moves) {
moveEvaluations.add(this.threadPool.submit(() -> {
return AlphaBetaThreadCreator.getMoveValue(move, this.searchDepth);
}));
}
for (int i = 0; i < moves.size(); i++) {
Move move = moves.get(i);
float value = MIN_FLOAT;
try {
value = moveEvaluations.get(i).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (value > bestMoveValue) {
bestMoveValue = value;
bestMove = move;
}
}
System.out.println("Best move : " + bestMoveValue);
return bestMove;
}
@Override
public void onGameEnd() {
this.threadPool.close();
}
@Override
protected void play() {
long current = System.currentTimeMillis();
Move move = getBestMove();
long elapsed = System.currentTimeMillis() - current;
System.out.println("Took " + elapsed + "ms");
sendCommand(new MoveCommand(move));
}
@Override
protected void promote(Coordinate pawnCoords) {
sendCommand(new PromoteCommand(PromoteType.Queen));
}
}

View File

@@ -0,0 +1,94 @@
package chess.ai.minimax;
import java.util.List;
import chess.ai.PieceCost;
import chess.ai.PiecePosCost;
import chess.model.ChessBoard;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
import chess.model.Piece;
public class AlphaBetaThread extends Thread {
private final GameSimulation simulation;
private final PieceCost pieceCost;
private final PiecePosCost piecePosCost;
private final Color color;
private static final int GREAT_MOVE = -9999;
private static final int HORRIBLE_MOVE = -GREAT_MOVE;
private static final float MAX_FLOAT = Float.MAX_VALUE;
private static final float MIN_FLOAT = -MAX_FLOAT;
public AlphaBetaThread(Runnable task, GameSimulation simulation, Color color) {
super(task);
this.simulation = simulation;
this.pieceCost = new PieceCost(color);
this.piecePosCost = new PiecePosCost(color);
this.color = color;
}
private float getEndGameEvaluation() {
Color currentTurn = this.simulation.getPlayerTurn();
if (currentTurn == this.color) {
return HORRIBLE_MOVE;
} else {
if (this.simulation.getBoard().isKingInCheck(currentTurn))
return GREAT_MOVE;
return getBoardEvaluation() + PieceCost.PAWN;
}
}
private float getBoardEvaluation() {
final ChessBoard board = this.simulation.getBoard();
float result = 0;
for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
Coordinate coordinate = new Coordinate(i, j);
Piece piece = board.pieceAt(coordinate);
result += pieceCost.getCost(piece) + piecePosCost.getEvaluation(piece, coordinate);
}
}
if (this.simulation.getPlayerTurn() != color)
return -result;
return result;
}
public float getMoveValue(Move move, int searchDepth) {
this.simulation.tryMove(move);
float value = -negaMax(searchDepth - 1, MIN_FLOAT, MAX_FLOAT);
this.simulation.undoMove();
return value;
}
private float negaMax(int depth, float alpha, float beta) {
if (depth == 0)
return getBoardEvaluation();
float value = MIN_FLOAT;
List<Move> moves = this.simulation.getAllowedMoves();
if (moves.isEmpty())
return getEndGameEvaluation();
for (Move move : moves) {
this.simulation.tryMove(move);
value = Float.max(value, -negaMax(depth - 1, -beta, -alpha));
this.simulation.undoMove();
alpha = Float.max(alpha, value);
if (alpha >= beta)
return value;
}
return value;
}
public GameSimulation getSimulation() {
return simulation;
}
}

View File

@@ -0,0 +1,36 @@
package chess.ai.minimax;
import java.util.concurrent.ThreadFactory;
import chess.controller.CommandExecutor;
import chess.model.Color;
import chess.model.Move;
public class AlphaBetaThreadCreator implements ThreadFactory{
private final Color color;
private final GameSimulation simulations[];
private int currentThread = 0;
public AlphaBetaThreadCreator(CommandExecutor commandExecutor, Color color, int threadCount) {
this.color = color;
simulations = new GameSimulation[threadCount];
for (int i = 0; i < threadCount; i++) {
simulations[i] = new GameSimulation();
commandExecutor.addListener(simulations[i]);
}
}
public static float getMoveValue(Move move, int searchDepth) {
AlphaBetaThread t = (AlphaBetaThread) Thread.currentThread();
return t.getMoveValue(move, searchDepth);
}
@Override
public Thread newThread(Runnable r) {
AlphaBetaThread t = new AlphaBetaThread(r, simulations[currentThread], color);
currentThread++;
return t;
}
}

View File

@@ -0,0 +1,96 @@
package chess.ai.minimax;
import java.util.List;
import chess.controller.Command;
import chess.controller.Command.CommandResult;
import chess.controller.CommandExecutor;
import chess.controller.commands.CastlingCommand;
import chess.controller.commands.GetPlayerMovesCommand;
import chess.controller.commands.MoveCommand;
import chess.controller.commands.NewGameCommand;
import chess.controller.commands.PromoteCommand;
import chess.controller.commands.UndoCommand;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.controller.event.EmptyGameDispatcher;
import chess.controller.event.GameAdaptator;
import chess.model.ChessBoard;
import chess.model.Color;
import chess.model.Game;
import chess.model.Move;
public class GameSimulation extends GameAdaptator {
private final CommandExecutor simulation;
private final Game gameSimulation;
public GameSimulation() {
this.gameSimulation = new Game();
this.simulation = new CommandExecutor(gameSimulation, new EmptyGameDispatcher());
}
protected CommandResult sendCommand(Command command) {
CommandResult result = this.simulation.executeCommand(command);
if (result == CommandResult.NotAllowed) {
System.out.println("eeeeee");
}
return result;
}
public void tryMove(Move move) {
sendCommand(new MoveCommand(move));
if (this.gameSimulation.getBoard().pawnShouldBePromoted())
sendCommand(new PromoteCommand(PromoteType.Queen));
}
public void undoMove() {
sendCommand(new UndoCommand());
}
@Override
public void onPawnPromoted(PromoteType promotion) {
sendCommand(new PromoteCommand(promotion));
}
@Override
public void onCastling(boolean bigCastling) {
sendCommand(new CastlingCommand(bigCastling));
}
@Override
public void onMove(Move move) {
sendCommand(new MoveCommand(move));
}
@Override
public void onGameStart() {
sendCommand(new NewGameCommand());
}
public CommandExecutor getCommandExecutor() {
return simulation;
}
public Game getGame() {
return gameSimulation;
}
public ChessBoard getBoard() {
return this.gameSimulation.getBoard();
}
public Color getPlayerTurn() {
return this.gameSimulation.getPlayerTurn();
}
public List<Move> getAllowedMoves() {
GetPlayerMovesCommand cmd = new GetPlayerMovesCommand();
sendCommand(cmd);
return cmd.getMoves();
}
public void close() {
this.simulation.close();
}
}

View File

@@ -2,6 +2,7 @@ package chess.controller;
import chess.controller.Command.CommandResult;
import chess.controller.commands.UndoCommand;
import chess.controller.event.AsyncGameDispatcher;
import chess.controller.event.GameDispatcher;
import chess.controller.event.GameListener;
import chess.model.Game;
@@ -17,7 +18,7 @@ public class CommandExecutor {
}
public CommandExecutor(Game game) {
this(game, new GameDispatcher());
this(game, new AsyncGameDispatcher());
}
public CommandExecutor(Game game, GameDispatcher dispatcher) {
@@ -52,19 +53,21 @@ public class CommandExecutor {
return;
case Moved:
boolean notifyPlayerTurn = true;
this.dispatcher.onBoardUpdate();
if (checkGameStatus()) {
this.dispatcher.onGameEnd();
return;
notifyPlayerTurn = false;
}
switchPlayerTurn();
switchPlayerTurn(command instanceof UndoCommand, notifyPlayerTurn);
return;
}
}
private void switchPlayerTurn() {
private void switchPlayerTurn(boolean undone, boolean notifyPlayerTurn) {
this.game.switchPlayerTurn();
this.dispatcher.onPlayerTurn(this.game.getPlayerTurn());
if (notifyPlayerTurn)
this.dispatcher.onPlayerTurn(this.game.getPlayerTurn(), undone);
}
/**
@@ -107,6 +110,6 @@ public class CommandExecutor {
}
public void close() {
this.dispatcher.stopService();
this.dispatcher.close();
}
}

View File

@@ -49,6 +49,8 @@ public class CastlingCommand extends PlayerCommand {
board.applyMove(this.kingMove);
board.applyMove(this.rookMove);
outputSystem.onCastling(this.bigCastling);
return CommandResult.Moved;
}

View File

@@ -37,7 +37,6 @@ public class MoveCommand extends PlayerCommand {
return result;
case Moved:
outputSystem.onMove(this.move);
game.saveTraitPiecesPos();
return result;
@@ -76,11 +75,14 @@ public class MoveCommand extends PlayerCommand {
}
if (tryPromote(game, outputSystem)) {
outputSystem.onMove(this.move);
return CommandResult.ActionNeeded;
}
board.setLastMove(this.move);
outputSystem.onMove(this.move);
return CommandResult.Moved;
}

View File

@@ -51,7 +51,7 @@ public class NewGameCommand extends Command {
game.reset();
outputSystem.onGameStart();
outputSystem.onPlayerTurn(game.getPlayerTurn());
outputSystem.onPlayerTurn(game.getPlayerTurn(), false);
return CommandResult.NotMoved;
}

View File

@@ -55,6 +55,8 @@ public class PromoteCommand extends PlayerCommand {
this.oldPawn = pawn;
board.pieceComes(createPiece(this.promoteType, pawn.getColor()), this.pieceCoords);
outputSystem.onPawnPromoted(this.promoteType);
return CommandResult.Moved;
}

View File

@@ -0,0 +1,113 @@
package chess.controller.event;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
public class AsyncGameDispatcher extends GameDispatcher {
private final List<GameListener> listeners;
private final ExecutorService executor;
public AsyncGameDispatcher() {
this.listeners = new ArrayList<>();
this.executor = Executors.newSingleThreadExecutor();
}
@Override
public void addListener(GameListener listener) {
this.listeners.add(listener);
}
private void asyncForEachCall(Consumer<GameListener> func) {
this.executor.execute(() -> this.listeners.forEach(func));
}
@Override
public void onPlayerTurn(Color color, boolean undone) {
asyncForEachCall((l) -> l.onPlayerTurn(color, undone));
}
@Override
public void onWin(Color color) {
asyncForEachCall((l) -> l.onWin(color));
}
@Override
public void onKingInCheck() {
asyncForEachCall((l) -> l.onKingInCheck());
}
@Override
public void onKingInMat() {
asyncForEachCall((l) -> l.onKingInMat());
}
@Override
public void onPatSituation() {
asyncForEachCall((l) -> l.onPatSituation());
}
@Override
public void onSurrender(Color color) {
asyncForEachCall((l) -> l.onSurrender(color));
}
@Override
public void onGameStart() {
asyncForEachCall((l) -> l.onGameStart());
}
@Override
public void onPromotePawn(Coordinate pieceCoords) {
asyncForEachCall((l) -> l.onPromotePawn(pieceCoords));
}
@Override
public void onBoardUpdate() {
asyncForEachCall((l) -> l.onBoardUpdate());
}
@Override
public void onGameEnd() {
asyncForEachCall((l) -> l.onGameEnd());
}
@Override
public void onMove(Move move) {
asyncForEachCall((l) -> l.onMove(move));
}
@Override
public void onMoveNotAllowed(Move move) {
asyncForEachCall((l) -> l.onMoveNotAllowed(move));
}
@Override
public void onDraw() {
asyncForEachCall((l) -> l.onDraw());
}
@Override
public void onCastling(boolean bigCastling) {
asyncForEachCall((l) -> l.onCastling(bigCastling));
}
@Override
public void onPawnPromoted(PromoteType promotion) {
asyncForEachCall((l) -> l.onPawnPromoted(promotion));
}
@Override
public void close() {
this.executor.shutdown();
}
}

View File

@@ -1,5 +1,6 @@
package chess.controller.event;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
@@ -43,7 +44,7 @@ public class EmptyGameDispatcher extends GameDispatcher {
}
@Override
public void onPlayerTurn(Color color) {
public void onPlayerTurn(Color color, boolean undone) {
}
@Override
@@ -58,4 +59,20 @@ public class EmptyGameDispatcher extends GameDispatcher {
public void onWin(Color winner) {
}
@Override
public void onCastling(boolean bigCastling) {
}
@Override
public void onPawnPromoted(PromoteType promotion) {
}
@Override
public void addListener(GameListener listener) {
}
@Override
public void close() {
}
}

View File

@@ -1,5 +1,6 @@
package chess.controller.event;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
@@ -7,7 +8,7 @@ import chess.model.Move;
public abstract class GameAdaptator implements GameListener {
@Override
public void onPlayerTurn(Color color) {}
public void onPlayerTurn(Color color, boolean undone) {}
@Override
public void onWin(Color color) {}
@@ -45,4 +46,10 @@ public abstract class GameAdaptator implements GameListener {
@Override
public void onDraw() {}
@Override
public void onCastling(boolean bigCastling) {}
@Override
public void onPawnPromoted(PromoteType promotion) {}
}

View File

@@ -1,100 +1,9 @@
package chess.controller.event;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
public abstract class GameDispatcher extends GameAdaptator {
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
public abstract void addListener(GameListener listener);
public class GameDispatcher implements GameListener {
private final List<GameListener> listeners;
private final ExecutorService executor;
public GameDispatcher() {
this.listeners = new ArrayList<>();
this.executor = Executors.newSingleThreadExecutor();
}
public void addListener(GameListener listener) {
this.listeners.add(listener);
}
private void asyncForEachCall(Consumer<GameListener> func) {
this.executor.execute(() -> this.listeners.forEach(func));
}
@Override
public void onPlayerTurn(Color color) {
asyncForEachCall((l) -> l.onPlayerTurn(color));
}
@Override
public void onWin(Color color) {
asyncForEachCall((l) -> l.onWin(color));
}
@Override
public void onKingInCheck() {
asyncForEachCall((l) -> l.onKingInCheck());
}
@Override
public void onKingInMat() {
asyncForEachCall((l) -> l.onKingInMat());
}
@Override
public void onPatSituation() {
asyncForEachCall((l) -> l.onPatSituation());
}
@Override
public void onSurrender(Color color) {
asyncForEachCall((l) -> l.onSurrender(color));
}
@Override
public void onGameStart() {
asyncForEachCall((l) -> l.onGameStart());
}
@Override
public void onPromotePawn(Coordinate pieceCoords) {
asyncForEachCall((l) -> l.onPromotePawn(pieceCoords));
}
@Override
public void onBoardUpdate() {
asyncForEachCall((l) -> l.onBoardUpdate());
}
@Override
public void onGameEnd() {
asyncForEachCall((l) -> l.onGameEnd());
}
@Override
public void onMove(Move move) {
asyncForEachCall((l) -> l.onMove(move));
}
@Override
public void onMoveNotAllowed(Move move) {
asyncForEachCall((l) -> l.onMoveNotAllowed(move));
}
@Override
public void onDraw() {
asyncForEachCall((l) -> l.onDraw());
}
public void stopService() {
this.executor.shutdown();
}
public abstract void close();
}

View File

@@ -1,5 +1,6 @@
package chess.controller.event;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
@@ -38,12 +39,14 @@ public interface GameListener {
/**
* Invoked when a valid move on the board occurs
*
* @param move the move to be processed
*/
void onMove(Move move);
/**
* Invoked when a sent move is not allowed
*
* @param move the move to be processed
*/
void onMoveNotAllowed(Move move);
@@ -55,26 +58,46 @@ public interface GameListener {
/**
* Invoked when it's the player turn
* @param color the color of the player who should play
*
* @param color the color of the player who should play
* @param undone true if it's a result of an undo command
*/
void onPlayerTurn(Color color);
void onPlayerTurn(Color color, boolean undone);
/**
* Invoked when a pawn should be promoted
*
* @param pieceCoords the coordinates of the pawn
*/
void onPromotePawn(Coordinate pieceCoords);
/**
* Invoked when a players surrenders
*
* @param coward the player who gave up
*/
void onSurrender(Color coward);
/**
* Invoked when a player wins (by checkmate or if the other one surrenders)
*
* @param winner
*/
void onWin(Color winner);
/**
* Invoked when a castling is done
*
* @param bigCastling if it's queen side castling
*/
void onCastling(boolean bigCastling);
/**
* Invoked when a pawn is promoted
*
* @param promotion the type of promotion
* @param player the player who promoted the pawns
*/
void onPawnPromoted(PromoteType promotion);
}

View File

@@ -20,8 +20,8 @@ public class Game {
Draw, Check, CheckMate, OnGoing, Pat;
}
public Game(ChessBoard board) {
this.board = board;
public Game() {
this.board = new ChessBoard();
this.movesHistory = new Stack<>();
this.traitsPos = new HashMap<>();
}
@@ -70,24 +70,26 @@ public class Game {
playerTurn = Color.getEnemy(playerTurn);
}
public GameStatus checkGameStatus() {
final Color enemy = Color.getEnemy(getPlayerTurn());
public GameStatus checkGameStatus(Color color) {
if (checkDraw())
return GameStatus.Draw;
if (this.board.isKingInCheck(enemy))
if (this.board.hasAllowedMoves(enemy))
if (this.board.isKingInCheck(color))
if (this.board.hasAllowedMoves(color))
return GameStatus.Check;
else
return GameStatus.CheckMate;
if (!board.hasAllowedMoves(enemy))
if (!board.hasAllowedMoves(color))
return GameStatus.Pat;
return GameStatus.OnGoing;
}
public GameStatus checkGameStatus() {
return checkGameStatus(Color.getEnemy(getPlayerTurn()));
}
public void addAction(PlayerCommand command) {
this.movesHistory.add(command);
}

View File

@@ -11,7 +11,6 @@ import chess.controller.commands.MoveCommand;
import chess.controller.commands.NewGameCommand;
import chess.controller.commands.PromoteCommand;
import chess.controller.event.EmptyGameDispatcher;
import chess.model.ChessBoard;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Game;
@@ -22,24 +21,24 @@ import chess.model.pieces.Pawn;
public class PgnExport {
// public static void main(String[] args) {
// final Game game = new Game(new ChessBoard());
// final CommandExecutor commandExecutor = new CommandExecutor(game);
// final Game game = new Game();
// final CommandExecutor commandExecutor = new CommandExecutor(game);
// DumbAI ai1 = new DumbAI(commandExecutor, Color.White);
// commandExecutor.addListener(ai1);
// DumbAI ai1 = new DumbAI(commandExecutor, Color.White);
// commandExecutor.addListener(ai1);
// DumbAI ai2 = new DumbAI(commandExecutor, Color.Black);
// commandExecutor.addListener(ai2);
// DumbAI ai2 = new DumbAI(commandExecutor, Color.Black);
// commandExecutor.addListener(ai2);
// commandExecutor.addListener(new GameAdaptator() {
// @Override
// public void onGameEnd() {
// System.out.println(exportGame(game));
// commandExecutor.close();
// }
// });
// commandExecutor.addListener(new GameAdaptator() {
// @Override
// public void onGameEnd() {
// System.out.println(exportGame(game));
// commandExecutor.close();
// }
// });
// commandExecutor.executeCommand(new NewGameCommand());
// commandExecutor.executeCommand(new NewGameCommand());
// }
private static final PiecePgnName piecePgnName = new PiecePgnName();
@@ -57,15 +56,15 @@ public class PgnExport {
}
private static String gameEnd(Game game) {
switch (game.checkGameStatus()) {
switch (game.checkGameStatus(game.getPlayerTurn())) {
case Draw:
case Pat:
return "1/2-1/2";
case CheckMate:
if (game.getPlayerTurn() == Color.White)
return "1-0";
return "0-1";
return "0-1";
return "1-0";
default:
return "";
@@ -138,7 +137,7 @@ public class PgnExport {
}
private static String checkCheckMate(Game game) {
switch (game.checkGameStatus()) {
switch (game.checkGameStatus(game.getPlayerTurn())) {
case CheckMate:
return "#";
@@ -190,8 +189,7 @@ public class PgnExport {
public static String exportGame(Game game) {
ChessBoard board = new ChessBoard();
Game virtualGame = new Game(board);
Game virtualGame = new Game();
CommandExecutor executor = new CommandExecutor(virtualGame, new EmptyGameDispatcher());
executor.executeCommand(new NewGameCommand());

View File

@@ -20,12 +20,17 @@ public class Console implements GameListener {
private final Scanner scanner = new Scanner(System.in);
private final CommandExecutor commandExecutor;
private final ConsolePieceName consolePieceName = new ConsolePieceName();
private boolean captureInput = false;
private boolean captureInput;
private final ExecutorService executor;
public Console(CommandExecutor commandExecutor) {
public Console(CommandExecutor commandExecutor, boolean captureInput) {
this.commandExecutor = commandExecutor;
this.executor = Executors.newSingleThreadExecutor();
this.captureInput = captureInput;
}
public Console(CommandExecutor commandExecutor) {
this(commandExecutor, true);
}
private Piece pieceAt(int x, int y) {
@@ -61,7 +66,7 @@ public class Console implements GameListener {
}
@Override
public void onPlayerTurn(Color color) {
public void onPlayerTurn(Color color, boolean undone) {
if (!captureInput)
return;
System.out.println(Colors.RED + "Player turn: " + color + Colors.RESET);
@@ -328,4 +333,11 @@ public class Console implements GameListener {
this.captureInput = captureInput;
}
@Override
public void onCastling(boolean bigCastling) {}
@Override
public void onPawnPromoted(PromoteType promotion) {}
}

View File

@@ -213,7 +213,7 @@ public class Window extends JFrame implements GameListener {
}
@Override
public void onPlayerTurn(chess.model.Color color) {
public void onPlayerTurn(chess.model.Color color, boolean undone) {
this.displayText.setText("Current turn: " + color);
updateButtons();
}
@@ -318,4 +318,10 @@ public class Window extends JFrame implements GameListener {
JOptionPane.showMessageDialog(this, "Same position was repeated three times. It's a draw!");
}
@Override
public void onCastling(boolean bigCastling) {}
@Override
public void onPawnPromoted(PromoteType promotion) {}
}

View File

@@ -3,24 +3,20 @@
*/
package chess;
import org.junit.jupiter.api.Test;
import chess.ai.DumbAI;
import chess.controller.Command;
import chess.controller.CommandExecutor;
import chess.controller.commands.NewGameCommand;
import chess.controller.commands.UndoCommand;
import chess.controller.event.GameAdaptator;
import chess.model.*;
import chess.model.pieces.*;
import chess.simulator.Simulator;
import chess.view.simplerender.Window;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Objects;
import chess.model.Color;
import chess.model.Game;
class AppTest {
@Test void functionalRollback(){
Game game = new Game(new ChessBoard());
Game game = new Game();
CommandExecutor commandExecutor = new CommandExecutor(game);
DumbAI ai = new DumbAI(commandExecutor, Color.Black);
@@ -38,9 +34,9 @@ class AppTest {
result = commandExecutor.executeCommand(new UndoCommand());
} while (result != Command.CommandResult.NotAllowed);
Game initialGame = new Game(new ChessBoard());
Game initialGame = new Game();
CommandExecutor initialCommandExecutor = new CommandExecutor(initialGame);
commandExecutor.executeCommand(new NewGameCommand());
initialCommandExecutor.executeCommand(new NewGameCommand());
assert(game.getBoard().equals(initialGame.getBoard()));