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
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.
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.
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/>.
28 extern uint32_t probe_kpk_bitbase(Square wksq, Square wpsq, Square bksq, Color stm);
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,
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
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 };
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 };
66 // Build corresponding key code for the opposite color: "KBPKN" -> "KNKBP"
67 const string swap_colors(const string& keyCode) {
69 size_t idx = keyCode.find('K', 1);
70 return keyCode.substr(idx) + keyCode.substr(0, idx);
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) {
79 assert(keyCode.length() > 0 && keyCode.length() < 8);
80 assert(keyCode[0] == 'K');
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());
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";
92 // Build a Position out of the fen string and get its material key
93 return Position(fen, false, 0).get_material_key();
96 typedef Endgames::EMap<Value>::type EFMap;
97 typedef Endgames::EMap<ScaleFactor>::type SFMap;
102 /// Endgames member definitions
104 template<> const EFMap& Endgames::map<Value>() const { return maps.first; }
105 template<> const SFMap& Endgames::map<ScaleFactor>() const { return maps.second; }
107 Endgames::Endgames() {
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");
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");
126 Endgames::~Endgames() {
128 for (EFMap::const_iterator it = map<Value>().begin(); it != map<Value>().end(); ++it)
131 for (SFMap::const_iterator it = map<ScaleFactor>().begin(); it != map<ScaleFactor>().end(); ++it)
135 template<typename T, EndgameType E>
136 void Endgames::add(const string& keyCode) {
138 typedef Endgame<T, E> EG;
139 typedef typename EG::Base B;
140 typedef typename EMap<T>::type M;
142 const_cast<M&>(map<T>()).insert(std::pair<Key, B*>(mat_key(keyCode), new EG(WHITE)));
143 const_cast<M&>(map<T>()).insert(std::pair<Key, B*>(mat_key(swap_colors(keyCode)), new EG(BLACK)));
147 EndgameBase<T>* Endgames::get(Key key) const {
149 typename EMap<T>::type::const_iterator it = map<T>().find(key);
150 return it != map<T>().end() ? it->second : NULL;
153 // Explicit template instantiations
154 template EndgameBase<Value>* Endgames::get<Value>(Key key) const;
155 template EndgameBase<ScaleFactor>* Endgames::get<ScaleFactor>(Key key) const;
158 /// Mate with KX vs K. This function is used to evaluate positions with
159 /// King and plenty of material vs a lone king. It simply gives the
160 /// attacking side a bonus for driving the defending king towards the edge
161 /// of the board, and for keeping the distance between the two kings small.
163 Value Endgame<Value, KXK>::apply(const Position& pos) const {
165 assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
166 assert(pos.piece_count(weakerSide, PAWN) == VALUE_ZERO);
168 Square winnerKSq = pos.king_square(strongerSide);
169 Square loserKSq = pos.king_square(weakerSide);
171 Value result = pos.non_pawn_material(strongerSide)
172 + pos.piece_count(strongerSide, PAWN) * PawnValueEndgame
173 + MateTable[loserKSq]
174 + DistanceBonus[square_distance(winnerKSq, loserKSq)];
176 if ( pos.piece_count(strongerSide, QUEEN)
177 || pos.piece_count(strongerSide, ROOK)
178 || pos.piece_count(strongerSide, BISHOP) > 1)
179 // TODO: check for two equal-colored bishops!
180 result += VALUE_KNOWN_WIN;
182 return strongerSide == pos.side_to_move() ? result : -result;
186 /// Mate with KBN vs K. This is similar to KX vs K, but we have to drive the
187 /// defending king towards a corner square of the right color.
189 Value Endgame<Value, KBNK>::apply(const Position& pos) const {
191 assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
192 assert(pos.piece_count(weakerSide, PAWN) == VALUE_ZERO);
193 assert(pos.non_pawn_material(strongerSide) == KnightValueMidgame + BishopValueMidgame);
194 assert(pos.piece_count(strongerSide, BISHOP) == 1);
195 assert(pos.piece_count(strongerSide, KNIGHT) == 1);
196 assert(pos.piece_count(strongerSide, PAWN) == 0);
198 Square winnerKSq = pos.king_square(strongerSide);
199 Square loserKSq = pos.king_square(weakerSide);
200 Square bishopSquare = pos.piece_list(strongerSide, BISHOP)[0];
202 // kbnk_mate_table() tries to drive toward corners A1 or H8,
203 // if we have a bishop that cannot reach the above squares we
204 // mirror the kings so to drive enemy toward corners A8 or H1.
205 if (opposite_color_squares(bishopSquare, SQ_A1))
207 winnerKSq = flop_square(winnerKSq);
208 loserKSq = flop_square(loserKSq);
211 Value result = VALUE_KNOWN_WIN
212 + DistanceBonus[square_distance(winnerKSq, loserKSq)]
213 + KBNKMateTable[loserKSq];
215 return strongerSide == pos.side_to_move() ? result : -result;
219 /// KP vs K. This endgame is evaluated with the help of a bitbase.
221 Value Endgame<Value, KPK>::apply(const Position& pos) const {
223 assert(pos.non_pawn_material(strongerSide) == VALUE_ZERO);
224 assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
225 assert(pos.piece_count(strongerSide, PAWN) == 1);
226 assert(pos.piece_count(weakerSide, PAWN) == 0);
228 Square wksq, bksq, wpsq;
231 if (strongerSide == WHITE)
233 wksq = pos.king_square(WHITE);
234 bksq = pos.king_square(BLACK);
235 wpsq = pos.piece_list(WHITE, PAWN)[0];
236 stm = pos.side_to_move();
240 wksq = flip_square(pos.king_square(BLACK));
241 bksq = flip_square(pos.king_square(WHITE));
242 wpsq = flip_square(pos.piece_list(BLACK, PAWN)[0]);
243 stm = opposite_color(pos.side_to_move());
246 if (square_file(wpsq) >= FILE_E)
248 wksq = flop_square(wksq);
249 bksq = flop_square(bksq);
250 wpsq = flop_square(wpsq);
253 if (!probe_kpk_bitbase(wksq, wpsq, bksq, stm))
256 Value result = VALUE_KNOWN_WIN
258 + Value(square_rank(wpsq));
260 return strongerSide == pos.side_to_move() ? result : -result;
264 /// KR vs KP. This is a somewhat tricky endgame to evaluate precisely without
265 /// a bitbase. The function below returns drawish scores when the pawn is
266 /// far advanced with support of the king, while the attacking king is far
269 Value Endgame<Value, KRKP>::apply(const Position& pos) const {
271 assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
272 assert(pos.piece_count(strongerSide, PAWN) == 0);
273 assert(pos.non_pawn_material(weakerSide) == 0);
274 assert(pos.piece_count(weakerSide, PAWN) == 1);
276 Square wksq, wrsq, bksq, bpsq;
277 int tempo = (pos.side_to_move() == strongerSide);
279 wksq = pos.king_square(strongerSide);
280 wrsq = pos.piece_list(strongerSide, ROOK)[0];
281 bksq = pos.king_square(weakerSide);
282 bpsq = pos.piece_list(weakerSide, PAWN)[0];
284 if (strongerSide == BLACK)
286 wksq = flip_square(wksq);
287 wrsq = flip_square(wrsq);
288 bksq = flip_square(bksq);
289 bpsq = flip_square(bpsq);
292 Square queeningSq = make_square(square_file(bpsq), RANK_1);
295 // If the stronger side's king is in front of the pawn, it's a win
296 if (wksq < bpsq && square_file(wksq) == square_file(bpsq))
297 result = RookValueEndgame - Value(square_distance(wksq, bpsq));
299 // If the weaker side's king is too far from the pawn and the rook,
301 else if ( square_distance(bksq, bpsq) - (tempo ^ 1) >= 3
302 && square_distance(bksq, wrsq) >= 3)
303 result = RookValueEndgame - Value(square_distance(wksq, bpsq));
305 // If the pawn is far advanced and supported by the defending king,
306 // the position is drawish
307 else if ( square_rank(bksq) <= RANK_3
308 && square_distance(bksq, bpsq) == 1
309 && square_rank(wksq) >= RANK_4
310 && square_distance(wksq, bpsq) - tempo > 2)
311 result = Value(80 - square_distance(wksq, bpsq) * 8);
315 - Value(square_distance(wksq, bpsq + DELTA_S) * 8)
316 + Value(square_distance(bksq, bpsq + DELTA_S) * 8)
317 + Value(square_distance(bpsq, queeningSq) * 8);
319 return strongerSide == pos.side_to_move() ? result : -result;
323 /// KR vs KB. This is very simple, and always returns drawish scores. The
324 /// score is slightly bigger when the defending king is close to the edge.
326 Value Endgame<Value, KRKB>::apply(const Position& pos) const {
328 assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
329 assert(pos.piece_count(strongerSide, PAWN) == 0);
330 assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
331 assert(pos.piece_count(weakerSide, PAWN) == 0);
332 assert(pos.piece_count(weakerSide, BISHOP) == 1);
334 Value result = Value(MateTable[pos.king_square(weakerSide)]);
335 return strongerSide == pos.side_to_move() ? result : -result;
339 /// KR vs KN. The attacking side has slightly better winning chances than
340 /// in KR vs KB, particularly if the king and the knight are far apart.
342 Value Endgame<Value, KRKN>::apply(const Position& pos) const {
344 assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
345 assert(pos.piece_count(strongerSide, PAWN) == 0);
346 assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
347 assert(pos.piece_count(weakerSide, PAWN) == 0);
348 assert(pos.piece_count(weakerSide, KNIGHT) == 1);
350 Square defendingKSq = pos.king_square(weakerSide);
351 Square nSq = pos.piece_list(weakerSide, KNIGHT)[0];
353 int d = square_distance(defendingKSq, nSq);
354 Value result = Value(10)
355 + MateTable[defendingKSq]
356 + KRKNKingKnightDistancePenalty[d];
358 return strongerSide == pos.side_to_move() ? result : -result;
362 /// KQ vs KR. This is almost identical to KX vs K: We give the attacking
363 /// king a bonus for having the kings close together, and for forcing the
364 /// defending king towards the edge. If we also take care to avoid null move
365 /// for the defending side in the search, this is usually sufficient to be
366 /// able to win KQ vs KR.
368 Value Endgame<Value, KQKR>::apply(const Position& pos) const {
370 assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
371 assert(pos.piece_count(strongerSide, PAWN) == 0);
372 assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
373 assert(pos.piece_count(weakerSide, PAWN) == 0);
375 Square winnerKSq = pos.king_square(strongerSide);
376 Square loserKSq = pos.king_square(weakerSide);
378 Value result = QueenValueEndgame
380 + MateTable[loserKSq]
381 + DistanceBonus[square_distance(winnerKSq, loserKSq)];
383 return strongerSide == pos.side_to_move() ? result : -result;
387 Value Endgame<Value, KBBKN>::apply(const Position& pos) const {
389 assert(pos.piece_count(strongerSide, BISHOP) == 2);
390 assert(pos.non_pawn_material(strongerSide) == 2*BishopValueMidgame);
391 assert(pos.piece_count(weakerSide, KNIGHT) == 1);
392 assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
393 assert(pos.pieces(PAWN) == EmptyBoardBB);
395 Value result = BishopValueEndgame;
396 Square wksq = pos.king_square(strongerSide);
397 Square bksq = pos.king_square(weakerSide);
398 Square nsq = pos.piece_list(weakerSide, KNIGHT)[0];
400 // Bonus for attacking king close to defending king
401 result += Value(DistanceBonus[square_distance(wksq, bksq)]);
403 // Bonus for driving the defending king and knight apart
404 result += Value(square_distance(bksq, nsq) * 32);
406 // Bonus for restricting the knight's mobility
407 result += Value((8 - count_1s<CNT32_MAX15>(pos.attacks_from<KNIGHT>(nsq))) * 8);
409 return strongerSide == pos.side_to_move() ? result : -result;
413 /// K and two minors vs K and one or two minors or K and two knights against
414 /// king alone are always draw.
416 Value Endgame<Value, KmmKm>::apply(const Position&) const {
421 Value Endgame<Value, KNNK>::apply(const Position&) const {
425 /// KBPKScalingFunction scales endgames where the stronger side has king,
426 /// bishop and one or more pawns. It checks for draws with rook pawns and a
427 /// bishop of the wrong color. If such a draw is detected, SCALE_FACTOR_ZERO is
428 /// returned. If not, the return value is SCALE_FACTOR_NONE, i.e. no scaling
431 ScaleFactor Endgame<ScaleFactor, KBPsK>::apply(const Position& pos) const {
433 assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
434 assert(pos.piece_count(strongerSide, BISHOP) == 1);
435 assert(pos.piece_count(strongerSide, PAWN) >= 1);
437 // No assertions about the material of weakerSide, because we want draws to
438 // be detected even when the weaker side has some pawns.
440 Bitboard pawns = pos.pieces(PAWN, strongerSide);
441 File pawnFile = square_file(pos.piece_list(strongerSide, PAWN)[0]);
443 // All pawns are on a single rook file ?
444 if ( (pawnFile == FILE_A || pawnFile == FILE_H)
445 && (pawns & ~file_bb(pawnFile)) == EmptyBoardBB)
447 Square bishopSq = pos.piece_list(strongerSide, BISHOP)[0];
448 Square queeningSq = relative_square(strongerSide, make_square(pawnFile, RANK_8));
449 Square kingSq = pos.king_square(weakerSide);
451 if ( opposite_color_squares(queeningSq, bishopSq)
452 && abs(square_file(kingSq) - pawnFile) <= 1)
454 // The bishop has the wrong color, and the defending king is on the
455 // file of the pawn(s) or the neighboring file. Find the rank of the
458 if (strongerSide == WHITE)
460 for (rank = RANK_7; (rank_bb(rank) & pawns) == EmptyBoardBB; rank--) {}
461 assert(rank >= RANK_2 && rank <= RANK_7);
465 for (rank = RANK_2; (rank_bb(rank) & pawns) == EmptyBoardBB; rank++) {}
466 rank = Rank(rank ^ 7); // HACK to get the relative rank
467 assert(rank >= RANK_2 && rank <= RANK_7);
469 // If the defending king has distance 1 to the promotion square or
470 // is placed somewhere in front of the pawn, it's a draw.
471 if ( square_distance(kingSq, queeningSq) <= 1
472 || relative_rank(strongerSide, kingSq) >= rank)
473 return SCALE_FACTOR_ZERO;
476 return SCALE_FACTOR_NONE;
480 /// KQKRPScalingFunction scales endgames where the stronger side has only
481 /// king and queen, while the weaker side has at least a rook and a pawn.
482 /// It tests for fortress draws with a rook on the third rank defended by
485 ScaleFactor Endgame<ScaleFactor, KQKRPs>::apply(const Position& pos) const {
487 assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
488 assert(pos.piece_count(strongerSide, QUEEN) == 1);
489 assert(pos.piece_count(strongerSide, PAWN) == 0);
490 assert(pos.piece_count(weakerSide, ROOK) == 1);
491 assert(pos.piece_count(weakerSide, PAWN) >= 1);
493 Square kingSq = pos.king_square(weakerSide);
494 if ( relative_rank(weakerSide, kingSq) <= RANK_2
495 && relative_rank(weakerSide, pos.king_square(strongerSide)) >= RANK_4
496 && (pos.pieces(ROOK, weakerSide) & rank_bb(relative_rank(weakerSide, RANK_3)))
497 && (pos.pieces(PAWN, weakerSide) & rank_bb(relative_rank(weakerSide, RANK_2)))
498 && (pos.attacks_from<KING>(kingSq) & pos.pieces(PAWN, weakerSide)))
500 Square rsq = pos.piece_list(weakerSide, ROOK)[0];
501 if (pos.attacks_from<PAWN>(rsq, strongerSide) & pos.pieces(PAWN, weakerSide))
502 return SCALE_FACTOR_ZERO;
504 return SCALE_FACTOR_NONE;
508 /// KRPKRScalingFunction scales KRP vs KR endgames. This function knows a
509 /// handful of the most important classes of drawn positions, but is far
510 /// from perfect. It would probably be a good idea to add more knowledge
513 /// It would also be nice to rewrite the actual code for this function,
514 /// which is mostly copied from Glaurung 1.x, and not very pretty.
516 ScaleFactor Endgame<ScaleFactor, KRPKR>::apply(const Position& pos) const {
518 assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
519 assert(pos.piece_count(strongerSide, PAWN) == 1);
520 assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
521 assert(pos.piece_count(weakerSide, PAWN) == 0);
523 Square wksq = pos.king_square(strongerSide);
524 Square wrsq = pos.piece_list(strongerSide, ROOK)[0];
525 Square wpsq = pos.piece_list(strongerSide, PAWN)[0];
526 Square bksq = pos.king_square(weakerSide);
527 Square brsq = pos.piece_list(weakerSide, ROOK)[0];
529 // Orient the board in such a way that the stronger side is white, and the
530 // pawn is on the left half of the board.
531 if (strongerSide == BLACK)
533 wksq = flip_square(wksq);
534 wrsq = flip_square(wrsq);
535 wpsq = flip_square(wpsq);
536 bksq = flip_square(bksq);
537 brsq = flip_square(brsq);
539 if (square_file(wpsq) > FILE_D)
541 wksq = flop_square(wksq);
542 wrsq = flop_square(wrsq);
543 wpsq = flop_square(wpsq);
544 bksq = flop_square(bksq);
545 brsq = flop_square(brsq);
548 File f = square_file(wpsq);
549 Rank r = square_rank(wpsq);
550 Square queeningSq = make_square(f, RANK_8);
551 int tempo = (pos.side_to_move() == strongerSide);
553 // If the pawn is not too far advanced and the defending king defends the
554 // queening square, use the third-rank defence.
556 && square_distance(bksq, queeningSq) <= 1
558 && (square_rank(brsq) == RANK_6 || (r <= RANK_3 && square_rank(wrsq) != RANK_6)))
559 return SCALE_FACTOR_ZERO;
561 // The defending side saves a draw by checking from behind in case the pawn
562 // has advanced to the 6th rank with the king behind.
564 && square_distance(bksq, queeningSq) <= 1
565 && square_rank(wksq) + tempo <= RANK_6
566 && (square_rank(brsq) == RANK_1 || (!tempo && abs(square_file(brsq) - f) >= 3)))
567 return SCALE_FACTOR_ZERO;
570 && bksq == queeningSq
571 && square_rank(brsq) == RANK_1
572 && (!tempo || square_distance(wksq, wpsq) >= 2))
573 return SCALE_FACTOR_ZERO;
575 // White pawn on a7 and rook on a8 is a draw if black's king is on g7 or h7
576 // and the black rook is behind the pawn.
579 && (bksq == SQ_H7 || bksq == SQ_G7)
580 && square_file(brsq) == FILE_A
581 && (square_rank(brsq) <= RANK_3 || square_file(wksq) >= FILE_D || square_rank(wksq) <= RANK_5))
582 return SCALE_FACTOR_ZERO;
584 // If the defending king blocks the pawn and the attacking king is too far
585 // away, it's a draw.
587 && bksq == wpsq + DELTA_N
588 && square_distance(wksq, wpsq) - tempo >= 2
589 && square_distance(wksq, brsq) - tempo >= 2)
590 return SCALE_FACTOR_ZERO;
592 // Pawn on the 7th rank supported by the rook from behind usually wins if the
593 // attacking king is closer to the queening square than the defending king,
594 // and the defending king cannot gain tempi by threatening the attacking rook.
597 && square_file(wrsq) == f
598 && wrsq != queeningSq
599 && (square_distance(wksq, queeningSq) < square_distance(bksq, queeningSq) - 2 + tempo)
600 && (square_distance(wksq, queeningSq) < square_distance(bksq, wrsq) + tempo))
601 return ScaleFactor(SCALE_FACTOR_MAX - 2 * square_distance(wksq, queeningSq));
603 // Similar to the above, but with the pawn further back
605 && square_file(wrsq) == f
607 && (square_distance(wksq, queeningSq) < square_distance(bksq, queeningSq) - 2 + tempo)
608 && (square_distance(wksq, wpsq + DELTA_N) < square_distance(bksq, wpsq + DELTA_N) - 2 + tempo)
609 && ( square_distance(bksq, wrsq) + tempo >= 3
610 || ( square_distance(wksq, queeningSq) < square_distance(bksq, wrsq) + tempo
611 && (square_distance(wksq, wpsq + DELTA_N) < square_distance(bksq, wrsq) + tempo))))
612 return ScaleFactor( SCALE_FACTOR_MAX
613 - 8 * square_distance(wpsq, queeningSq)
614 - 2 * square_distance(wksq, queeningSq));
616 // If the pawn is not far advanced, and the defending king is somewhere in
617 // the pawn's path, it's probably a draw.
618 if (r <= RANK_4 && bksq > wpsq)
620 if (square_file(bksq) == square_file(wpsq))
621 return ScaleFactor(10);
622 if ( abs(square_file(bksq) - square_file(wpsq)) == 1
623 && square_distance(wksq, bksq) > 2)
624 return ScaleFactor(24 - 2 * square_distance(wksq, bksq));
626 return SCALE_FACTOR_NONE;
630 /// KRPPKRPScalingFunction scales KRPP vs KRP endgames. There is only a
631 /// single pattern: If the stronger side has no pawns and the defending king
632 /// is actively placed, the position is drawish.
634 ScaleFactor Endgame<ScaleFactor, KRPPKRP>::apply(const Position& pos) const {
636 assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
637 assert(pos.piece_count(strongerSide, PAWN) == 2);
638 assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
639 assert(pos.piece_count(weakerSide, PAWN) == 1);
641 Square wpsq1 = pos.piece_list(strongerSide, PAWN)[0];
642 Square wpsq2 = pos.piece_list(strongerSide, PAWN)[1];
643 Square bksq = pos.king_square(weakerSide);
645 // Does the stronger side have a passed pawn?
646 if ( pos.pawn_is_passed(strongerSide, wpsq1)
647 || pos.pawn_is_passed(strongerSide, wpsq2))
648 return SCALE_FACTOR_NONE;
650 Rank r = Max(relative_rank(strongerSide, wpsq1), relative_rank(strongerSide, wpsq2));
652 if ( file_distance(bksq, wpsq1) <= 1
653 && file_distance(bksq, wpsq2) <= 1
654 && relative_rank(strongerSide, bksq) > r)
657 case RANK_2: return ScaleFactor(10);
658 case RANK_3: return ScaleFactor(10);
659 case RANK_4: return ScaleFactor(15);
660 case RANK_5: return ScaleFactor(20);
661 case RANK_6: return ScaleFactor(40);
662 default: assert(false);
665 return SCALE_FACTOR_NONE;
669 /// KPsKScalingFunction scales endgames with king and two or more pawns
670 /// against king. There is just a single rule here: If all pawns are on
671 /// the same rook file and are blocked by the defending king, it's a draw.
673 ScaleFactor Endgame<ScaleFactor, KPsK>::apply(const Position& pos) const {
675 assert(pos.non_pawn_material(strongerSide) == VALUE_ZERO);
676 assert(pos.piece_count(strongerSide, PAWN) >= 2);
677 assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
678 assert(pos.piece_count(weakerSide, PAWN) == 0);
680 Square ksq = pos.king_square(weakerSide);
681 Bitboard pawns = pos.pieces(PAWN, strongerSide);
683 // Are all pawns on the 'a' file?
684 if ((pawns & ~FileABB) == EmptyBoardBB)
686 // Does the defending king block the pawns?
687 if ( square_distance(ksq, relative_square(strongerSide, SQ_A8)) <= 1
688 || ( square_file(ksq) == FILE_A
689 && (in_front_bb(strongerSide, ksq) & pawns) == EmptyBoardBB))
690 return SCALE_FACTOR_ZERO;
692 // Are all pawns on the 'h' file?
693 else if ((pawns & ~FileHBB) == EmptyBoardBB)
695 // Does the defending king block the pawns?
696 if ( square_distance(ksq, relative_square(strongerSide, SQ_H8)) <= 1
697 || ( square_file(ksq) == FILE_H
698 && (in_front_bb(strongerSide, ksq) & pawns) == EmptyBoardBB))
699 return SCALE_FACTOR_ZERO;
701 return SCALE_FACTOR_NONE;
705 /// KBPKBScalingFunction scales KBP vs KB endgames. There are two rules:
706 /// If the defending king is somewhere along the path of the pawn, and the
707 /// square of the king is not of the same color as the stronger side's bishop,
708 /// it's a draw. If the two bishops have opposite color, it's almost always
711 ScaleFactor Endgame<ScaleFactor, KBPKB>::apply(const Position& pos) const {
713 assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
714 assert(pos.piece_count(strongerSide, BISHOP) == 1);
715 assert(pos.piece_count(strongerSide, PAWN) == 1);
716 assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
717 assert(pos.piece_count(weakerSide, BISHOP) == 1);
718 assert(pos.piece_count(weakerSide, PAWN) == 0);
720 Square pawnSq = pos.piece_list(strongerSide, PAWN)[0];
721 Square strongerBishopSq = pos.piece_list(strongerSide, BISHOP)[0];
722 Square weakerBishopSq = pos.piece_list(weakerSide, BISHOP)[0];
723 Square weakerKingSq = pos.king_square(weakerSide);
725 // Case 1: Defending king blocks the pawn, and cannot be driven away
726 if ( square_file(weakerKingSq) == square_file(pawnSq)
727 && relative_rank(strongerSide, pawnSq) < relative_rank(strongerSide, weakerKingSq)
728 && ( opposite_color_squares(weakerKingSq, strongerBishopSq)
729 || relative_rank(strongerSide, weakerKingSq) <= RANK_6))
730 return SCALE_FACTOR_ZERO;
732 // Case 2: Opposite colored bishops
733 if (opposite_color_squares(strongerBishopSq, weakerBishopSq))
735 // We assume that the position is drawn in the following three situations:
737 // a. The pawn is on rank 5 or further back.
738 // b. The defending king is somewhere in the pawn's path.
739 // c. The defending bishop attacks some square along the pawn's path,
740 // and is at least three squares away from the pawn.
742 // These rules are probably not perfect, but in practice they work
745 if (relative_rank(strongerSide, pawnSq) <= RANK_5)
746 return SCALE_FACTOR_ZERO;
749 Bitboard path = squares_in_front_of(strongerSide, pawnSq);
751 if (path & pos.pieces(KING, weakerSide))
752 return SCALE_FACTOR_ZERO;
754 if ( (pos.attacks_from<BISHOP>(weakerBishopSq) & path)
755 && square_distance(weakerBishopSq, pawnSq) >= 3)
756 return SCALE_FACTOR_ZERO;
759 return SCALE_FACTOR_NONE;
763 /// KBPPKBScalingFunction scales KBPP vs KB endgames. It detects a few basic
764 /// draws with opposite-colored bishops.
766 ScaleFactor Endgame<ScaleFactor, KBPPKB>::apply(const Position& pos) const {
768 assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
769 assert(pos.piece_count(strongerSide, BISHOP) == 1);
770 assert(pos.piece_count(strongerSide, PAWN) == 2);
771 assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
772 assert(pos.piece_count(weakerSide, BISHOP) == 1);
773 assert(pos.piece_count(weakerSide, PAWN) == 0);
775 Square wbsq = pos.piece_list(strongerSide, BISHOP)[0];
776 Square bbsq = pos.piece_list(weakerSide, BISHOP)[0];
778 if (!opposite_color_squares(wbsq, bbsq))
779 return SCALE_FACTOR_NONE;
781 Square ksq = pos.king_square(weakerSide);
782 Square psq1 = pos.piece_list(strongerSide, PAWN)[0];
783 Square psq2 = pos.piece_list(strongerSide, PAWN)[1];
784 Rank r1 = square_rank(psq1);
785 Rank r2 = square_rank(psq2);
786 Square blockSq1, blockSq2;
788 if (relative_rank(strongerSide, psq1) > relative_rank(strongerSide, psq2))
790 blockSq1 = psq1 + pawn_push(strongerSide);
791 blockSq2 = make_square(square_file(psq2), square_rank(psq1));
795 blockSq1 = psq2 + pawn_push(strongerSide);
796 blockSq2 = make_square(square_file(psq1), square_rank(psq2));
799 switch (file_distance(psq1, psq2))
802 // Both pawns are on the same file. Easy draw if defender firmly controls
803 // some square in the frontmost pawn's path.
804 if ( square_file(ksq) == square_file(blockSq1)
805 && relative_rank(strongerSide, ksq) >= relative_rank(strongerSide, blockSq1)
806 && opposite_color_squares(ksq, wbsq))
807 return SCALE_FACTOR_ZERO;
809 return SCALE_FACTOR_NONE;
812 // Pawns on neighboring files. Draw if defender firmly controls the square
813 // in front of the frontmost pawn's path, and the square diagonally behind
814 // this square on the file of the other pawn.
816 && opposite_color_squares(ksq, wbsq)
817 && ( bbsq == blockSq2
818 || (pos.attacks_from<BISHOP>(blockSq2) & pos.pieces(BISHOP, weakerSide))
819 || abs(r1 - r2) >= 2))
820 return SCALE_FACTOR_ZERO;
822 else if ( ksq == blockSq2
823 && opposite_color_squares(ksq, wbsq)
824 && ( bbsq == blockSq1
825 || (pos.attacks_from<BISHOP>(blockSq1) & pos.pieces(BISHOP, weakerSide))))
826 return SCALE_FACTOR_ZERO;
828 return SCALE_FACTOR_NONE;
831 // The pawns are not on the same file or adjacent files. No scaling.
832 return SCALE_FACTOR_NONE;
837 /// KBPKNScalingFunction scales KBP vs KN endgames. There is a single rule:
838 /// If the defending king is somewhere along the path of the pawn, and the
839 /// square of the king is not of the same color as the stronger side's bishop,
842 ScaleFactor Endgame<ScaleFactor, KBPKN>::apply(const Position& pos) const {
844 assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
845 assert(pos.piece_count(strongerSide, BISHOP) == 1);
846 assert(pos.piece_count(strongerSide, PAWN) == 1);
847 assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
848 assert(pos.piece_count(weakerSide, KNIGHT) == 1);
849 assert(pos.piece_count(weakerSide, PAWN) == 0);
851 Square pawnSq = pos.piece_list(strongerSide, PAWN)[0];
852 Square strongerBishopSq = pos.piece_list(strongerSide, BISHOP)[0];
853 Square weakerKingSq = pos.king_square(weakerSide);
855 if ( square_file(weakerKingSq) == square_file(pawnSq)
856 && relative_rank(strongerSide, pawnSq) < relative_rank(strongerSide, weakerKingSq)
857 && ( opposite_color_squares(weakerKingSq, strongerBishopSq)
858 || relative_rank(strongerSide, weakerKingSq) <= RANK_6))
859 return SCALE_FACTOR_ZERO;
861 return SCALE_FACTOR_NONE;
865 /// KNPKScalingFunction scales KNP vs K endgames. There is a single rule:
866 /// If the pawn is a rook pawn on the 7th rank and the defending king prevents
867 /// the pawn from advancing, the position is drawn.
869 ScaleFactor Endgame<ScaleFactor, KNPK>::apply(const Position& pos) const {
871 assert(pos.non_pawn_material(strongerSide) == KnightValueMidgame);
872 assert(pos.piece_count(strongerSide, KNIGHT) == 1);
873 assert(pos.piece_count(strongerSide, PAWN) == 1);
874 assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
875 assert(pos.piece_count(weakerSide, PAWN) == 0);
877 Square pawnSq = pos.piece_list(strongerSide, PAWN)[0];
878 Square weakerKingSq = pos.king_square(weakerSide);
880 if ( pawnSq == relative_square(strongerSide, SQ_A7)
881 && square_distance(weakerKingSq, relative_square(strongerSide, SQ_A8)) <= 1)
882 return SCALE_FACTOR_ZERO;
884 if ( pawnSq == relative_square(strongerSide, SQ_H7)
885 && square_distance(weakerKingSq, relative_square(strongerSide, SQ_H8)) <= 1)
886 return SCALE_FACTOR_ZERO;
888 return SCALE_FACTOR_NONE;
892 /// KPKPScalingFunction scales KP vs KP endgames. This is done by removing
893 /// the weakest side's pawn and probing the KP vs K bitbase: If the weakest
894 /// side has a draw without the pawn, she probably has at least a draw with
895 /// the pawn as well. The exception is when the stronger side's pawn is far
896 /// advanced and not on a rook file; in this case it is often possible to win
897 /// (e.g. 8/4k3/3p4/3P4/6K1/8/8/8 w - - 0 1).
899 ScaleFactor Endgame<ScaleFactor, KPKP>::apply(const Position& pos) const {
901 assert(pos.non_pawn_material(strongerSide) == VALUE_ZERO);
902 assert(pos.non_pawn_material(weakerSide) == VALUE_ZERO);
903 assert(pos.piece_count(WHITE, PAWN) == 1);
904 assert(pos.piece_count(BLACK, PAWN) == 1);
906 Square wksq, bksq, wpsq;
909 if (strongerSide == WHITE)
911 wksq = pos.king_square(WHITE);
912 bksq = pos.king_square(BLACK);
913 wpsq = pos.piece_list(WHITE, PAWN)[0];
914 stm = pos.side_to_move();
918 wksq = flip_square(pos.king_square(BLACK));
919 bksq = flip_square(pos.king_square(WHITE));
920 wpsq = flip_square(pos.piece_list(BLACK, PAWN)[0]);
921 stm = opposite_color(pos.side_to_move());
924 if (square_file(wpsq) >= FILE_E)
926 wksq = flop_square(wksq);
927 bksq = flop_square(bksq);
928 wpsq = flop_square(wpsq);
931 // If the pawn has advanced to the fifth rank or further, and is not a
932 // rook pawn, it's too dangerous to assume that it's at least a draw.
933 if ( square_rank(wpsq) >= RANK_5
934 && square_file(wpsq) != FILE_A)
935 return SCALE_FACTOR_NONE;
937 // Probe the KPK bitbase with the weakest side's pawn removed. If it's a
938 // draw, it's probably at least a draw even with the pawn.
939 return probe_kpk_bitbase(wksq, wpsq, bksq, stm) ? SCALE_FACTOR_NONE : SCALE_FACTOR_ZERO;