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