refactor game

This commit is contained in:
2025-04-03 21:02:04 +02:00
parent 9179b3cda9
commit a81da804f0
4 changed files with 76 additions and 44 deletions

View File

@@ -1,12 +1,7 @@
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 {
@@ -19,59 +14,52 @@ public class CommandExecutor {
}
public CommandResult executeCommand(Command command) {
assert this.game != null : "No input game specified !";
assert this.outputSystem != null : "No output system specified !";
CommandResult result = command.execute(this.game, this.outputSystem);
if (result == CommandResult.Moved) {
checkPromotion(((MoveCommand) command).getMove().getFinish());
checkGameStatus();
alternatePlayers();
this.game.checkPromotion(((MoveCommand) command).getMove().getFinish());
this.game.checkGameStatus();
this.game.switchPlayerTurn();
}
return result;
}
private void alternatePlayers() {
this.game.switchPlayerTurn();
this.outputSystem.playerTurn(this.game.getPlayerTurn());
}
public void setOutputSystem(OutputSystem outputSystem) {
unbindListeners();
this.outputSystem = outputSystem;
bindListeners();
}
public void setGame(Game game) {
unbindListeners();
this.game = game;
bindListeners();
}
private void checkPromotion(Coordinate pieceCoords) {
Piece piece = this.game.getBoard().pieceAt(pieceCoords);
if (piece == null || !(piece instanceof Pawn))
private void unbindListeners() {
if (this.game == null || this.outputSystem == null)
return;
int destY = pieceCoords.getY();
int enemyLine = piece.getColor() == Color.White ? 0 : 7;
if (destY == enemyLine) {
outputSystem.promotePawn(pieceCoords);
}
this.game.OnCheck.disconnect(outputSystem::kingIsInCheck);
this.game.OnMat.disconnect(outputSystem::kingIsInMat);
this.game.OnPat.disconnect(outputSystem::patSituation);
this.game.OnPromote.disconnect(outputSystem::promotePawn);
this.game.OnWin.disconnect(outputSystem::winnerIs);
this.game.OnPlayerTurn.disconnect(outputSystem::playerTurn);
}
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();
}
private void bindListeners() {
if (this.game == null || this.outputSystem == null)
return;
this.game.OnCheck.connect(outputSystem::kingIsInCheck);
this.game.OnMat.connect(outputSystem::kingIsInMat);
this.game.OnPat.connect(outputSystem::patSituation);
this.game.OnPromote.connect(outputSystem::promotePawn);
this.game.OnWin.connect(outputSystem::winnerIs);
this.game.OnPlayerTurn.connect(outputSystem::playerTurn);
}
}