]> git.sesse.net Git - stockfish/blob - src/endgame.cpp
c55013f3ac141f531c3bee0192a63ee4da85eb17
[stockfish] / src / endgame.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <cassert>
21
22 #include "bitcount.h"
23 #include "endgame.h"
24 #include "pawns.h"
25
26 using std::string;
27
28 extern uint32_t probe_kpk_bitbase(Square wksq, Square wpsq, Square bksq, Color stm);
29
30 namespace {
31
32   // Table used to drive the defending king towards the edge of the board
33   // in KX vs K and KQ vs KR endgames.
34   const int MateTable[64] = {
35     100, 90, 80, 70, 70, 80, 90, 100,
36      90, 70, 60, 50, 50, 60, 70,  90,
37      80, 60, 40, 30, 30, 40, 60,  80,
38      70, 50, 30, 20, 20, 30, 50,  70,
39      70, 50, 30, 20, 20, 30, 50,  70,
40      80, 60, 40, 30, 30, 40, 60,  80,
41      90, 70, 60, 50, 50, 60, 70,  90,
42     100, 90, 80, 70, 70, 80, 90, 100,
43   };
44
45   // Table used to drive the defending king towards a corner square of the
46   // right color in KBN vs K endgames.
47   const int KBNKMateTable[64] = {
48     200, 190, 180, 170, 160, 150, 140, 130,
49     190, 180, 170, 160, 150, 140, 130, 140,
50     180, 170, 155, 140, 140, 125, 140, 150,
51     170, 160, 140, 120, 110, 140, 150, 160,
52     160, 150, 140, 110, 120, 140, 160, 170,
53     150, 140, 125, 140, 140, 155, 170, 180,
54     140, 130, 140, 150, 160, 170, 180, 190,
55     130, 140, 150, 160, 170, 180, 190, 200
56   };
57
58   // The attacking side is given a descending bonus based on distance between
59   // the two kings in basic endgames.
60   const int DistanceBonus[8] = { 0, 0, 100, 80, 60, 40, 20, 10 };
61
62   // Penalty for big distance between king and knight for the defending king
63   // and knight in KR vs KN endgames.
64   const int KRKNKingKnightDistancePenalty[8] = { 0, 0, 4, 10, 20, 32, 48, 70 };
65
66   // Build corresponding key code for the opposite color: "KBPKN" -> "KNKBP"
67   const string swap_colors(const string& keyCode) {
68
69     size_t idx = keyCode.find('K', 1);
70     return keyCode.substr(idx) + keyCode.substr(0, idx);
71   }
72
73   // Get the material key of a position out of the given endgame key code
74   // like "KBPKN". The trick here is to first build up a FEN string and then
75   // let a Position object to do the work for us. Note that the FEN string
76   // could correspond to an illegal position.
77   Key mat_key(const string& keyCode) {
78
79     assert(keyCode.length() > 0 && keyCode.length() < 8);
80     assert(keyCode[0] == 'K');
81
82     string fen;
83     size_t i = 0;
84
85     // First add white and then black pieces
86     do fen += keyCode[i];                while (keyCode[++i] != 'K');
87     do fen += char(tolower(keyCode[i])); while (++i < keyCode.length());
88
89     // Add file padding and remaining empty ranks
90     fen += string(1, '0' + int(8 - keyCode.length())) + "/8/8/8/8/8/8/8 w - - 0 10";
91
92     // Build a Position out of the fen string and get its material key
93     return Position(fen, false, 0).get_material_key();
94   }
95
96   typedef EndgameBase<Value> EF;
97   typedef EndgameBase<ScaleFactor> SF;
98
99 } // namespace
100
101
102 /// Endgames member definitions
103
104 template<> const Endgames::EFMap& Endgames::map<EF>() const { return maps.first; }
105 template<> const Endgames::SFMap& Endgames::map<SF>() const { return maps.second; }
106
107 Endgames::Endgames() {
108
109   add<Value, KPK>("KPK");
110   add<Value, KNNK>("KNNK");
111   add<Value, KBNK>("KBNK");
112   add<Value, KRKP>("KRKP");
113   add<Value, KRKB>("KRKB");
114   add<Value, KRKN>("KRKN");
115   add<Value, KQKR>("KQKR");
116   add<Value, KBBKN>("KBBKN");
117
118   add<ScaleFactor, KNPK>("KNPK");
119   add<ScaleFactor, KRPKR>("KRPKR");
120   add<ScaleFactor, KBPKB>("KBPKB");
121   add<ScaleFactor, KBPKN>("KBPKN");
122   add<ScaleFactor, KBPPKB>("KBPPKB");
123   add<ScaleFactor, KRPPKRP>("KRPPKRP");
124 }
125
126 Endgames::~Endgames() {
127
128   for (EFMap::const_iterator it = map<EF>().begin(); it != map<EF>().end(); ++it)
129       delete it->second;
130
131   for (SFMap::const_iterator it = map<SF>().begin(); it != map<SF>().end(); ++it)
132       delete it->second;
133 }
134
135 template<typename T, EndgameType E>
136 void Endgames::add(const string& keyCode) {
137
138   typedef Endgame<T, E> EG;
139   typedef typename EG::Base B;
140   typedef std::map<Key, B*> M;
141
142   const_cast<M&>(map<B>()).insert(std::pair<Key, B*>(mat_key(keyCode), new EG(WHITE)));
143   const_cast<M&>(map<B>()).insert(std::pair<Key, B*>(mat_key(swap_colors(keyCode)), new EG(BLACK)));
144 }
145
146 template<typename T>
147 EndgameBase<T>* Endgames::get(Key key) const {
148
149   typedef EndgameBase<T> E;
150   typename std::map<Key, E*>::const_iterator it = map<E>().find(key);
151   return it != map<E>().end() ? it->second : NULL;
152 }
153
154 // Explicit template instantiations
155 template EF* Endgames::get<Value>(Key key) const;
156 template SF* Endgames::get<ScaleFactor>(Key key) const;
157
158
159 /// Mate with KX vs K. This function is used to evaluate positions with
160 /// King and plenty of material vs a lone king. It simply gives the
161 /// attacking side a bonus for driving the defending king towards the edge
162 /// of the board, and for keeping the distance between the two kings small.
163 template<>
164 Value Endgame<Value, KXK>::apply(const Position& pos) const {
165
166   assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
167   assert(pos.piece_count(weakerSide, PAWN) == VALUE_ZERO);
168
169   Square winnerKSq = pos.king_square(strongerSide);
170   Square loserKSq = pos.king_square(weakerSide);
171
172   Value result =   pos.non_pawn_material(strongerSide)
173                  + pos.piece_count(strongerSide, PAWN) * PawnValueEndgame
174                  + MateTable[loserKSq]
175                  + DistanceBonus[square_distance(winnerKSq, loserKSq)];
176
177   if (   pos.piece_count(strongerSide, QUEEN)
178       || pos.piece_count(strongerSide, ROOK)
179       || pos.piece_count(strongerSide, BISHOP) > 1)
180       // TODO: check for two equal-colored bishops!
181       result += VALUE_KNOWN_WIN;
182
183   return strongerSide == pos.side_to_move() ? result : -result;
184 }
185
186
187 /// Mate with KBN vs K. This is similar to KX vs K, but we have to drive the
188 /// defending king towards a corner square of the right color.
189 template<>
190 Value Endgame<Value, KBNK>::apply(const Position& pos) const {
191
192   assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
193   assert(pos.piece_count(weakerSide, PAWN) == VALUE_ZERO);
194   assert(pos.non_pawn_material(strongerSide) == KnightValueMidgame + BishopValueMidgame);
195   assert(pos.piece_count(strongerSide, BISHOP) == 1);
196   assert(pos.piece_count(strongerSide, KNIGHT) == 1);
197   assert(pos.piece_count(strongerSide, PAWN) == 0);
198
199   Square winnerKSq = pos.king_square(strongerSide);
200   Square loserKSq = pos.king_square(weakerSide);
201   Square bishopSquare = pos.piece_list(strongerSide, BISHOP)[0];
202
203   // kbnk_mate_table() tries to drive toward corners A1 or H8,
204   // if we have a bishop that cannot reach the above squares we
205   // mirror the kings so to drive enemy toward corners A8 or H1.
206   if (opposite_color_squares(bishopSquare, SQ_A1))
207   {
208       winnerKSq = flop_square(winnerKSq);
209       loserKSq = flop_square(loserKSq);
210   }
211
212   Value result =  VALUE_KNOWN_WIN
213                 + DistanceBonus[square_distance(winnerKSq, loserKSq)]
214                 + KBNKMateTable[loserKSq];
215
216   return strongerSide == pos.side_to_move() ? result : -result;
217 }
218
219
220 /// KP vs K. This endgame is evaluated with the help of a bitbase.
221 template<>
222 Value Endgame<Value, KPK>::apply(const Position& pos) const {
223
224   assert(pos.non_pawn_material(strongerSide) == VALUE_ZERO);
225   assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
226   assert(pos.piece_count(strongerSide, PAWN) == 1);
227   assert(pos.piece_count(weakerSide, PAWN) == 0);
228
229   Square wksq, bksq, wpsq;
230   Color stm;
231
232   if (strongerSide == WHITE)
233   {
234       wksq = pos.king_square(WHITE);
235       bksq = pos.king_square(BLACK);
236       wpsq = pos.piece_list(WHITE, PAWN)[0];
237       stm = pos.side_to_move();
238   }
239   else
240   {
241       wksq = flip_square(pos.king_square(BLACK));
242       bksq = flip_square(pos.king_square(WHITE));
243       wpsq = flip_square(pos.piece_list(BLACK, PAWN)[0]);
244       stm = opposite_color(pos.side_to_move());
245   }
246
247   if (square_file(wpsq) >= FILE_E)
248   {
249       wksq = flop_square(wksq);
250       bksq = flop_square(bksq);
251       wpsq = flop_square(wpsq);
252   }
253
254   if (!probe_kpk_bitbase(wksq, wpsq, bksq, stm))
255       return VALUE_DRAW;
256
257   Value result =  VALUE_KNOWN_WIN
258                 + PawnValueEndgame
259                 + Value(square_rank(wpsq));
260
261   return strongerSide == pos.side_to_move() ? result : -result;
262 }
263
264
265 /// KR vs KP. This is a somewhat tricky endgame to evaluate precisely without
266 /// a bitbase. The function below returns drawish scores when the pawn is
267 /// far advanced with support of the king, while the attacking king is far
268 /// away.
269 template<>
270 Value Endgame<Value, KRKP>::apply(const Position& pos) const {
271
272   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
273   assert(pos.piece_count(strongerSide, PAWN) == 0);
274   assert(pos.non_pawn_material(weakerSide) == 0);
275   assert(pos.piece_count(weakerSide, PAWN) == 1);
276
277   Square wksq, wrsq, bksq, bpsq;
278   int tempo = (pos.side_to_move() == strongerSide);
279
280   wksq = pos.king_square(strongerSide);
281   wrsq = pos.piece_list(strongerSide, ROOK)[0];
282   bksq = pos.king_square(weakerSide);
283   bpsq = pos.piece_list(weakerSide, PAWN)[0];
284
285   if (strongerSide == BLACK)
286   {
287       wksq = flip_square(wksq);
288       wrsq = flip_square(wrsq);
289       bksq = flip_square(bksq);
290       bpsq = flip_square(bpsq);
291   }
292
293   Square queeningSq = make_square(square_file(bpsq), RANK_1);
294   Value result;
295
296   // If the stronger side's king is in front of the pawn, it's a win
297   if (wksq < bpsq && square_file(wksq) == square_file(bpsq))
298       result = RookValueEndgame - Value(square_distance(wksq, bpsq));
299
300   // If the weaker side's king is too far from the pawn and the rook,
301   // it's a win
302   else if (   square_distance(bksq, bpsq) - (tempo ^ 1) >= 3
303            && square_distance(bksq, wrsq) >= 3)
304       result = RookValueEndgame - Value(square_distance(wksq, bpsq));
305
306   // If the pawn is far advanced and supported by the defending king,
307   // the position is drawish
308   else if (   square_rank(bksq) <= RANK_3
309            && square_distance(bksq, bpsq) == 1
310            && square_rank(wksq) >= RANK_4
311            && square_distance(wksq, bpsq) - tempo > 2)
312       result = Value(80 - square_distance(wksq, bpsq) * 8);
313
314   else
315       result =  Value(200)
316               - Value(square_distance(wksq, bpsq + DELTA_S) * 8)
317               + Value(square_distance(bksq, bpsq + DELTA_S) * 8)
318               + Value(square_distance(bpsq, queeningSq) * 8);
319
320   return strongerSide == pos.side_to_move() ? result : -result;
321 }
322
323
324 /// KR vs KB. This is very simple, and always returns drawish scores.  The
325 /// score is slightly bigger when the defending king is close to the edge.
326 template<>
327 Value Endgame<Value, KRKB>::apply(const Position& pos) const {
328
329   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
330   assert(pos.piece_count(strongerSide, PAWN) == 0);
331   assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
332   assert(pos.piece_count(weakerSide, PAWN) == 0);
333   assert(pos.piece_count(weakerSide, BISHOP) == 1);
334
335   Value result = Value(MateTable[pos.king_square(weakerSide)]);
336   return strongerSide == pos.side_to_move() ? result : -result;
337 }
338
339
340 /// KR vs KN.  The attacking side has slightly better winning chances than
341 /// in KR vs KB, particularly if the king and the knight are far apart.
342 template<>
343 Value Endgame<Value, KRKN>::apply(const Position& pos) const {
344
345   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
346   assert(pos.piece_count(strongerSide, PAWN) == 0);
347   assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
348   assert(pos.piece_count(weakerSide, PAWN) == 0);
349   assert(pos.piece_count(weakerSide, KNIGHT) == 1);
350
351   Square defendingKSq = pos.king_square(weakerSide);
352   Square nSq = pos.piece_list(weakerSide, KNIGHT)[0];
353
354   int d = square_distance(defendingKSq, nSq);
355   Value result =   Value(10)
356                  + MateTable[defendingKSq]
357                  + KRKNKingKnightDistancePenalty[d];
358
359   return strongerSide == pos.side_to_move() ? result : -result;
360 }
361
362
363 /// KQ vs KR.  This is almost identical to KX vs K:  We give the attacking
364 /// king a bonus for having the kings close together, and for forcing the
365 /// defending king towards the edge.  If we also take care to avoid null move
366 /// for the defending side in the search, this is usually sufficient to be
367 /// able to win KQ vs KR.
368 template<>
369 Value Endgame<Value, KQKR>::apply(const Position& pos) const {
370
371   assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
372   assert(pos.piece_count(strongerSide, PAWN) == 0);
373   assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
374   assert(pos.piece_count(weakerSide, PAWN) == 0);
375
376   Square winnerKSq = pos.king_square(strongerSide);
377   Square loserKSq = pos.king_square(weakerSide);
378
379   Value result =  QueenValueEndgame
380                 - RookValueEndgame
381                 + MateTable[loserKSq]
382                 + DistanceBonus[square_distance(winnerKSq, loserKSq)];
383
384   return strongerSide == pos.side_to_move() ? result : -result;
385 }
386
387 template<>
388 Value Endgame<Value, KBBKN>::apply(const Position& pos) const {
389
390   assert(pos.piece_count(strongerSide, BISHOP) == 2);
391   assert(pos.non_pawn_material(strongerSide) == 2*BishopValueMidgame);
392   assert(pos.piece_count(weakerSide, KNIGHT) == 1);
393   assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
394   assert(pos.pieces(PAWN) == EmptyBoardBB);
395
396   Value result = BishopValueEndgame;
397   Square wksq = pos.king_square(strongerSide);
398   Square bksq = pos.king_square(weakerSide);
399   Square nsq = pos.piece_list(weakerSide, KNIGHT)[0];
400
401   // Bonus for attacking king close to defending king
402   result += Value(DistanceBonus[square_distance(wksq, bksq)]);
403
404   // Bonus for driving the defending king and knight apart
405   result += Value(square_distance(bksq, nsq) * 32);
406
407   // Bonus for restricting the knight's mobility
408   result += Value((8 - count_1s<CNT32_MAX15>(pos.attacks_from<KNIGHT>(nsq))) * 8);
409
410   return strongerSide == pos.side_to_move() ? result : -result;
411 }
412
413
414 /// K and two minors vs K and one or two minors or K and two knights against
415 /// king alone are always draw.
416 template<>
417 Value Endgame<Value, KmmKm>::apply(const Position&) const {
418   return VALUE_DRAW;
419 }
420
421 template<>
422 Value Endgame<Value, KNNK>::apply(const Position&) const {
423   return VALUE_DRAW;
424 }
425
426 /// KBPKScalingFunction scales endgames where the stronger side has king,
427 /// bishop and one or more pawns. It checks for draws with rook pawns and a
428 /// bishop of the wrong color. If such a draw is detected, SCALE_FACTOR_ZERO is
429 /// returned. If not, the return value is SCALE_FACTOR_NONE, i.e. no scaling
430 /// will be used.
431 template<>
432 ScaleFactor Endgame<ScaleFactor, KBPsK>::apply(const Position& pos) const {
433
434   assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
435   assert(pos.piece_count(strongerSide, BISHOP) == 1);
436   assert(pos.piece_count(strongerSide, PAWN) >= 1);
437
438   // No assertions about the material of weakerSide, because we want draws to
439   // be detected even when the weaker side has some pawns.
440
441   Bitboard pawns = pos.pieces(PAWN, strongerSide);
442   File pawnFile = square_file(pos.piece_list(strongerSide, PAWN)[0]);
443
444   // All pawns are on a single rook file ?
445   if (   (pawnFile == FILE_A || pawnFile == FILE_H)
446       && (pawns & ~file_bb(pawnFile)) == EmptyBoardBB)
447   {
448       Square bishopSq = pos.piece_list(strongerSide, BISHOP)[0];
449       Square queeningSq = relative_square(strongerSide, make_square(pawnFile, RANK_8));
450       Square kingSq = pos.king_square(weakerSide);
451
452       if (   opposite_color_squares(queeningSq, bishopSq)
453           && abs(square_file(kingSq) - pawnFile) <= 1)
454       {
455           // The bishop has the wrong color, and the defending king is on the
456           // file of the pawn(s) or the neighboring file. Find the rank of the
457           // frontmost pawn.
458           Rank rank;
459           if (strongerSide == WHITE)
460           {
461               for (rank = RANK_7; (rank_bb(rank) & pawns) == EmptyBoardBB; rank--) {}
462               assert(rank >= RANK_2 && rank <= RANK_7);
463           }
464           else
465           {
466               for (rank = RANK_2; (rank_bb(rank) & pawns) == EmptyBoardBB; rank++) {}
467               rank = Rank(rank ^ 7);  // HACK to get the relative rank
468               assert(rank >= RANK_2 && rank <= RANK_7);
469           }
470           // If the defending king has distance 1 to the promotion square or
471           // is placed somewhere in front of the pawn, it's a draw.
472           if (   square_distance(kingSq, queeningSq) <= 1
473               || relative_rank(strongerSide, kingSq) >= rank)
474               return SCALE_FACTOR_ZERO;
475       }
476   }
477   return SCALE_FACTOR_NONE;
478 }
479
480
481 /// KQKRPScalingFunction scales endgames where the stronger side has only
482 /// king and queen, while the weaker side has at least a rook and a pawn.
483 /// It tests for fortress draws with a rook on the third rank defended by
484 /// a pawn.
485 template<>
486 ScaleFactor Endgame<ScaleFactor, KQKRPs>::apply(const Position& pos) const {
487
488   assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
489   assert(pos.piece_count(strongerSide, QUEEN) == 1);
490   assert(pos.piece_count(strongerSide, PAWN) == 0);
491   assert(pos.piece_count(weakerSide, ROOK) == 1);
492   assert(pos.piece_count(weakerSide, PAWN) >= 1);
493
494   Square kingSq = pos.king_square(weakerSide);
495   if (   relative_rank(weakerSide, kingSq) <= RANK_2
496       && relative_rank(weakerSide, pos.king_square(strongerSide)) >= RANK_4
497       && (pos.pieces(ROOK, weakerSide) & rank_bb(relative_rank(weakerSide, RANK_3)))
498       && (pos.pieces(PAWN, weakerSide) & rank_bb(relative_rank(weakerSide, RANK_2)))
499       && (pos.attacks_from<KING>(kingSq) & pos.pieces(PAWN, weakerSide)))
500   {
501       Square rsq = pos.piece_list(weakerSide, ROOK)[0];
502       if (pos.attacks_from<PAWN>(rsq, strongerSide) & pos.pieces(PAWN, weakerSide))
503           return SCALE_FACTOR_ZERO;
504   }
505   return SCALE_FACTOR_NONE;
506 }
507
508
509 /// KRPKRScalingFunction scales KRP vs KR endgames. This function knows a
510 /// handful of the most important classes of drawn positions, but is far
511 /// from perfect. It would probably be a good idea to add more knowledge
512 /// in the future.
513 ///
514 /// It would also be nice to rewrite the actual code for this function,
515 /// which is mostly copied from Glaurung 1.x, and not very pretty.
516 template<>
517 ScaleFactor Endgame<ScaleFactor, KRPKR>::apply(const Position& pos) const {
518
519   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
520   assert(pos.piece_count(strongerSide, PAWN) == 1);
521   assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
522   assert(pos.piece_count(weakerSide, PAWN) == 0);
523
524   Square wksq = pos.king_square(strongerSide);
525   Square wrsq = pos.piece_list(strongerSide, ROOK)[0];
526   Square wpsq = pos.piece_list(strongerSide, PAWN)[0];
527   Square bksq = pos.king_square(weakerSide);
528   Square brsq = pos.piece_list(weakerSide, ROOK)[0];
529
530   // Orient the board in such a way that the stronger side is white, and the
531   // pawn is on the left half of the board.
532   if (strongerSide == BLACK)
533   {
534       wksq = flip_square(wksq);
535       wrsq = flip_square(wrsq);
536       wpsq = flip_square(wpsq);
537       bksq = flip_square(bksq);
538       brsq = flip_square(brsq);
539   }
540   if (square_file(wpsq) > FILE_D)
541   {
542       wksq = flop_square(wksq);
543       wrsq = flop_square(wrsq);
544       wpsq = flop_square(wpsq);
545       bksq = flop_square(bksq);
546       brsq = flop_square(brsq);
547   }
548
549   File f = square_file(wpsq);
550   Rank r = square_rank(wpsq);
551   Square queeningSq = make_square(f, RANK_8);
552   int tempo = (pos.side_to_move() == strongerSide);
553
554   // If the pawn is not too far advanced and the defending king defends the
555   // queening square, use the third-rank defence.
556   if (   r <= RANK_5
557       && square_distance(bksq, queeningSq) <= 1
558       && wksq <= SQ_H5
559       && (square_rank(brsq) == RANK_6 || (r <= RANK_3 && square_rank(wrsq) != RANK_6)))
560       return SCALE_FACTOR_ZERO;
561
562   // The defending side saves a draw by checking from behind in case the pawn
563   // has advanced to the 6th rank with the king behind.
564   if (   r == RANK_6
565       && square_distance(bksq, queeningSq) <= 1
566       && square_rank(wksq) + tempo <= RANK_6
567       && (square_rank(brsq) == RANK_1 || (!tempo && abs(square_file(brsq) - f) >= 3)))
568       return SCALE_FACTOR_ZERO;
569
570   if (   r >= RANK_6
571       && bksq == queeningSq
572       && square_rank(brsq) == RANK_1
573       && (!tempo || square_distance(wksq, wpsq) >= 2))
574       return SCALE_FACTOR_ZERO;
575
576   // White pawn on a7 and rook on a8 is a draw if black's king is on g7 or h7
577   // and the black rook is behind the pawn.
578   if (   wpsq == SQ_A7
579       && wrsq == SQ_A8
580       && (bksq == SQ_H7 || bksq == SQ_G7)
581       && square_file(brsq) == FILE_A
582       && (square_rank(brsq) <= RANK_3 || square_file(wksq) >= FILE_D || square_rank(wksq) <= RANK_5))
583       return SCALE_FACTOR_ZERO;
584
585   // If the defending king blocks the pawn and the attacking king is too far
586   // away, it's a draw.
587   if (   r <= RANK_5
588       && bksq == wpsq + DELTA_N
589       && square_distance(wksq, wpsq) - tempo >= 2
590       && square_distance(wksq, brsq) - tempo >= 2)
591       return SCALE_FACTOR_ZERO;
592
593   // Pawn on the 7th rank supported by the rook from behind usually wins if the
594   // attacking king is closer to the queening square than the defending king,
595   // and the defending king cannot gain tempi by threatening the attacking rook.
596   if (   r == RANK_7
597       && f != FILE_A
598       && square_file(wrsq) == f
599       && wrsq != queeningSq
600       && (square_distance(wksq, queeningSq) < square_distance(bksq, queeningSq) - 2 + tempo)
601       && (square_distance(wksq, queeningSq) < square_distance(bksq, wrsq) + tempo))
602       return ScaleFactor(SCALE_FACTOR_MAX - 2 * square_distance(wksq, queeningSq));
603
604   // Similar to the above, but with the pawn further back
605   if (   f != FILE_A
606       && square_file(wrsq) == f
607       && wrsq < wpsq
608       && (square_distance(wksq, queeningSq) < square_distance(bksq, queeningSq) - 2 + tempo)
609       && (square_distance(wksq, wpsq + DELTA_N) < square_distance(bksq, wpsq + DELTA_N) - 2 + tempo)
610       && (  square_distance(bksq, wrsq) + tempo >= 3
611           || (    square_distance(wksq, queeningSq) < square_distance(bksq, wrsq) + tempo
612               && (square_distance(wksq, wpsq + DELTA_N) < square_distance(bksq, wrsq) + tempo))))
613       return ScaleFactor(  SCALE_FACTOR_MAX
614                          - 8 * square_distance(wpsq, queeningSq)
615                          - 2 * square_distance(wksq, queeningSq));
616
617   // If the pawn is not far advanced, and the defending king is somewhere in
618   // the pawn's path, it's probably a draw.
619   if (r <= RANK_4 && bksq > wpsq)
620   {
621       if (square_file(bksq) == square_file(wpsq))
622           return ScaleFactor(10);
623       if (   abs(square_file(bksq) - square_file(wpsq)) == 1
624           && square_distance(wksq, bksq) > 2)
625           return ScaleFactor(24 - 2 * square_distance(wksq, bksq));
626   }
627   return SCALE_FACTOR_NONE;
628 }
629
630
631 /// KRPPKRPScalingFunction scales KRPP vs KRP endgames. There is only a
632 /// single pattern: If the stronger side has no pawns and the defending king
633 /// is actively placed, the position is drawish.
634 template<>
635 ScaleFactor Endgame<ScaleFactor, KRPPKRP>::apply(const Position& pos) const {
636
637   assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
638   assert(pos.piece_count(strongerSide, PAWN) == 2);
639   assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
640   assert(pos.piece_count(weakerSide, PAWN) == 1);
641
642   Square wpsq1 = pos.piece_list(strongerSide, PAWN)[0];
643   Square wpsq2 = pos.piece_list(strongerSide, PAWN)[1];
644   Square bksq = pos.king_square(weakerSide);
645
646   // Does the stronger side have a passed pawn?
647   if (   pos.pawn_is_passed(strongerSide, wpsq1)
648       || pos.pawn_is_passed(strongerSide, wpsq2))
649       return SCALE_FACTOR_NONE;
650
651   Rank r = Max(relative_rank(strongerSide, wpsq1), relative_rank(strongerSide, wpsq2));
652
653   if (   file_distance(bksq, wpsq1) <= 1
654       && file_distance(bksq, wpsq2) <= 1
655       && relative_rank(strongerSide, bksq) > r)
656   {
657       switch (r) {
658       case RANK_2: return ScaleFactor(10);
659       case RANK_3: return ScaleFactor(10);
660       case RANK_4: return ScaleFactor(15);
661       case RANK_5: return ScaleFactor(20);
662       case RANK_6: return ScaleFactor(40);
663       default: assert(false);
664       }
665   }
666   return SCALE_FACTOR_NONE;
667 }
668
669
670 /// KPsKScalingFunction scales endgames with king and two or more pawns
671 /// against king. There is just a single rule here: If all pawns are on
672 /// the same rook file and are blocked by the defending king, it's a draw.
673 template<>
674 ScaleFactor Endgame<ScaleFactor, KPsK>::apply(const Position& pos) const {
675
676   assert(pos.non_pawn_material(strongerSide) == VALUE_ZERO);
677   assert(pos.piece_count(strongerSide, PAWN) >= 2);
678   assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
679   assert(pos.piece_count(weakerSide, PAWN) == 0);
680
681   Square ksq = pos.king_square(weakerSide);
682   Bitboard pawns = pos.pieces(PAWN, strongerSide);
683
684   // Are all pawns on the 'a' file?
685   if ((pawns & ~FileABB) == EmptyBoardBB)
686   {
687       // Does the defending king block the pawns?
688       if (   square_distance(ksq, relative_square(strongerSide, SQ_A8)) <= 1
689           || (   square_file(ksq) == FILE_A
690               && (in_front_bb(strongerSide, ksq) & pawns) == EmptyBoardBB))
691           return SCALE_FACTOR_ZERO;
692   }
693   // Are all pawns on the 'h' file?
694   else if ((pawns & ~FileHBB) == EmptyBoardBB)
695   {
696     // Does the defending king block the pawns?
697     if (   square_distance(ksq, relative_square(strongerSide, SQ_H8)) <= 1
698         || (   square_file(ksq) == FILE_H
699             && (in_front_bb(strongerSide, ksq) & pawns) == EmptyBoardBB))
700         return SCALE_FACTOR_ZERO;
701   }
702   return SCALE_FACTOR_NONE;
703 }
704
705
706 /// KBPKBScalingFunction scales KBP vs KB endgames. There are two rules:
707 /// If the defending king is somewhere along the path of the pawn, and the
708 /// square of the king is not of the same color as the stronger side's bishop,
709 /// it's a draw. If the two bishops have opposite color, it's almost always
710 /// a draw.
711 template<>
712 ScaleFactor Endgame<ScaleFactor, KBPKB>::apply(const Position& pos) const {
713
714   assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
715   assert(pos.piece_count(strongerSide, BISHOP) == 1);
716   assert(pos.piece_count(strongerSide, PAWN) == 1);
717   assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
718   assert(pos.piece_count(weakerSide, BISHOP) == 1);
719   assert(pos.piece_count(weakerSide, PAWN) == 0);
720
721   Square pawnSq = pos.piece_list(strongerSide, PAWN)[0];
722   Square strongerBishopSq = pos.piece_list(strongerSide, BISHOP)[0];
723   Square weakerBishopSq = pos.piece_list(weakerSide, BISHOP)[0];
724   Square weakerKingSq = pos.king_square(weakerSide);
725
726   // Case 1: Defending king blocks the pawn, and cannot be driven away
727   if (   square_file(weakerKingSq) == square_file(pawnSq)
728       && relative_rank(strongerSide, pawnSq) < relative_rank(strongerSide, weakerKingSq)
729       && (   opposite_color_squares(weakerKingSq, strongerBishopSq)
730           || relative_rank(strongerSide, weakerKingSq) <= RANK_6))
731       return SCALE_FACTOR_ZERO;
732
733   // Case 2: Opposite colored bishops
734   if (opposite_color_squares(strongerBishopSq, weakerBishopSq))
735   {
736       // We assume that the position is drawn in the following three situations:
737       //
738       //   a. The pawn is on rank 5 or further back.
739       //   b. The defending king is somewhere in the pawn's path.
740       //   c. The defending bishop attacks some square along the pawn's path,
741       //      and is at least three squares away from the pawn.
742       //
743       // These rules are probably not perfect, but in practice they work
744       // reasonably well.
745
746       if (relative_rank(strongerSide, pawnSq) <= RANK_5)
747           return SCALE_FACTOR_ZERO;
748       else
749       {
750           Bitboard path = squares_in_front_of(strongerSide, pawnSq);
751
752           if (path & pos.pieces(KING, weakerSide))
753               return SCALE_FACTOR_ZERO;
754
755           if (  (pos.attacks_from<BISHOP>(weakerBishopSq) & path)
756               && square_distance(weakerBishopSq, pawnSq) >= 3)
757               return SCALE_FACTOR_ZERO;
758       }
759   }
760   return SCALE_FACTOR_NONE;
761 }
762
763
764 /// KBPPKBScalingFunction scales KBPP vs KB endgames. It detects a few basic
765 /// draws with opposite-colored bishops.
766 template<>
767 ScaleFactor Endgame<ScaleFactor, KBPPKB>::apply(const Position& pos) const {
768
769   assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
770   assert(pos.piece_count(strongerSide, BISHOP) == 1);
771   assert(pos.piece_count(strongerSide, PAWN) == 2);
772   assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
773   assert(pos.piece_count(weakerSide, BISHOP) == 1);
774   assert(pos.piece_count(weakerSide, PAWN) == 0);
775
776   Square wbsq = pos.piece_list(strongerSide, BISHOP)[0];
777   Square bbsq = pos.piece_list(weakerSide, BISHOP)[0];
778
779   if (!opposite_color_squares(wbsq, bbsq))
780       return SCALE_FACTOR_NONE;
781
782   Square ksq = pos.king_square(weakerSide);
783   Square psq1 = pos.piece_list(strongerSide, PAWN)[0];
784   Square psq2 = pos.piece_list(strongerSide, PAWN)[1];
785   Rank r1 = square_rank(psq1);
786   Rank r2 = square_rank(psq2);
787   Square blockSq1, blockSq2;
788
789   if (relative_rank(strongerSide, psq1) > relative_rank(strongerSide, psq2))
790   {
791       blockSq1 = psq1 + pawn_push(strongerSide);
792       blockSq2 = make_square(square_file(psq2), square_rank(psq1));
793   }
794   else
795   {
796       blockSq1 = psq2 + pawn_push(strongerSide);
797       blockSq2 = make_square(square_file(psq1), square_rank(psq2));
798   }
799
800   switch (file_distance(psq1, psq2))
801   {
802   case 0:
803     // Both pawns are on the same file. Easy draw if defender firmly controls
804     // some square in the frontmost pawn's path.
805     if (   square_file(ksq) == square_file(blockSq1)
806         && relative_rank(strongerSide, ksq) >= relative_rank(strongerSide, blockSq1)
807         && opposite_color_squares(ksq, wbsq))
808         return SCALE_FACTOR_ZERO;
809     else
810         return SCALE_FACTOR_NONE;
811
812   case 1:
813     // Pawns on neighboring files. Draw if defender firmly controls the square
814     // in front of the frontmost pawn's path, and the square diagonally behind
815     // this square on the file of the other pawn.
816     if (   ksq == blockSq1
817         && opposite_color_squares(ksq, wbsq)
818         && (   bbsq == blockSq2
819             || (pos.attacks_from<BISHOP>(blockSq2) & pos.pieces(BISHOP, weakerSide))
820             || abs(r1 - r2) >= 2))
821         return SCALE_FACTOR_ZERO;
822
823     else if (   ksq == blockSq2
824              && opposite_color_squares(ksq, wbsq)
825              && (   bbsq == blockSq1
826                  || (pos.attacks_from<BISHOP>(blockSq1) & pos.pieces(BISHOP, weakerSide))))
827         return SCALE_FACTOR_ZERO;
828     else
829         return SCALE_FACTOR_NONE;
830
831   default:
832     // The pawns are not on the same file or adjacent files. No scaling.
833     return SCALE_FACTOR_NONE;
834   }
835 }
836
837
838 /// KBPKNScalingFunction scales KBP vs KN endgames. There is a single rule:
839 /// If the defending king is somewhere along the path of the pawn, and the
840 /// square of the king is not of the same color as the stronger side's bishop,
841 /// it's a draw.
842 template<>
843 ScaleFactor Endgame<ScaleFactor, KBPKN>::apply(const Position& pos) const {
844
845   assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
846   assert(pos.piece_count(strongerSide, BISHOP) == 1);
847   assert(pos.piece_count(strongerSide, PAWN) == 1);
848   assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
849   assert(pos.piece_count(weakerSide, KNIGHT) == 1);
850   assert(pos.piece_count(weakerSide, PAWN) == 0);
851
852   Square pawnSq = pos.piece_list(strongerSide, PAWN)[0];
853   Square strongerBishopSq = pos.piece_list(strongerSide, BISHOP)[0];
854   Square weakerKingSq = pos.king_square(weakerSide);
855
856   if (   square_file(weakerKingSq) == square_file(pawnSq)
857       && relative_rank(strongerSide, pawnSq) < relative_rank(strongerSide, weakerKingSq)
858       && (   opposite_color_squares(weakerKingSq, strongerBishopSq)
859           || relative_rank(strongerSide, weakerKingSq) <= RANK_6))
860       return SCALE_FACTOR_ZERO;
861
862   return SCALE_FACTOR_NONE;
863 }
864
865
866 /// KNPKScalingFunction scales KNP vs K endgames. There is a single rule:
867 /// If the pawn is a rook pawn on the 7th rank and the defending king prevents
868 /// the pawn from advancing, the position is drawn.
869 template<>
870 ScaleFactor Endgame<ScaleFactor, KNPK>::apply(const Position& pos) const {
871
872   assert(pos.non_pawn_material(strongerSide) == KnightValueMidgame);
873   assert(pos.piece_count(strongerSide, KNIGHT) == 1);
874   assert(pos.piece_count(strongerSide, PAWN) == 1);
875   assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
876   assert(pos.piece_count(weakerSide, PAWN) == 0);
877
878   Square pawnSq = pos.piece_list(strongerSide, PAWN)[0];
879   Square weakerKingSq = pos.king_square(weakerSide);
880
881   if (   pawnSq == relative_square(strongerSide, SQ_A7)
882       && square_distance(weakerKingSq, relative_square(strongerSide, SQ_A8)) <= 1)
883       return SCALE_FACTOR_ZERO;
884
885   if (   pawnSq == relative_square(strongerSide, SQ_H7)
886       && square_distance(weakerKingSq, relative_square(strongerSide, SQ_H8)) <= 1)
887       return SCALE_FACTOR_ZERO;
888
889   return SCALE_FACTOR_NONE;
890 }
891
892
893 /// KPKPScalingFunction scales KP vs KP endgames. This is done by removing
894 /// the weakest side's pawn and probing the KP vs K bitbase: If the weakest
895 /// side has a draw without the pawn, she probably has at least a draw with
896 /// the pawn as well. The exception is when the stronger side's pawn is far
897 /// advanced and not on a rook file; in this case it is often possible to win
898 /// (e.g. 8/4k3/3p4/3P4/6K1/8/8/8 w - - 0 1).
899 template<>
900 ScaleFactor Endgame<ScaleFactor, KPKP>::apply(const Position& pos) const {
901
902   assert(pos.non_pawn_material(strongerSide) == VALUE_ZERO);
903   assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
904   assert(pos.piece_count(WHITE, PAWN) == 1);
905   assert(pos.piece_count(BLACK, PAWN) == 1);
906
907   Square wksq, bksq, wpsq;
908   Color stm;
909
910   if (strongerSide == WHITE)
911   {
912       wksq = pos.king_square(WHITE);
913       bksq = pos.king_square(BLACK);
914       wpsq = pos.piece_list(WHITE, PAWN)[0];
915       stm = pos.side_to_move();
916   }
917   else
918   {
919       wksq = flip_square(pos.king_square(BLACK));
920       bksq = flip_square(pos.king_square(WHITE));
921       wpsq = flip_square(pos.piece_list(BLACK, PAWN)[0]);
922       stm = opposite_color(pos.side_to_move());
923   }
924
925   if (square_file(wpsq) >= FILE_E)
926   {
927       wksq = flop_square(wksq);
928       bksq = flop_square(bksq);
929       wpsq = flop_square(wpsq);
930   }
931
932   // If the pawn has advanced to the fifth rank or further, and is not a
933   // rook pawn, it's too dangerous to assume that it's at least a draw.
934   if (   square_rank(wpsq) >= RANK_5
935       && square_file(wpsq) != FILE_A)
936       return SCALE_FACTOR_NONE;
937
938   // Probe the KPK bitbase with the weakest side's pawn removed. If it's a
939   // draw, it's probably at least a draw even with the pawn.
940   return probe_kpk_bitbase(wksq, wpsq, bksq, stm) ? SCALE_FACTOR_NONE : SCALE_FACTOR_ZERO;
941 }