From 350965339281872ea6e242833c4de25392221ad7 Mon Sep 17 00:00:00 2001 From: HP Date: Sat, 17 May 2025 20:36:12 +0200 Subject: [PATCH] promotion with the undo ! --- src/backend/CheckManager.java | 50 +++++++++++++++++++++++++++++++++++ src/backend/Move.java | 3 ++- 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 src/backend/CheckManager.java diff --git a/src/backend/CheckManager.java b/src/backend/CheckManager.java new file mode 100644 index 0000000..d80be72 --- /dev/null +++ b/src/backend/CheckManager.java @@ -0,0 +1,50 @@ +package backend; + +import java.util.ArrayList; + +public class CheckManager { + private Board board; + + + public CheckManager(Board board) { + this.board = board; + } + + // Check if the king of a given color is in check + public boolean isKingInCheck(boolean isWhite) { + int[] kingPosition = board.findKingPosition(isWhite); // You must implement this + for (Piece piece : board.getPieces()) { + if (piece.isWhite() != isWhite) { + ArrayList enemyMoves = board.computeLegalMoves(piece); // you already have this? + for (int[] move : enemyMoves) { + if (move[0] == kingPosition[0] && move[1] == kingPosition[1]) { + return true; + } + } + } + } + return false; + } + + // Filter out illegal moves (those that leave king in check) + public ArrayList getLegalMovesFiltered(boolean isWhite) { + ArrayList allMoves = board.getAllMoves(isWhite); // You must write this or adapt it + ArrayList legalMoves = new ArrayList<>(); + + for (int[] move : allMoves) { + // board.makeMove(move); // Simulate move + boolean inCheck = isKingInCheck(isWhite); + // board.undoMove(); // Undo move + if (!inCheck) { + legalMoves.add(move); + } + } + + return legalMoves; + } + + public boolean isCheckmate(boolean isWhite) { + if (!isKingInCheck(isWhite)) return false; + return getLegalMovesFiltered(isWhite).isEmpty(); + } +} diff --git a/src/backend/Move.java b/src/backend/Move.java index cc260a7..aada99a 100644 --- a/src/backend/Move.java +++ b/src/backend/Move.java @@ -24,6 +24,7 @@ public class Move { public boolean isWhite() { return isWhite; } public PieceType getType() { return type; } public Piece getCapturedPiece() { return capturedPiece; } - } + +}