hasInsufficientMaterial method

  1. @override
bool hasInsufficientMaterial(
  1. Side side
)
override

Tests if a Side has insufficient winning material.

Implementation

@override
bool hasInsufficientMaterial(Side side) {
  // Remaining material does not matter if the enemy king is already
  // exploded.
  if (board.piecesOf(side.opposite, Role.king).isEmpty) return false;

  // Bare king cannot mate.
  if (board.bySide(side).diff(board.kings).isEmpty) return true;

  // As long as the enemy king is not alone, there is always a chance their
  // own pieces explode next to it.
  if (board.bySide(side.opposite).diff(board.kings).isNotEmpty) {
    // Unless there are only bishops that cannot explode each other.
    if (board.occupied == board.bishops | board.kings) {
      if (!(board.bishops & board.white)
          .isIntersected(SquareSet.darkSquares)) {
        return !(board.bishops & board.black)
            .isIntersected(SquareSet.lightSquares);
      }
      if (!(board.bishops & board.white)
          .isIntersected(SquareSet.lightSquares)) {
        return !(board.bishops & board.black)
            .isIntersected(SquareSet.darkSquares);
      }
    }
    return false;
  }

  // Queen or pawn (future queen) can give mate against bare king.
  if (board.queens.isNotEmpty || board.pawns.isNotEmpty) return false;

  // Single knight, bishop or rook cannot mate against bare king.
  if ((board.knights | board.bishops | board.rooks).size == 1) {
    return true;
  }

  // If only knights, more than two are required to mate bare king.
  if (board.occupied == board.knights | board.kings) {
    return board.knights.size <= 2;
  }

  return false;
}