package chess.io; import chess.io.commands.MoveCommand; import chess.model.ChessBoard; import chess.model.Color; import chess.model.Coordinate; import chess.model.Game; import chess.model.Piece; import chess.model.pieces.Pawn; public class CommandExecutor { private Game game; private OutputSystem outputSystem; public CommandExecutor() { this.game = null; this.outputSystem = null; } public CommandResult executeCommand(Command command) { CommandResult result = command.execute(this.game, this.outputSystem); if (result == CommandResult.Moved) { checkPromotion(((MoveCommand) command).getMove().getFinish()); checkGameStatus(); alternatePlayers(); } return result; } private void alternatePlayers() { this.game.switchPlayerTurn(); this.outputSystem.playerTurn(this.game.getPlayerTurn()); } public void setOutputSystem(OutputSystem outputSystem) { this.outputSystem = outputSystem; } public void setGame(Game game) { this.game = game; } private void checkPromotion(Coordinate pieceCoords) { Piece piece = this.game.getBoard().pieceAt(pieceCoords); if (piece == null || !(piece instanceof Pawn)) return; int destY = pieceCoords.getY(); int enemyLine = piece.getColor() == Color.White ? 0 : 7; if (destY == enemyLine) { outputSystem.promotePawn(pieceCoords); } } private void checkGameStatus() { final ChessBoard board = game.getBoard(); final Color enemy = Color.getEnemy(game.getPlayerTurn()); if (board.isKingInCheck(enemy)) { if (board.hasAllowedMoves(enemy)) { outputSystem.kingIsInCheck(); } else { outputSystem.kingIsInMat(); outputSystem.winnerIs(game.getPlayerTurn()); } } else if (!board.hasAllowedMoves(enemy)) { outputSystem.patSituation(); } } }