AiPlayerTurn update + UserTouch (Game stop when King is in echec)

This commit is contained in:
Tilman Crosetti 2025-05-22 00:03:21 +02:00
parent 1227a67ee3
commit 216d7cf153
2 changed files with 47 additions and 5 deletions

View File

@ -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<Move> 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;
}
}

View File

@ -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);
}
}
}