package backend; import windowInterface.MyInterface; import java.util.List; public class Game extends Thread { private final AutoPlayer aiPlayer; private Board board; private final MyInterface ui; private final boolean[] aiOn = new boolean[2]; // [0]=black, [1]=white private int whiteCaptures = 0, blackCaptures = 0; private boolean gameOver = false; private int loopDelay = 250; // ms public Game(MyInterface ui) { this.ui = ui; this.board = new Board(8, 8); this.aiPlayer = new AutoPlayer(); } public int getWidth() { return board.getWidth(); } public int getHeight() { return board.getHeight(); } public int getWhiteCaptures() { return whiteCaptures; } public int getBlackCaptures() { return blackCaptures; } @Override public void run() { while (!gameOver) { if (aiOn[board.isTurnWhite() ? 1 : 0]) { Move m = aiPlayer.computeBestMove(new Board(board)); board.playMove(m); recordCapture(m); checkEnd(); } ui.update(board.getTurnNumber(), board.isTurnWhite()); try { Thread.sleep(loopDelay); } catch (InterruptedException e) { } } } private void recordCapture(Move m) { if (m != null && m.getCapturedPiece() != null) { if (m.isWhite()) whiteCaptures++; else blackCaptures++; } } public void clickCoords(int x, int y) { if (gameOver) return; if (!aiOn[board.isTurnWhite() ? 1 : 0]) { board.userTouch(x, y); Move last = board.getLastMove(); recordCapture(last); checkEnd(); } } private void checkEnd() { boolean side = board.isTurnWhite(); List replies = board.generateLegalMoves(side); if (replies.isEmpty()) { String msg; if (board.isInCheck(side)) { msg = (side ? "White" : "Black") + " is checkmated. " + (!side ? "White" : "Black") + " wins!"; } else { msg = "Stalemate—draw."; } ui.gameOver(msg); gameOver = true; } } // ─── simple forwards to Board ───────────────────────────────────────── public void setPiece(boolean w, PieceType t, int x, int y) { board.setPiece(w, t, x, y); } public void setDefaultSetup() { board.cleanBoard(); board.populateBoard(); } public void setBoard(String[] rows) { board = new Board(rows); } public String[] getFileRepresentation() { return board.toFileRep(); } public Iterable getPieces() { return board.getPieces(); } public boolean isSelected(int x, int y) { return board.isSelected(x, y); } public boolean isHighlighted(int x, int y) { return board.isHighlighted(x, y); } public void undoLastMove() { board.undoLastMove(); } public void toggleAI(boolean isWhite) { aiOn[isWhite ? 1 : 0] = !aiOn[isWhite ? 1 : 0]; } public Board getBoard() { return board; } public void setLoopDelay(int ms) { this.loopDelay = ms; } }