insufficient_material property

bool get insufficient_material

Implementation

bool get insufficient_material {
  final pieces = {};
  final bishops = <int>[];
  var num_pieces = 0;
  var sq_color = 0;

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

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

  /* k vs. k */
  if (num_pieces == 2) {
    return true;
  } /* k vs. kn .... or .... k vs. kb */
  else if (num_pieces == 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) && num_pieces == (pieces[BISHOP] + 2)) {
    var sum = 0;
    var len = bishops.length;
    for (var i = 0; i < len; i++) {
      sum += bishops[i];
    }
    if (sum == 0 || sum == len) {
      return true;
    }
  }

  return false;
}