isInsufficientMaterial method
Checks if the game is in a draw state due to insufficient material.
Implementation
bool isInsufficientMaterial() {
List<ChessPiece> remainingPieces = [];
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
ChessPiece? piece = getPiece(Position(row: row, col: col));
if (piece != null) {
remainingPieces.add(piece);
}
}
}
// Only kings left
if (remainingPieces.length == 2) {
return remainingPieces.every((p) => p.type == PieceType.king);
}
// King and bishop or knight vs king
if (remainingPieces.length == 3) {
bool hasOneMinor =
remainingPieces
.where(
(p) => p.type == PieceType.bishop || p.type == PieceType.knight,
)
.length ==
1;
return hasOneMinor;
}
// King and bishop vs king and bishop (same color bishops)
if (remainingPieces.length == 4) {
List<ChessPiece> bishops =
remainingPieces.where((p) => p.type == PieceType.bishop).toList();
if (bishops.length == 2) {
// Get their positions to compare bishop square colors
List<Position> positions = [];
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
ChessPiece? piece = getPiece(Position(row: row, col: col));
if (piece != null && piece.type == PieceType.bishop) {
positions.add(Position(row: row, col: col));
}
}
}
if (positions.length == 2) {
bool sameColorSquares =
(positions[0].row + positions[0].col) % 2 ==
(positions[1].row + positions[1].col) % 2;
return sameColorSquares;
}
}
}
return false;
}