insufficientMaterial property Null safety

bool insufficientMaterial

Implementation

bool get insufficientMaterial {
  Map pieces = {};
  List<int> bishops = [];
  int numPieces = 0;
  int sqColor = 0;

  for (int i = SQUARES_A8; i <= SQUARES_H1; i++) {
    sqColor = (sqColor + 1) % 2;
    if ((i & 0x88) != 0) {
      i += 7;
      continue;
    }

    Piece? piece = board[i];
    if (piece != null) {
      pieces[piece.type] =
          (pieces.containsKey(piece.type)) ? pieces[piece.type] + 1 : 1;
      if (piece.type == BISHOP) {
        bishops.add(sqColor);
      }
      numPieces++;
    }
  }

  /* k vs. k */
  if (numPieces == 2) {
    return true;
  } /* k vs. kn .... or .... k vs. kb */
  else if (numPieces == 3 && (pieces[BISHOP] == 1 || pieces[KNIGHT] == 1)) {
    return true;
  } /* kb vs. kb where any number of bishops are all on the same color */
  else if (pieces.containsKey(BISHOP) && numPieces == (pieces[BISHOP] + 2)) {
    int sum = 0;
    int len = bishops.length;
    for (int i = 0; i < len; i++) {
      sum += bishops[i];
    }
    if (sum == 0 || sum == len) {
      return true;
    }
  }

  return false;
}