- added the castling method

This commit is contained in:
willo 2025-05-17 17:53:21 +02:00
parent 1e615f8700
commit 10373c8e92
3 changed files with 56 additions and 4 deletions

View File

@ -173,6 +173,12 @@ public class MovePiece {
return true;
}
}
// Castling move
MovementCapabilities mc = new MovementCapabilities();
if (mc.castling(piece, x, y, board)) {
return true;
}
return false;
}

View File

@ -50,11 +50,57 @@ public class MovementCapabilities {
public boolean castling(Piece king, int x, int y, Board board) {
if (king.getType()!= PieceType.King|| king.getdidMove()) {
return false;
if (king.getType()!= PieceType.King|| king.getDidMove()) {
return false;
}
int currentX = king.getX();
int currentY = king.getY();
boolean isWhite = king.isWhite(); // getting coordinates and color of the king
if (y != currentY) { // checking to see if the king has moved during the game yet
return false;
}
if (x==currentX+2) { // moving the king to the right of the rook AKA "kingside castling"
Piece rook = board.getPiece(7, currentY);
// writing each condition separately instead of in the if loop for more clarity
boolean isRook = rook != null && rook.getType()== PieceType.Rook; // check if rook exists
boolean rookMoved = !rook.getDidMove();
boolean emptySpaceRight = board.getPiece(5, currentY)== null && board.getPiece(6, currentY)== null;
if (isRook && rookMoved) {
if (emptySpaceRight) {
board.movePiece(currentX, currentY, 6, currentY); // moving the king to ...
board.movePiece(7, currentY, 5, currentY); // moving the rook to ...
return true;
}
}
}
if (x==currentX-2) { // moving the king to the left of the rook AKA "queenside castling")
Piece rook = board.getPiece(0, currentY);
boolean isRook = rook != null && rook.getType()== PieceType.Rook;
boolean rookMoved = !rook.getDidMove();
boolean emptySpaceLeft = board.getPiece(3, currentY) == null && board.getPiece(2, currentY) == null && board.getPiece(1, currentY)== null;
if (isRook && rookMoved) {
if (emptySpaceLeft) {
board.movePiece(currentX, currentY, 2, currentY); // moving king to...
board.movePiece(0,currentY,3,currentY); // moving rook to...
return true;
}
}
}
return false;
}
}

View File

@ -39,7 +39,7 @@ public class Piece {
return white;
}
public boolean getdidMove() { // added getter
public boolean getDidMove() { // added getter
return didMove;
}