diff --git a/OOP_2B1_Project/src/backend/Board.java b/OOP_2B1_Project/src/backend/Board.java index f909295..d5bbad6 100644 --- a/OOP_2B1_Project/src/backend/Board.java +++ b/OOP_2B1_Project/src/backend/Board.java @@ -181,6 +181,13 @@ public class Board implements Cloneable { if (move.getToCol() == x && move.getToRow() == y) { saveStateToHistory(); playMove(move); + + + boolean kingIsWhite = pieceToMove.isWhite(); + if (isKingInCheck(kingIsWhite)) { + System.out.println("Check! Game over."); + setGameOver(true); + } break; } } @@ -613,6 +620,33 @@ public class Board implements Cloneable { this.enPassantVulnerablePawn = null; } } - - + public boolean isKingInCheck(boolean kingIsWhite) { + Piece king = null; + for (Piece p : pieces) { + if (p.getType() == PieceType.King && p.isWhite() == kingIsWhite) { + king = p; + break; + } + } + if (king == null) { + return false; + } + + List opponentMoves = getAllLegalMoves(!kingIsWhite); + for (Move move : opponentMoves) { + if (move.getToCol() == king.getX() && move.getToRow() == king.getY()) { + return true; + } + } + return false; + } + private boolean gameOver = false; + + public boolean isGameOver() { + return gameOver; + } + + public void setGameOver(boolean gameOver) { + this.gameOver = gameOver; + } } diff --git a/OOP_2B1_Project/src/backend/Game.java b/OOP_2B1_Project/src/backend/Game.java index 0d8e57c..b814c88 100644 --- a/OOP_2B1_Project/src/backend/Game.java +++ b/OOP_2B1_Project/src/backend/Game.java @@ -32,7 +32,7 @@ public class Game extends Thread { } public void run() { - while(true) { + while(!board.isGameOver()) { aiPlayerTurn(); mjf.update(board.getTurnNumber(), board.isTurnWhite()); try { @@ -48,8 +48,16 @@ public class Game extends Thread { } private void aiPlayerTurn() { - if(isAITurn()) { - board.playMove(aiPlayer.computeBestMove(new Board(board))); + if (isAITurn()) { + Move bestMove = aiPlayer.computeBestMove(new Board(board)); + board.playMove(bestMove); + + // Check if the king is in check after the AI move + boolean kingIsWhite = board.isTurnWhite(); // This is the color of the player who just moved + if (board.isKingInCheck(!kingIsWhite)) { // Check the opponent's king + System.out.println("Check! Game over."); + board.setGameOver(true); + } } }