import java.awt.*; public class King extends ChessPiece { public King (int c, Image p, Component l) { super (c, p, l); } public boolean legalMove (ChessBoard cb, int x, int y) { int dist = moveDistance (x, y); if (dist == 1) { return (legalCapture (cb, x, y) >= 0 && (moveStraight (x, y) || moveDiagonally (x, y))); } else { //can I castle? if (dist != 2 || hasMoved || !moveStraight (x, y) || moveForward (x, y) || legalCapture (cb, x, y) != 0 || moveBlocked (cb, x, y)) { return false; } else { //king can castle and path is clear; now, which side do we //castle on? can the rook move? final int LEFT = 0, RIGHT = 1; int whichSide = x < squareX ? LEFT : RIGHT; ChessPiece atRooks; if (whichSide == LEFT) atRooks = cb.getPieceAt (0, y); else atRooks = cb.getPieceAt (7, y); if (atRooks == null || atRooks.hasMoved) { return false; } else { //The rook is in the correct position and it hasn't moved. //Now determine whether we can really castle, and do it. if (cb.getPieceAt (whichSide == LEFT ? 1 : 6, y) == null) { //castle! cb.placePiece (atRooks, whichSide == LEFT ? x+1 : x-1, y); return true; } else return false; } } } } }