72 lines
1.8 KiB
Java
72 lines
1.8 KiB
Java
package chess.controller.commands;
|
|
|
|
import chess.controller.PlayerCommand;
|
|
import chess.controller.event.GameListener;
|
|
import chess.model.ChessBoard;
|
|
import chess.model.Color;
|
|
import chess.model.Coordinate;
|
|
import chess.model.Game;
|
|
import chess.model.Move;
|
|
|
|
public class CastlingCommand extends PlayerCommand {
|
|
|
|
private Move kingMove;
|
|
private Move rookMove;
|
|
private final boolean bigCastling;
|
|
|
|
public CastlingCommand(boolean bigCastling) {
|
|
this.bigCastling = bigCastling;
|
|
}
|
|
|
|
@Override
|
|
public CommandResult execute(Game game, GameListener outputSystem) {
|
|
final ChessBoard board = game.getBoard();
|
|
|
|
// we must promote the pending pawn before
|
|
if (board.pawnShouldBePromoted())
|
|
return CommandResult.NotAllowed;
|
|
|
|
if (bigCastling && !board.canBigCastle(game.getPlayerTurn()))
|
|
return CommandResult.NotAllowed;
|
|
|
|
if (!bigCastling && !board.canSmallCastle(game.getPlayerTurn()))
|
|
return CommandResult.NotAllowed;
|
|
|
|
int rookBeginX = bigCastling ? 0 : 7;
|
|
int rookEndX = bigCastling ? 3 : 5;
|
|
|
|
int kingBeginX = 4;
|
|
int kingEndX = bigCastling ? 2 : 6;
|
|
|
|
int colorLine = game.getPlayerTurn() == Color.White ? 7 : 0;
|
|
|
|
Coordinate kingCoords = new Coordinate(kingBeginX, colorLine);
|
|
Coordinate rookCoords = new Coordinate(rookBeginX, colorLine);
|
|
|
|
this.kingMove = new Move(kingCoords, new Coordinate(kingEndX, colorLine));
|
|
this.rookMove = new Move(rookCoords, new Coordinate(rookEndX, colorLine));
|
|
|
|
board.applyMove(this.kingMove);
|
|
board.applyMove(this.rookMove);
|
|
|
|
board.setLastMove(this.kingMove);
|
|
|
|
outputSystem.onCastling(this.bigCastling);
|
|
|
|
return CommandResult.Moved;
|
|
}
|
|
|
|
public boolean isBigCastling() {
|
|
return bigCastling;
|
|
}
|
|
|
|
@Override
|
|
protected CommandResult undoImpl(Game game, GameListener outputSystem) {
|
|
game.getBoard().undoMove(this.kingMove, null);
|
|
game.getBoard().undoMove(this.rookMove, null);
|
|
|
|
return CommandResult.Moved;
|
|
}
|
|
|
|
}
|