Chess Game
Ye problem POLYMORPHISM test karne ke liye hai. Ek abstract Piece class ho jisme abstract method canMove(Board, from, to) ho, aur King, Queen, Rook, Bishop, Knight, Pawn use implement karein. Board ke andar "if piece is Knight then..." likhna sabse badi galti hai.
Special moves zaroor mention karo — castling, en passant, aur pawn promotion. Inhe base canMove() mein thoosne ke bajaye alag MoveValidator chain rakhna saaf rehta hai. Check/checkmate detection ke liye batao: move lagao, "kya mera king attack mein hai?" check karo, phir undo kar do.
abstract class Piece {
protected final Color color;
abstract boolean canMove(Board board, Cell from, Cell to);
}
class Knight extends Piece {
public boolean canMove(Board b, Cell from, Cell to) {
int dx = Math.abs(from.x - to.x), dy = Math.abs(from.y - to.y);
return dx * dy == 2 // L shape
&& (to.getPiece() == null || to.getPiece().color != color);
}
}
// Board ko kabhi pata nahi chalta ki piece Knight hai ya Bishop- Abstract Piece + har piece ka apna canMove — Board mein instanceof kabhi nahi
- Castling, en passant, promotion alag validator chain mein rakho
- Check detection: simulate → validate → undo
Rook, Bishop aur Queen SEEDHI LINE mein chalte hain — inke liye sirf destination valid hona kaafi nahi, raste mein koi piece nahi hona chahiye. Knight EKMATRA piece hai jo kood sakta hai.
Isliye ek common helper isPathClear(from, to) banao jo direction nikaal kar beech ke cells check kare. Ise base Piece class mein rakho taaki teeno pieces reuse karein.
protected boolean isPathClear(Board b, Cell from, Cell to) {
int dx = Integer.signum(to.x - from.x);
int dy = Integer.signum(to.y - from.y);
int x = from.x + dx, y = from.y + dy;
while (x != to.x || y != to.y) {
if (b.cellAt(x, y).getPiece() != null) return false;
x += dx; y += dy;
}
return true;
}CHECK: king abhi attack mein hai. CHECKMATE: king attack mein hai aur koi bhi legal move usse bacha nahi sakta. STALEMATE: king attack mein NAHI hai par koi legal move hai hi nahi — ye DRAW hai, haar nahi.
Detection ka tareeka dono ke liye same hai: saare possible moves generate karo, har ek ko simulate karo, aur dekho ki kya koi move king ko safe kar deta hai. Simulate ke baad UNDO karna mat bhoolo.