Detect stalemate in KXK endgames
authorGary Linscott <glinscott@gmail.com>
Sun, 5 Feb 2012 15:24:53 +0000 (10:24 -0500)
committerGary Linscott <glinscott@gmail.com>
Sun, 5 Feb 2012 15:24:53 +0000 (10:24 -0500)
Also, handle cases where there are 2 bishops of the same color.

src/endgame.cpp
src/position.h

index d458cd66d78df9c4a46281a3201d5505a3f92fc8..d7cb2b3c8c58541a54d0e662aff2d25110a1e07f 100644 (file)
@@ -82,6 +82,21 @@ namespace {
   template<typename M>
   void delete_endgame(const typename M::value_type& p) { delete p.second; }
 
+  // Fast stalemate detection with lone king
+  bool is_kxk_stalemate(const Position &pos, const Color c) {
+    if ( pos.side_to_move() == c &&
+        !pos.in_check()) {
+      const Square from = pos.king_square(c);
+      Bitboard b = pos.attacks_from<KING>(from);
+      while (b) {
+        // Assume there are no pinned pieces, as it is a lone king
+        if (pos.pl_move_is_legal(make_move(from, pop_1st_bit(&b)), 0))
+          return false;
+      }
+      return true;
+    }
+    return false;
+  }
 } // namespace
 
 
@@ -132,6 +147,10 @@ Value Endgame<KXK>::operator()(const Position& pos) const {
   assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
   assert(pos.piece_count(weakerSide, PAWN) == VALUE_ZERO);
 
+  if (is_kxk_stalemate(pos, weakerSide)) {
+    return VALUE_DRAW;
+  }
+  
   Square winnerKSq = pos.king_square(strongerSide);
   Square loserKSq = pos.king_square(weakerSide);
 
@@ -142,9 +161,9 @@ Value Endgame<KXK>::operator()(const Position& pos) const {
 
   if (   pos.piece_count(strongerSide, QUEEN)
       || pos.piece_count(strongerSide, ROOK)
-      || pos.piece_count(strongerSide, BISHOP) > 1)
-      // TODO: check for two equal-colored bishops!
-      result += VALUE_KNOWN_WIN;
+      || pos.both_color_bishops(strongerSide)) {
+    result += VALUE_KNOWN_WIN;
+  }
 
   return strongerSide == pos.side_to_move() ? result : -result;
 }
index bcbfc850d0c8b15eb4677f63b447996fde6fdeca..8229e71b4a1a4e8c3c66f7cdcd12cbaa580635b2 100644 (file)
@@ -189,6 +189,7 @@ public:
   template<bool SkipRepetition> bool is_draw() const;
   int startpos_ply_counter() const;
   bool opposite_colored_bishops() const;
+  bool both_color_bishops(Color c) const;
   bool has_pawn_on_7th(Color c) const;
   bool is_chess960() const;
 
@@ -432,6 +433,12 @@ inline bool Position::opposite_colored_bishops() const {
         && opposite_colors(pieceList[WHITE][BISHOP][0], pieceList[BLACK][BISHOP][0]);
 }
 
+inline bool Position::both_color_bishops(Color c) const {
+  // Assumes that there are only two bishops
+  return  pieceCount[c][BISHOP] >= 2 &&
+          opposite_colors(pieceList[c][BISHOP][0], pieceList[c][BISHOP][1]);
+}
+
 inline bool Position::has_pawn_on_7th(Color c) const {
   return pieces(PAWN, c) & rank_bb(relative_rank(c, RANK_7));
 }