]> git.sesse.net Git - stockfish/blob - src/position.cpp
5a8ef0b1c8c5ad56334f8bc2d6e013138a264fc2
[stockfish] / src / position.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 Marco Costalba
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
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26 #include <iostream>
27 #include <fstream>
28
29 #include "mersenne.h"
30 #include "movegen.h"
31 #include "movepick.h"
32 #include "position.h"
33 #include "psqtab.h"
34 #include "san.h"
35 #include "ucioption.h"
36
37
38 ////
39 //// Variables
40 ////
41
42 extern SearchStack EmptySearchStack;
43
44 int Position::castleRightsMask[64];
45
46 Key Position::zobrist[2][8][64];
47 Key Position::zobEp[64];
48 Key Position::zobCastle[16];
49 Key Position::zobMaterial[2][8][16];
50 Key Position::zobSideToMove;
51
52 Value Position::MgPieceSquareTable[16][64];
53 Value Position::EgPieceSquareTable[16][64];
54
55 static bool RequestPending = false;
56
57 ////
58 //// Functions
59 ////
60
61 /// Constructors
62
63 Position::Position(const Position& pos) {
64   copy(pos);
65 }
66
67 Position::Position(const std::string& fen) {
68   from_fen(fen);
69 }
70
71
72 /// Position::from_fen() initializes the position object with the given FEN
73 /// string. This function is not very robust - make sure that input FENs are
74 /// correct (this is assumed to be the responsibility of the GUI).
75
76 void Position::from_fen(const std::string& fen) {
77
78   static const std::string pieceLetters = "KQRBNPkqrbnp";
79   static const Piece pieces[] = { WK, WQ, WR, WB, WN, WP, BK, BQ, BR, BB, BN, BP };
80
81   clear();
82
83   // Board
84   Rank rank = RANK_8;
85   File file = FILE_A;
86   size_t i = 0;
87   for ( ; fen[i] != ' '; i++)
88   {
89       if (isdigit(fen[i]))
90       {
91           // Skip the given number of files
92           file += (fen[i] - '1' + 1);
93           continue;
94       }
95       else if (fen[i] == '/')
96       {
97           file = FILE_A;
98           rank--;
99           continue;
100       }
101       size_t idx = pieceLetters.find(fen[i]);
102       if (idx == std::string::npos)
103       {
104            std::cout << "Error in FEN at character " << i << std::endl;
105            return;
106       }
107       Square square = make_square(file, rank);
108       put_piece(pieces[idx], square);
109       file++;
110   }
111
112   // Side to move
113   i++;
114   if (fen[i] != 'w' && fen[i] != 'b')
115   {
116       std::cout << "Error in FEN at character " << i << std::endl;
117       return;
118   }
119   sideToMove = (fen[i] == 'w' ? WHITE : BLACK);
120
121   // Castling rights
122   i++;
123   if (fen[i] != ' ')
124   {
125       std::cout << "Error in FEN at character " << i << std::endl;
126       return;
127   }
128
129   i++;
130   while(strchr("KQkqabcdefghABCDEFGH-", fen[i])) {
131     if (fen[i] == '-')
132     {
133       i++;
134       break;
135     }
136     else if(fen[i] == 'K') allow_oo(WHITE);
137     else if(fen[i] == 'Q') allow_ooo(WHITE);
138     else if(fen[i] == 'k') allow_oo(BLACK);
139     else if(fen[i] == 'q') allow_ooo(BLACK);
140     else if(fen[i] >= 'A' && fen[i] <= 'H') {
141       File rookFile, kingFile = FILE_NONE;
142       for(Square square = SQ_B1; square <= SQ_G1; square++)
143         if(piece_on(square) == WK)
144           kingFile = square_file(square);
145       if(kingFile == FILE_NONE) {
146         std::cout << "Error in FEN at character " << i << std::endl;
147         return;
148       }
149       initialKFile = kingFile;
150       rookFile = File(fen[i] - 'A') + FILE_A;
151       if(rookFile < initialKFile) {
152         allow_ooo(WHITE);
153         initialQRFile = rookFile;
154       }
155       else {
156         allow_oo(WHITE);
157         initialKRFile = rookFile;
158       }
159     }
160     else if(fen[i] >= 'a' && fen[i] <= 'h') {
161       File rookFile, kingFile = FILE_NONE;
162       for(Square square = SQ_B8; square <= SQ_G8; square++)
163         if(piece_on(square) == BK)
164           kingFile = square_file(square);
165       if(kingFile == FILE_NONE) {
166         std::cout << "Error in FEN at character " << i << std::endl;
167         return;
168       }
169       initialKFile = kingFile;
170       rookFile = File(fen[i] - 'a') + FILE_A;
171       if(rookFile < initialKFile) {
172         allow_ooo(BLACK);
173         initialQRFile = rookFile;
174       }
175       else {
176         allow_oo(BLACK);
177         initialKRFile = rookFile;
178       }
179     }
180     else {
181       std::cout << "Error in FEN at character " << i << std::endl;
182       return;
183     }
184     i++;
185   }
186
187   // Skip blanks
188   while (fen[i] == ' ')
189       i++;
190
191   // En passant square
192   if (    i < fen.length() - 2
193       && (fen[i] >= 'a' && fen[i] <= 'h')
194       && (fen[i+1] == '3' || fen[i+1] == '6'))
195       epSquare = square_from_string(fen.substr(i, 2));
196
197   // Various initialisation
198   for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
199       castleRightsMask[sq] = ALL_CASTLES;
200
201   castleRightsMask[make_square(initialKFile,  RANK_1)] ^= (WHITE_OO|WHITE_OOO);
202   castleRightsMask[make_square(initialKFile,  RANK_8)] ^= (BLACK_OO|BLACK_OOO);
203   castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
204   castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
205   castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
206   castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
207
208   find_checkers();
209
210   key = compute_key();
211   pawnKey = compute_pawn_key();
212   materialKey = compute_material_key();
213   mgValue = compute_mg_value();
214   egValue = compute_eg_value();
215   npMaterial[WHITE] = compute_non_pawn_material(WHITE);
216   npMaterial[BLACK] = compute_non_pawn_material(BLACK);
217 }
218
219
220 /// Position::to_fen() converts the position object to a FEN string. This is
221 /// probably only useful for debugging.
222
223 const std::string Position::to_fen() const {
224
225   static const std::string pieceLetters = " PNBRQK  pnbrqk";
226   std::string fen;
227   int skip;
228
229   for (Rank rank = RANK_8; rank >= RANK_1; rank--)
230   {
231       skip = 0;
232       for (File file = FILE_A; file <= FILE_H; file++)
233       {
234           Square sq = make_square(file, rank);
235           if (!square_is_occupied(sq))
236           {   skip++;
237               continue;
238           }
239           if (skip > 0)
240           {
241               fen += (char)skip + '0';
242               skip = 0;
243           }
244           fen += pieceLetters[piece_on(sq)];
245       }
246       if (skip > 0)
247           fen += (char)skip + '0';
248
249       fen += (rank > RANK_1 ? '/' : ' ');
250   }
251   fen += (sideToMove == WHITE ? "w " : "b ");
252   if (castleRights != NO_CASTLES)
253   {
254     if (can_castle_kingside(WHITE))  fen += 'K';
255     if (can_castle_queenside(WHITE)) fen += 'Q';
256     if (can_castle_kingside(BLACK))  fen += 'k';
257     if (can_castle_queenside(BLACK)) fen += 'q';
258   } else
259       fen += '-';
260
261   fen += ' ';
262   if (ep_square() != SQ_NONE)
263       fen += square_to_string(ep_square());
264   else
265       fen += '-';
266
267   return fen;
268 }
269
270
271 /// Position::print() prints an ASCII representation of the position to
272 /// the standard output. If a move is given then also the san is print.
273
274 void Position::print(Move m) const {
275
276   static const std::string pieceLetters = " PNBRQK  PNBRQK .";
277
278   // Check for reentrancy, as example when called from inside
279   // MovePicker that is used also here in move_to_san()
280   if (RequestPending)
281       return;
282
283   RequestPending = true;
284
285   std::cout << std::endl;
286   if (m != MOVE_NONE)
287   {
288       std::string col = (color_of_piece_on(move_from(m)) == BLACK ? ".." : "");
289       std::cout << "Move is: " << col << move_to_san(*this, m) << std::endl;
290   }
291   for (Rank rank = RANK_8; rank >= RANK_1; rank--)
292   {
293       std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
294       for (File file = FILE_A; file <= FILE_H; file++)
295       {
296           Square sq = make_square(file, rank);
297           Piece piece = piece_on(sq);
298           if (piece == EMPTY && square_color(sq) == WHITE)
299               piece = NO_PIECE;
300
301           char col = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
302           std::cout << '|' << col << pieceLetters[piece] << col;
303       }
304       std::cout << '|' << std::endl;
305   }
306   std::cout << "+---+---+---+---+---+---+---+---+" << std::endl
307             << "Fen is: " << to_fen() << std::endl
308             << "Key is: " << key << std::endl;
309
310   RequestPending = false;
311 }
312
313
314 /// Position::copy() creates a copy of the input position.
315
316 void Position::copy(const Position &pos) {
317
318   memcpy(this, &pos, sizeof(Position));
319 }
320
321
322 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
323 /// king) pieces for the given color.
324 Bitboard Position::pinned_pieces(Color c) const {
325
326   if (pinned[c] != ~EmptyBoardBB)
327       return pinned[c];
328
329   Bitboard p1, p2;
330   Square ksq = king_square(c);
331   pinned[c] = hidden_checks<ROOK, true>(c, ksq, p1) | hidden_checks<BISHOP, true>(c, ksq, p2);
332   pinners[c] = p1 | p2;
333   return pinned[c];
334 }
335
336 Bitboard Position::pinned_pieces(Color c, Bitboard& p) const {
337
338   if (pinned[c] == ~EmptyBoardBB)
339       pinned_pieces(c);
340
341   p = pinners[c];
342   return pinned[c];
343 }
344
345 Bitboard Position::discovered_check_candidates(Color c) const {
346
347   if (dcCandidates[c] != ~EmptyBoardBB)
348       return dcCandidates[c];
349
350   Bitboard dummy;
351   Square ksq = king_square(opposite_color(c));
352   dcCandidates[c] = hidden_checks<ROOK, false>(c, ksq, dummy) | hidden_checks<BISHOP, false>(c, ksq, dummy);
353   return dcCandidates[c];
354 }
355
356 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
357 /// king) pieces for the given color and for the given pinner type. Or, when
358 /// template parameter FindPinned is false, the pinned pieces of opposite color
359 /// that are, indeed, the pieces candidate for a discovery check.
360 template<PieceType Piece, bool FindPinned>
361 Bitboard Position::hidden_checks(Color c, Square ksq, Bitboard& pinners) const {
362
363   Square s;
364   Bitboard sliders, result = EmptyBoardBB;
365
366   if (Piece == ROOK) // Resolved at compile time
367       sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
368   else
369       sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
370
371   if (sliders && (!FindPinned || (sliders & ~checkersBB)))
372   {
373        // King blockers are candidate pinned pieces
374       Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
375
376       // Pinners are sliders, not checkers, that give check when
377       // candidate pinned are removed.
378       pinners = (FindPinned ? sliders & ~checkersBB : sliders);
379
380       if (Piece == ROOK)
381           pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
382       else
383           pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
384
385       // Finally for each pinner find the corresponding pinned piece (if same color of king)
386       // or discovery checker (if opposite color) among the candidates.
387       Bitboard p = pinners;
388       while (p)
389       {
390           s = pop_1st_bit(&p);
391           result |= (squares_between(s, ksq) & candidate_pinned);
392       }
393   }
394   else
395       pinners = EmptyBoardBB;
396
397   return result;
398 }
399
400
401 /// Position::attacks_to() computes a bitboard containing all pieces which
402 /// attacks a given square. There are two versions of this function: One
403 /// which finds attackers of both colors, and one which only finds the
404 /// attackers for one side.
405
406 Bitboard Position::attacks_to(Square s) const {
407
408   return  (pawn_attacks(BLACK, s)   & pawns(WHITE))
409         | (pawn_attacks(WHITE, s)   & pawns(BLACK))
410         | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
411         | (piece_attacks<ROOK>(s)   & rooks_and_queens())
412         | (piece_attacks<BISHOP>(s) & bishops_and_queens())
413         | (piece_attacks<KING>(s)   & pieces_of_type(KING));
414 }
415
416 /// Position::piece_attacks_square() tests whether the piece on square f
417 /// attacks square t.
418
419 bool Position::piece_attacks_square(Piece p, Square f, Square t) const {
420
421   assert(square_is_ok(f));
422   assert(square_is_ok(t));
423
424   switch (p)
425   {
426   case WP:          return pawn_attacks_square(WHITE, f, t);
427   case BP:          return pawn_attacks_square(BLACK, f, t);
428   case WN: case BN: return piece_attacks_square<KNIGHT>(f, t);
429   case WB: case BB: return piece_attacks_square<BISHOP>(f, t);
430   case WR: case BR: return piece_attacks_square<ROOK>(f, t);
431   case WQ: case BQ: return piece_attacks_square<QUEEN>(f, t);
432   case WK: case BK: return piece_attacks_square<KING>(f, t);
433   default: break;
434   }
435   return false;
436 }
437
438
439 /// Position::move_attacks_square() tests whether a move from the current
440 /// position attacks a given square.
441
442 bool Position::move_attacks_square(Move m, Square s) const {
443
444   assert(move_is_ok(m));
445   assert(square_is_ok(s));
446
447   Square f = move_from(m), t = move_to(m);
448
449   assert(square_is_occupied(f));
450
451   if (piece_attacks_square(piece_on(f), t, s))
452       return true;
453
454   // Move the piece and scan for X-ray attacks behind it
455   Bitboard occ = occupied_squares();
456   Color us = color_of_piece_on(f);
457   clear_bit(&occ, f);
458   set_bit(&occ, t);
459   Bitboard xray = ( (rook_attacks_bb(s, occ) & rooks_and_queens())
460                    |(bishop_attacks_bb(s, occ) & bishops_and_queens())) & pieces_of_color(us);
461
462   // If we have attacks we need to verify that are caused by our move
463   // and are not already existent ones.
464   return xray && (xray ^ (xray & piece_attacks<QUEEN>(s)));
465 }
466
467
468 /// Position::find_checkers() computes the checkersBB bitboard, which
469 /// contains a nonzero bit for each checking piece (0, 1 or 2).  It
470 /// currently works by calling Position::attacks_to, which is probably
471 /// inefficient. Consider rewriting this function to use the last move
472 /// played, like in non-bitboard versions of Glaurung.
473
474 void Position::find_checkers() {
475
476   Color us = side_to_move();
477   checkersBB = attacks_to(king_square(us), opposite_color(us));
478 }
479
480
481 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
482
483 bool Position::pl_move_is_legal(Move m) const {
484
485   assert(is_ok());
486   assert(move_is_ok(m));
487
488   // If we're in check, all pseudo-legal moves are legal, because our
489   // check evasion generator only generates true legal moves.
490   if (is_check())
491       return true;
492
493   // Castling moves are checked for legality during move generation.
494   if (move_is_castle(m))
495       return true;
496
497   Color us = side_to_move();
498   Color them = opposite_color(us);
499   Square from = move_from(m);
500   Square ksq = king_square(us);
501
502   assert(color_of_piece_on(from) == us);
503   assert(piece_on(ksq) == piece_of_color_and_type(us, KING));
504
505   // En passant captures are a tricky special case.  Because they are
506   // rather uncommon, we do it simply by testing whether the king is attacked
507   // after the move is made
508   if (move_is_ep(m))
509   {
510       Square to = move_to(m);
511       Square capsq = make_square(square_file(to), square_rank(from));
512       Bitboard b = occupied_squares();
513
514       assert(to == ep_square());
515       assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
516       assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
517       assert(piece_on(to) == EMPTY);
518
519       clear_bit(&b, from);
520       clear_bit(&b, capsq);
521       set_bit(&b, to);
522
523       return   !(rook_attacks_bb(ksq, b) & rooks_and_queens(them))
524             && !(bishop_attacks_bb(ksq, b) & bishops_and_queens(them));
525   }
526
527   // If the moving piece is a king, check whether the destination
528   // square is attacked by the opponent.
529   if (from == ksq)
530       return !(square_is_attacked(move_to(m), them));
531
532   // A non-king move is legal if and only if it is not pinned or it
533   // is moving along the ray towards or away from the king.
534   return (   !bit_is_set(pinned_pieces(us), from)
535           || (direction_between_squares(from, ksq) == direction_between_squares(move_to(m), ksq)));
536 }
537
538
539 /// Position::move_is_check() tests whether a pseudo-legal move is a check
540
541 bool Position::move_is_check(Move m) const {
542
543   assert(is_ok());
544   assert(move_is_ok(m));
545
546   Color us = side_to_move();
547   Color them = opposite_color(us);
548   Square from = move_from(m);
549   Square to = move_to(m);
550   Square ksq = king_square(them);
551   Bitboard dcCandidates = discovered_check_candidates(us);
552
553   assert(color_of_piece_on(from) == us);
554   assert(piece_on(ksq) == piece_of_color_and_type(them, KING));
555
556   // Proceed according to the type of the moving piece
557   switch (type_of_piece_on(from))
558   {
559   case PAWN:
560
561       if (bit_is_set(pawn_attacks(them, ksq), to)) // Normal check?
562           return true;
563
564       if (    bit_is_set(dcCandidates, from)      // Discovered check?
565           && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
566           return true;
567
568       if (move_promotion(m)) // Promotion with check?
569       {
570           Bitboard b = occupied_squares();
571           clear_bit(&b, from);
572
573           switch (move_promotion(m))
574           {
575           case KNIGHT:
576               return bit_is_set(piece_attacks<KNIGHT>(to), ksq);
577           case BISHOP:
578               return bit_is_set(bishop_attacks_bb(to, b), ksq);
579           case ROOK:
580               return bit_is_set(rook_attacks_bb(to, b), ksq);
581           case QUEEN:
582               return bit_is_set(queen_attacks_bb(to, b), ksq);
583           default:
584               assert(false);
585           }
586       }
587       // En passant capture with check?  We have already handled the case
588       // of direct checks and ordinary discovered check, the only case we
589       // need to handle is the unusual case of a discovered check through the
590       // captured pawn.
591       else if (move_is_ep(m))
592       {
593           Square capsq = make_square(square_file(to), square_rank(from));
594           Bitboard b = occupied_squares();
595           clear_bit(&b, from);
596           clear_bit(&b, capsq);
597           set_bit(&b, to);
598           return  (rook_attacks_bb(ksq, b) & rooks_and_queens(us))
599                 ||(bishop_attacks_bb(ksq, b) & bishops_and_queens(us));
600       }
601       return false;
602
603   case KNIGHT:
604     return   bit_is_set(dcCandidates, from)              // Discovered check?
605           || bit_is_set(piece_attacks<KNIGHT>(ksq), to); // Normal check?
606
607   case BISHOP:
608     return   bit_is_set(dcCandidates, from)              // Discovered check?
609           || bit_is_set(piece_attacks<BISHOP>(ksq), to); // Normal check?
610
611   case ROOK:
612     return   bit_is_set(dcCandidates, from)              // Discovered check?
613           || bit_is_set(piece_attacks<ROOK>(ksq), to);   // Normal check?
614
615   case QUEEN:
616       // Discovered checks are impossible!
617       assert(!bit_is_set(dcCandidates, from));
618       return bit_is_set(piece_attacks<QUEEN>(ksq), to);  // Normal check?
619
620   case KING:
621       // Discovered check?
622       if (   bit_is_set(dcCandidates, from)
623           && (direction_between_squares(from, ksq) != direction_between_squares(to, ksq)))
624           return true;
625
626       // Castling with check?
627       if (move_is_castle(m))
628       {
629           Square kfrom, kto, rfrom, rto;
630           Bitboard b = occupied_squares();
631           kfrom = from;
632           rfrom = to;
633
634           if (rfrom > kfrom)
635           {
636               kto = relative_square(us, SQ_G1);
637               rto = relative_square(us, SQ_F1);
638           } else {
639               kto = relative_square(us, SQ_C1);
640               rto = relative_square(us, SQ_D1);
641           }
642           clear_bit(&b, kfrom);
643           clear_bit(&b, rfrom);
644           set_bit(&b, rto);
645           set_bit(&b, kto);
646           return bit_is_set(rook_attacks_bb(rto, b), ksq);
647       }
648       return false;
649
650   default: // NO_PIECE_TYPE
651       break;
652   }
653   assert(false);
654   return false;
655 }
656
657
658 /// Position::move_is_capture() tests whether a move from the current
659 /// position is a capture. Move must not be MOVE_NONE.
660
661 bool Position::move_is_capture(Move m) const {
662
663   assert(m != MOVE_NONE);
664
665   return (   !square_is_empty(move_to(m))
666           && (color_of_piece_on(move_to(m)) != color_of_piece_on(move_from(m)))
667          )
668          || move_is_ep(m);
669 }
670
671
672 /// Position::update_checkers() is a private method to udpate chekers info
673
674 template<PieceType Piece>
675 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
676                                       Square to, Bitboard dcCandidates) {
677
678   if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
679       set_bit(pCheckersBB, to);
680
681   if (Piece != QUEEN && bit_is_set(dcCandidates, from))
682   {
683       if (Piece != ROOK)
684           (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
685
686       if (Piece != BISHOP)
687           (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
688   }
689 }
690
691
692 /// Position::do_move() makes a move, and backs up all information necessary
693 /// to undo the move to an UndoInfo object. The move is assumed to be legal.
694 /// Pseudo-legal moves should be filtered out before this function is called.
695
696 void Position::do_move(Move m, UndoInfo& u) {
697
698   assert(is_ok());
699   assert(move_is_ok(m));
700
701   // Get now the current (pre-move) dc candidates that we will use
702   // in update_checkers().
703   Bitboard oldDcCandidates = discovered_check_candidates(side_to_move());
704
705   // Back up the necessary information to our UndoInfo object (except the
706   // captured piece, which is taken care of later.
707   u = undoInfoUnion;
708   u.capture = NO_PIECE_TYPE;
709
710   // Save the current key to the history[] array, in order to be able to
711   // detect repetition draws.
712   history[gamePly] = key;
713
714   // Increment the 50 moves rule draw counter. Resetting it to zero in the
715   // case of non-reversible moves is taken care of later.
716   rule50++;
717
718   // Reset pinned bitboard and its friends
719   for (Color c = WHITE; c <= BLACK; c++)
720       pinners[c] = pinned[c] = dcCandidates[c] = ~EmptyBoardBB;
721
722   if (move_is_castle(m))
723       do_castle_move(m);
724   else if (move_promotion(m))
725       do_promotion_move(m, u);
726   else if (move_is_ep(m))
727       do_ep_move(m);
728   else
729   {
730     Color us = side_to_move();
731     Color them = opposite_color(us);
732     Square from = move_from(m);
733     Square to = move_to(m);
734
735     assert(color_of_piece_on(from) == us);
736     assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
737
738     PieceType piece = type_of_piece_on(from);
739     PieceType capture = type_of_piece_on(to);
740
741     if (capture)
742     {
743       u.capture = capture;
744       do_capture_move(m, capture, them, to);
745     }
746
747     // Move the piece
748     clear_bit(&(byColorBB[us]), from);
749     clear_bit(&(byTypeBB[piece]), from);
750     clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
751     set_bit(&(byColorBB[us]), to);
752     set_bit(&(byTypeBB[piece]), to);
753     set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
754     board[to] = board[from];
755     board[from] = EMPTY;
756
757     // Update hash key
758     key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
759
760     // Update incremental scores
761     mgValue -= mg_pst(us, piece, from);
762     mgValue += mg_pst(us, piece, to);
763     egValue -= eg_pst(us, piece, from);
764     egValue += eg_pst(us, piece, to);
765
766     // If the moving piece was a king, update the king square
767     if (piece == KING)
768         kingSquare[us] = to;
769
770     // Reset en passant square
771     if (epSquare != SQ_NONE)
772     {
773         key ^= zobEp[epSquare];
774         epSquare = SQ_NONE;
775     }
776
777     // If the moving piece was a pawn do some special extra work
778     if (piece == PAWN)
779     {
780         // Reset rule 50 draw counter
781         rule50 = 0;
782
783         // Update pawn hash key
784         pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
785
786         // Set en passant square, only if moved pawn can be captured
787         if (abs(int(to) - int(from)) == 16)
788         {
789             if (   (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
790                 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
791             {
792                 epSquare = Square((int(from) + int(to)) / 2);
793                 key ^= zobEp[epSquare];
794             }
795         }
796     }
797
798     // Update piece lists
799     pieceList[us][piece][index[from]] = to;
800     index[to] = index[from];
801
802     // Update castle rights
803     key ^= zobCastle[castleRights];
804     castleRights &= castleRightsMask[from];
805     castleRights &= castleRightsMask[to];
806     key ^= zobCastle[castleRights];
807
808     // Update checkers bitboard, piece must be already moved
809     checkersBB = EmptyBoardBB;
810     Square ksq = king_square(them);
811     switch (piece)
812     {
813     case PAWN:   update_checkers<PAWN>(&checkersBB, ksq, from, to, oldDcCandidates);   break;
814     case KNIGHT: update_checkers<KNIGHT>(&checkersBB, ksq, from, to, oldDcCandidates); break;
815     case BISHOP: update_checkers<BISHOP>(&checkersBB, ksq, from, to, oldDcCandidates); break;
816     case ROOK:   update_checkers<ROOK>(&checkersBB, ksq, from, to, oldDcCandidates);   break;
817     case QUEEN:  update_checkers<QUEEN>(&checkersBB, ksq, from, to, oldDcCandidates);  break;
818     case KING:   update_checkers<KING>(&checkersBB, ksq, from, to, oldDcCandidates);   break;
819     default: assert(false); break;
820     }
821   }
822
823   // Finish
824   key ^= zobSideToMove;
825   sideToMove = opposite_color(sideToMove);
826   gamePly++;
827
828   mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
829   egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
830
831   assert(is_ok());
832 }
833
834
835 /// Position::do_capture_move() is a private method used to update captured
836 /// piece info. It is called from the main Position::do_move function.
837
838 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
839
840     assert(capture != KING);
841
842     // Remove captured piece
843     clear_bit(&(byColorBB[them]), to);
844     clear_bit(&(byTypeBB[capture]), to);
845
846     // Update hash key
847     key ^= zobrist[them][capture][to];
848
849     // If the captured piece was a pawn, update pawn hash key
850     if (capture == PAWN)
851         pawnKey ^= zobrist[them][PAWN][to];
852
853     // Update incremental scores
854     mgValue -= mg_pst(them, capture, to);
855     egValue -= eg_pst(them, capture, to);
856
857     assert(!move_promotion(m) || capture != PAWN);
858
859     // Update material
860     if (capture != PAWN)
861         npMaterial[them] -= piece_value_midgame(capture);
862
863     // Update material hash key
864     materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
865
866     // Update piece count
867     pieceCount[them][capture]--;
868
869     // Update piece list
870     pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
871     index[pieceList[them][capture][index[to]]] = index[to];
872
873     // Reset rule 50 counter
874     rule50 = 0;
875 }
876
877
878 /// Position::do_castle_move() is a private method used to make a castling
879 /// move. It is called from the main Position::do_move function. Note that
880 /// castling moves are encoded as "king captures friendly rook" moves, for
881 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
882
883 void Position::do_castle_move(Move m) {
884
885   assert(is_ok());
886   assert(move_is_ok(m));
887   assert(move_is_castle(m));
888
889   Color us = side_to_move();
890   Color them = opposite_color(us);
891
892   // Find source squares for king and rook
893   Square kfrom = move_from(m);
894   Square rfrom = move_to(m);  // HACK: See comment at beginning of function
895   Square kto, rto;
896
897   assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
898   assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
899
900   // Find destination squares for king and rook
901   if (rfrom > kfrom) // O-O
902   {
903       kto = relative_square(us, SQ_G1);
904       rto = relative_square(us, SQ_F1);
905   } else { // O-O-O
906       kto = relative_square(us, SQ_C1);
907       rto = relative_square(us, SQ_D1);
908   }
909
910   // Remove pieces from source squares
911   clear_bit(&(byColorBB[us]), kfrom);
912   clear_bit(&(byTypeBB[KING]), kfrom);
913   clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
914   clear_bit(&(byColorBB[us]), rfrom);
915   clear_bit(&(byTypeBB[ROOK]), rfrom);
916   clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
917
918   // Put pieces on destination squares
919   set_bit(&(byColorBB[us]), kto);
920   set_bit(&(byTypeBB[KING]), kto);
921   set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
922   set_bit(&(byColorBB[us]), rto);
923   set_bit(&(byTypeBB[ROOK]), rto);
924   set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
925
926   // Update board array
927   board[kfrom] = board[rfrom] = EMPTY;
928   board[kto] = piece_of_color_and_type(us, KING);
929   board[rto] = piece_of_color_and_type(us, ROOK);
930
931   // Update king square
932   kingSquare[us] = kto;
933
934   // Update piece lists
935   pieceList[us][KING][index[kfrom]] = kto;
936   pieceList[us][ROOK][index[rfrom]] = rto;
937   int tmp = index[rfrom];
938   index[kto] = index[kfrom];
939   index[rto] = tmp;
940
941   // Update incremental scores
942   mgValue -= mg_pst(us, KING, kfrom);
943   mgValue += mg_pst(us, KING, kto);
944   egValue -= eg_pst(us, KING, kfrom);
945   egValue += eg_pst(us, KING, kto);
946   mgValue -= mg_pst(us, ROOK, rfrom);
947   mgValue += mg_pst(us, ROOK, rto);
948   egValue -= eg_pst(us, ROOK, rfrom);
949   egValue += eg_pst(us, ROOK, rto);
950
951   // Update hash key
952   key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
953   key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
954
955   // Clear en passant square
956   if (epSquare != SQ_NONE)
957   {
958       key ^= zobEp[epSquare];
959       epSquare = SQ_NONE;
960   }
961
962   // Update castling rights
963   key ^= zobCastle[castleRights];
964   castleRights &= castleRightsMask[kfrom];
965   key ^= zobCastle[castleRights];
966
967   // Reset rule 50 counter
968   rule50 = 0;
969
970   // Update checkers BB
971   checkersBB = attacks_to(king_square(them), us);
972 }
973
974
975 /// Position::do_promotion_move() is a private method used to make a promotion
976 /// move. It is called from the main Position::do_move function. The
977 /// UndoInfo object, which has been initialized in Position::do_move, is
978 /// used to store the captured piece (if any).
979
980 void Position::do_promotion_move(Move m, UndoInfo &u) {
981
982   Color us, them;
983   Square from, to;
984   PieceType capture, promotion;
985
986   assert(is_ok());
987   assert(move_is_ok(m));
988   assert(move_promotion(m));
989
990   us = side_to_move();
991   them = opposite_color(us);
992   from = move_from(m);
993   to = move_to(m);
994
995   assert(relative_rank(us, to) == RANK_8);
996   assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
997   assert(color_of_piece_on(to) == them || square_is_empty(to));
998
999   capture = type_of_piece_on(to);
1000
1001   if (capture)
1002   {
1003     u.capture = capture;
1004     do_capture_move(m, capture, them, to);
1005   }
1006
1007   // Remove pawn
1008   clear_bit(&(byColorBB[us]), from);
1009   clear_bit(&(byTypeBB[PAWN]), from);
1010   clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1011   board[from] = EMPTY;
1012
1013   // Insert promoted piece
1014   promotion = move_promotion(m);
1015   assert(promotion >= KNIGHT && promotion <= QUEEN);
1016   set_bit(&(byColorBB[us]), to);
1017   set_bit(&(byTypeBB[promotion]), to);
1018   set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1019   board[to] = piece_of_color_and_type(us, promotion);
1020
1021   // Update hash key
1022   key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1023
1024   // Update pawn hash key
1025   pawnKey ^= zobrist[us][PAWN][from];
1026
1027   // Update material key
1028   materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1029   materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1030
1031   // Update piece counts
1032   pieceCount[us][PAWN]--;
1033   pieceCount[us][promotion]++;
1034
1035   // Update piece lists
1036   pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1037   index[pieceList[us][PAWN][index[from]]] = index[from];
1038   pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1039   index[to] = pieceCount[us][promotion] - 1;
1040
1041   // Update incremental scores
1042   mgValue -= mg_pst(us, PAWN, from);
1043   mgValue += mg_pst(us, promotion, to);
1044   egValue -= eg_pst(us, PAWN, from);
1045   egValue += eg_pst(us, promotion, to);
1046
1047   // Update material
1048   npMaterial[us] += piece_value_midgame(promotion);
1049
1050   // Clear the en passant square
1051   if (epSquare != SQ_NONE)
1052   {
1053       key ^= zobEp[epSquare];
1054       epSquare = SQ_NONE;
1055   }
1056
1057   // Update castle rights
1058   key ^= zobCastle[castleRights];
1059   castleRights &= castleRightsMask[to];
1060   key ^= zobCastle[castleRights];
1061
1062   // Reset rule 50 counter
1063   rule50 = 0;
1064
1065   // Update checkers BB
1066   checkersBB = attacks_to(king_square(them), us);
1067 }
1068
1069
1070 /// Position::do_ep_move() is a private method used to make an en passant
1071 /// capture. It is called from the main Position::do_move function. Because
1072 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1073 /// object in which to store the captured piece.
1074
1075 void Position::do_ep_move(Move m) {
1076
1077   Color us, them;
1078   Square from, to, capsq;
1079
1080   assert(is_ok());
1081   assert(move_is_ok(m));
1082   assert(move_is_ep(m));
1083
1084   us = side_to_move();
1085   them = opposite_color(us);
1086   from = move_from(m);
1087   to = move_to(m);
1088   capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1089
1090   assert(to == epSquare);
1091   assert(relative_rank(us, to) == RANK_6);
1092   assert(piece_on(to) == EMPTY);
1093   assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1094   assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1095
1096   // Remove captured piece
1097   clear_bit(&(byColorBB[them]), capsq);
1098   clear_bit(&(byTypeBB[PAWN]), capsq);
1099   clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1100   board[capsq] = EMPTY;
1101
1102   // Remove moving piece from source square
1103   clear_bit(&(byColorBB[us]), from);
1104   clear_bit(&(byTypeBB[PAWN]), from);
1105   clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1106
1107   // Put moving piece on destination square
1108   set_bit(&(byColorBB[us]), to);
1109   set_bit(&(byTypeBB[PAWN]), to);
1110   set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1111   board[to] = board[from];
1112   board[from] = EMPTY;
1113
1114   // Update material hash key
1115   materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1116
1117   // Update piece count
1118   pieceCount[them][PAWN]--;
1119
1120   // Update piece list
1121   pieceList[us][PAWN][index[from]] = to;
1122   index[to] = index[from];
1123   pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1124   index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1125
1126   // Update hash key
1127   key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1128   key ^= zobrist[them][PAWN][capsq];
1129   key ^= zobEp[epSquare];
1130
1131   // Update pawn hash key
1132   pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1133   pawnKey ^= zobrist[them][PAWN][capsq];
1134
1135   // Update incremental scores
1136   mgValue -= mg_pst(them, PAWN, capsq);
1137   mgValue -= mg_pst(us, PAWN, from);
1138   mgValue += mg_pst(us, PAWN, to);
1139   egValue -= eg_pst(them, PAWN, capsq);
1140   egValue -= eg_pst(us, PAWN, from);
1141   egValue += eg_pst(us, PAWN, to);
1142
1143   // Reset en passant square
1144   epSquare = SQ_NONE;
1145
1146   // Reset rule 50 counter
1147   rule50 = 0;
1148
1149   // Update checkers BB
1150   checkersBB = attacks_to(king_square(them), us);
1151 }
1152
1153
1154 /// Position::undo_move() unmakes a move. When it returns, the position should
1155 /// be restored to exactly the same state as before the move was made. It is
1156 /// important that Position::undo_move is called with the same move and UndoInfo
1157 /// object as the earlier call to Position::do_move.
1158
1159 void Position::undo_move(Move m, const UndoInfo &u) {
1160
1161   assert(is_ok());
1162   assert(move_is_ok(m));
1163
1164   gamePly--;
1165   sideToMove = opposite_color(sideToMove);
1166
1167   // Restore information from our UndoInfo object (except the captured piece,
1168   // which is taken care of later)
1169   undoInfoUnion = u;
1170
1171   if (move_is_castle(m))
1172       undo_castle_move(m);
1173   else if (move_promotion(m))
1174       undo_promotion_move(m, u);
1175   else if (move_is_ep(m))
1176       undo_ep_move(m);
1177   else
1178   {
1179       Color us, them;
1180       Square from, to;
1181       PieceType piece, capture;
1182
1183       us = side_to_move();
1184       them = opposite_color(us);
1185       from = move_from(m);
1186       to = move_to(m);
1187
1188       assert(piece_on(from) == EMPTY);
1189       assert(color_of_piece_on(to) == us);
1190
1191       // Put the piece back at the source square
1192       piece = type_of_piece_on(to);
1193       set_bit(&(byColorBB[us]), from);
1194       set_bit(&(byTypeBB[piece]), from);
1195       set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1196       board[from] = piece_of_color_and_type(us, piece);
1197
1198       // Clear the destination square
1199       clear_bit(&(byColorBB[us]), to);
1200       clear_bit(&(byTypeBB[piece]), to);
1201       clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1202
1203       // If the moving piece was a king, update the king square
1204       if (piece == KING)
1205           kingSquare[us] = from;
1206
1207       // Update piece list
1208       pieceList[us][piece][index[to]] = from;
1209       index[from] = index[to];
1210
1211       capture = u.capture;
1212
1213       if (capture)
1214       {
1215           assert(capture != KING);
1216
1217           // Replace the captured piece
1218           set_bit(&(byColorBB[them]), to);
1219           set_bit(&(byTypeBB[capture]), to);
1220           set_bit(&(byTypeBB[0]), to);
1221           board[to] = piece_of_color_and_type(them, capture);
1222
1223           // Update material
1224           if (capture != PAWN)
1225               npMaterial[them] += piece_value_midgame(capture);
1226
1227           // Update piece list
1228           pieceList[them][capture][pieceCount[them][capture]] = to;
1229           index[to] = pieceCount[them][capture];
1230
1231           // Update piece count
1232           pieceCount[them][capture]++;
1233       } else
1234           board[to] = EMPTY;
1235   }
1236
1237   assert(is_ok());
1238 }
1239
1240
1241 /// Position::undo_castle_move() is a private method used to unmake a castling
1242 /// move. It is called from the main Position::undo_move function. Note that
1243 /// castling moves are encoded as "king captures friendly rook" moves, for
1244 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1245
1246 void Position::undo_castle_move(Move m) {
1247
1248   assert(move_is_ok(m));
1249   assert(move_is_castle(m));
1250
1251   // When we have arrived here, some work has already been done by
1252   // Position::undo_move.  In particular, the side to move has been switched,
1253   // so the code below is correct.
1254   Color us = side_to_move();
1255
1256   // Find source squares for king and rook
1257   Square kfrom = move_from(m);
1258   Square rfrom = move_to(m);  // HACK: See comment at beginning of function
1259   Square kto, rto;
1260
1261   // Find destination squares for king and rook
1262   if (rfrom > kfrom) // O-O
1263   {
1264       kto = relative_square(us, SQ_G1);
1265       rto = relative_square(us, SQ_F1);
1266   } else { // O-O-O
1267       kto = relative_square(us, SQ_C1);
1268       rto = relative_square(us, SQ_D1);
1269   }
1270
1271   assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1272   assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1273
1274   // Remove pieces from destination squares
1275   clear_bit(&(byColorBB[us]), kto);
1276   clear_bit(&(byTypeBB[KING]), kto);
1277   clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1278   clear_bit(&(byColorBB[us]), rto);
1279   clear_bit(&(byTypeBB[ROOK]), rto);
1280   clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1281
1282   // Put pieces on source squares
1283   set_bit(&(byColorBB[us]), kfrom);
1284   set_bit(&(byTypeBB[KING]), kfrom);
1285   set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1286   set_bit(&(byColorBB[us]), rfrom);
1287   set_bit(&(byTypeBB[ROOK]), rfrom);
1288   set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1289
1290   // Update board
1291   board[rto] = board[kto] = EMPTY;
1292   board[rfrom] = piece_of_color_and_type(us, ROOK);
1293   board[kfrom] = piece_of_color_and_type(us, KING);
1294
1295   // Update king square
1296   kingSquare[us] = kfrom;
1297
1298   // Update piece lists
1299   pieceList[us][KING][index[kto]] = kfrom;
1300   pieceList[us][ROOK][index[rto]] = rfrom;
1301   int tmp = index[rto];  // Necessary because we may have rto == kfrom in FRC.
1302   index[kfrom] = index[kto];
1303   index[rfrom] = tmp;
1304 }
1305
1306
1307 /// Position::undo_promotion_move() is a private method used to unmake a
1308 /// promotion move. It is called from the main Position::do_move
1309 /// function. The UndoInfo object, which has been initialized in
1310 /// Position::do_move, is used to put back the captured piece (if any).
1311
1312 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1313
1314   Color us, them;
1315   Square from, to;
1316   PieceType capture, promotion;
1317
1318   assert(move_is_ok(m));
1319   assert(move_promotion(m));
1320
1321   // When we have arrived here, some work has already been done by
1322   // Position::undo_move.  In particular, the side to move has been switched,
1323   // so the code below is correct.
1324   us = side_to_move();
1325   them = opposite_color(us);
1326   from = move_from(m);
1327   to = move_to(m);
1328
1329   assert(relative_rank(us, to) == RANK_8);
1330   assert(piece_on(from) == EMPTY);
1331
1332   // Remove promoted piece
1333   promotion = move_promotion(m);
1334   assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1335   assert(promotion >= KNIGHT && promotion <= QUEEN);
1336   clear_bit(&(byColorBB[us]), to);
1337   clear_bit(&(byTypeBB[promotion]), to);
1338   clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1339
1340   // Insert pawn at source square
1341   set_bit(&(byColorBB[us]), from);
1342   set_bit(&(byTypeBB[PAWN]), from);
1343   set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1344   board[from] = piece_of_color_and_type(us, PAWN);
1345
1346   // Update material
1347   npMaterial[us] -= piece_value_midgame(promotion);
1348
1349   // Update piece list
1350   pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1351   index[from] = pieceCount[us][PAWN];
1352   pieceList[us][promotion][index[to]] =
1353     pieceList[us][promotion][pieceCount[us][promotion] - 1];
1354   index[pieceList[us][promotion][index[to]]] = index[to];
1355
1356   // Update piece counts
1357   pieceCount[us][promotion]--;
1358   pieceCount[us][PAWN]++;
1359
1360   capture = u.capture;
1361
1362   if (capture)
1363   {
1364       assert(capture != KING);
1365
1366       // Insert captured piece:
1367       set_bit(&(byColorBB[them]), to);
1368       set_bit(&(byTypeBB[capture]), to);
1369       set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1370       board[to] = piece_of_color_and_type(them, capture);
1371
1372       // Update material. Because the move is a promotion move, we know
1373       // that the captured piece cannot be a pawn.
1374       assert(capture != PAWN);
1375       npMaterial[them] += piece_value_midgame(capture);
1376
1377       // Update piece list
1378       pieceList[them][capture][pieceCount[them][capture]] = to;
1379       index[to] = pieceCount[them][capture];
1380
1381       // Update piece count
1382       pieceCount[them][capture]++;
1383   } else
1384       board[to] = EMPTY;
1385 }
1386
1387
1388 /// Position::undo_ep_move() is a private method used to unmake an en passant
1389 /// capture. It is called from the main Position::undo_move function.  Because
1390 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1391 /// object from which to retrieve the captured piece.
1392
1393 void Position::undo_ep_move(Move m) {
1394
1395   assert(move_is_ok(m));
1396   assert(move_is_ep(m));
1397
1398   // When we have arrived here, some work has already been done by
1399   // Position::undo_move. In particular, the side to move has been switched,
1400   // so the code below is correct.
1401   Color us = side_to_move();
1402   Color them = opposite_color(us);
1403   Square from = move_from(m);
1404   Square to = move_to(m);
1405   Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1406
1407   assert(to == ep_square());
1408   assert(relative_rank(us, to) == RANK_6);
1409   assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1410   assert(piece_on(from) == EMPTY);
1411   assert(piece_on(capsq) == EMPTY);
1412
1413   // Replace captured piece
1414   set_bit(&(byColorBB[them]), capsq);
1415   set_bit(&(byTypeBB[PAWN]), capsq);
1416   set_bit(&(byTypeBB[0]), capsq);
1417   board[capsq] = piece_of_color_and_type(them, PAWN);
1418
1419   // Remove moving piece from destination square
1420   clear_bit(&(byColorBB[us]), to);
1421   clear_bit(&(byTypeBB[PAWN]), to);
1422   clear_bit(&(byTypeBB[0]), to);
1423   board[to] = EMPTY;
1424
1425   // Replace moving piece at source square
1426   set_bit(&(byColorBB[us]), from);
1427   set_bit(&(byTypeBB[PAWN]), from);
1428   set_bit(&(byTypeBB[0]), from);
1429   board[from] = piece_of_color_and_type(us, PAWN);
1430
1431   // Update piece list:
1432   pieceList[us][PAWN][index[to]] = from;
1433   index[from] = index[to];
1434   pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1435   index[capsq] = pieceCount[them][PAWN];
1436
1437   // Update piece count:
1438   pieceCount[them][PAWN]++;
1439 }
1440
1441
1442 /// Position::do_null_move makes() a "null move": It switches the side to move
1443 /// and updates the hash key without executing any move on the board.
1444
1445 void Position::do_null_move(UndoInfo& u) {
1446
1447   assert(is_ok());
1448   assert(!is_check());
1449
1450   // Back up the information necessary to undo the null move to the supplied
1451   // UndoInfo object.  In the case of a null move, the only thing we need to
1452   // remember is the last move made and the en passant square.
1453   u.lastMove = lastMove;
1454   u.epSquare = epSquare;
1455
1456   // Save the current key to the history[] array, in order to be able to
1457   // detect repetition draws.
1458   history[gamePly] = key;
1459
1460   // Update the necessary information
1461   sideToMove = opposite_color(sideToMove);
1462   if (epSquare != SQ_NONE)
1463       key ^= zobEp[epSquare];
1464
1465   epSquare = SQ_NONE;
1466   rule50++;
1467   gamePly++;
1468   key ^= zobSideToMove;
1469
1470   mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1471   egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1472
1473   assert(is_ok());
1474 }
1475
1476
1477 /// Position::undo_null_move() unmakes a "null move".
1478
1479 void Position::undo_null_move(const UndoInfo &u) {
1480
1481   assert(is_ok());
1482   assert(!is_check());
1483
1484   // Restore information from the supplied UndoInfo object:
1485   lastMove = u.lastMove;
1486   epSquare = u.epSquare;
1487   if (epSquare != SQ_NONE)
1488       key ^= zobEp[epSquare];
1489
1490   // Update the necessary information.
1491   sideToMove = opposite_color(sideToMove);
1492   rule50--;
1493   gamePly--;
1494   key ^= zobSideToMove;
1495
1496   mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1497   egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1498
1499   assert(is_ok());
1500 }
1501
1502
1503 /// Position::see() is a static exchange evaluator: It tries to estimate the
1504 /// material gain or loss resulting from a move.  There are three versions of
1505 /// this function: One which takes a destination square as input, one takes a
1506 /// move, and one which takes a 'from' and a 'to' square. The function does
1507 /// not yet understand promotions captures.
1508
1509 int Position::see(Square to) const {
1510
1511   assert(square_is_ok(to));
1512   return see(SQ_NONE, to);
1513 }
1514
1515 int Position::see(Move m) const {
1516
1517   assert(move_is_ok(m));
1518   return see(move_from(m), move_to(m));
1519 }
1520
1521 int Position::see(Square from, Square to) const {
1522
1523   // Material values
1524   static const int seeValues[18] = {
1525     0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1526        RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1527     0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1528        RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1529     0, 0
1530   };
1531
1532   Bitboard attackers, occ, b;
1533
1534   assert(square_is_ok(from) || from == SQ_NONE);
1535   assert(square_is_ok(to));
1536
1537   // Initialize colors
1538   Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1539   Color them = opposite_color(us);
1540
1541   // Initialize pieces
1542   Piece piece = piece_on(from);
1543   Piece capture = piece_on(to);
1544
1545   // Find all attackers to the destination square, with the moving piece
1546   // removed, but possibly an X-ray attacker added behind it.
1547   occ = occupied_squares();
1548
1549   // Handle en passant moves
1550   if (epSquare == to && type_of_piece_on(from) == PAWN)
1551   {
1552       assert(capture == EMPTY);
1553
1554       Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1555       capture = piece_on(capQq);
1556
1557       assert(type_of_piece_on(capQq) == PAWN);
1558
1559       // Remove the captured pawn
1560       clear_bit(&occ, capQq);
1561   }
1562
1563   while (true)
1564   {
1565       clear_bit(&occ, from);
1566       attackers =  (rook_attacks_bb(to, occ)   & rooks_and_queens())
1567                  | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1568                  | (piece_attacks<KNIGHT>(to)  & knights())
1569                  | (piece_attacks<KING>(to)    & kings())
1570                  | (pawn_attacks(WHITE, to)    & pawns(BLACK))
1571                  | (pawn_attacks(BLACK, to)    & pawns(WHITE));
1572
1573       if (from != SQ_NONE)
1574           break;
1575
1576       // If we don't have any attacker we are finished
1577       if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1578           return 0;
1579
1580       // Locate the least valuable attacker to the destination square
1581       // and use it to initialize from square.
1582       PieceType pt;
1583       for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1584           assert(pt < KING);
1585
1586       from = first_1(attackers & pieces_of_color_and_type(us, pt));
1587       piece = piece_on(from);
1588   }
1589
1590   // If the opponent has no attackers we are finished
1591   if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1592       return seeValues[capture];
1593
1594   attackers &= occ; // Remove the moving piece
1595
1596   // The destination square is defended, which makes things rather more
1597   // difficult to compute. We proceed by building up a "swap list" containing
1598   // the material gain or loss at each stop in a sequence of captures to the
1599   // destination square, where the sides alternately capture, and always
1600   // capture with the least valuable piece. After each capture, we look for
1601   // new X-ray attacks from behind the capturing piece.
1602   int lastCapturingPieceValue = seeValues[piece];
1603   int swapList[32], n = 1;
1604   Color c = them;
1605   PieceType pt;
1606
1607   swapList[0] = seeValues[capture];
1608
1609   do {
1610       // Locate the least valuable attacker for the side to move.  The loop
1611       // below looks like it is potentially infinite, but it isn't. We know
1612       // that the side to move still has at least one attacker left.
1613       for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1614           assert(pt < KING);
1615
1616       // Remove the attacker we just found from the 'attackers' bitboard,
1617       // and scan for new X-ray attacks behind the attacker.
1618       b = attackers & pieces_of_color_and_type(c, pt);
1619       occ ^= (b & -b);
1620       attackers |=  (rook_attacks_bb(to, occ) & rooks_and_queens())
1621                   | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1622
1623       attackers &= occ;
1624
1625       // Add the new entry to the swap list
1626       assert(n < 32);
1627       swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1628       n++;
1629
1630       // Remember the value of the capturing piece, and change the side to move
1631       // before beginning the next iteration
1632       lastCapturingPieceValue = seeValues[pt];
1633       c = opposite_color(c);
1634
1635       // Stop after a king capture
1636       if (pt == KING && (attackers & pieces_of_color(c)))
1637       {
1638           assert(n < 32);
1639           swapList[n++] = 100;
1640           break;
1641       }
1642   } while (attackers & pieces_of_color(c));
1643
1644   // Having built the swap list, we negamax through it to find the best
1645   // achievable score from the point of view of the side to move
1646   while (--n)
1647       swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1648
1649   return swapList[0];
1650 }
1651
1652
1653 /// Position::clear() erases the position object to a pristine state, with an
1654 /// empty board, white to move, and no castling rights.
1655
1656 void Position::clear() {
1657
1658   for (int i = 0; i < 64; i++)
1659   {
1660       board[i] = EMPTY;
1661       index[i] = 0;
1662   }
1663
1664   for (int i = 0; i < 2; i++)
1665       byColorBB[i] = EmptyBoardBB;
1666
1667   for (int i = 0; i < 7; i++)
1668   {
1669       byTypeBB[i] = EmptyBoardBB;
1670       pieceCount[0][i] = pieceCount[1][i] = 0;
1671       for (int j = 0; j < 8; j++)
1672           pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1673   }
1674
1675   checkersBB = EmptyBoardBB;
1676   for (Color c = WHITE; c <= BLACK; c++)
1677       pinners[c] = pinned[c] = dcCandidates[c] = ~EmptyBoardBB;
1678
1679   lastMove = MOVE_NONE;
1680
1681   sideToMove = WHITE;
1682   castleRights = NO_CASTLES;
1683   initialKFile = FILE_E;
1684   initialKRFile = FILE_H;
1685   initialQRFile = FILE_A;
1686   epSquare = SQ_NONE;
1687   rule50 = 0;
1688   gamePly = 0;
1689 }
1690
1691
1692 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1693 /// UCI interface code, whenever a non-reversible move is made in a
1694 /// 'position fen <fen> moves m1 m2 ...' command.  This makes it possible
1695 /// for the program to handle games of arbitrary length, as long as the GUI
1696 /// handles draws by the 50 move rule correctly.
1697
1698 void Position::reset_game_ply() {
1699
1700   gamePly = 0;
1701 }
1702
1703
1704 /// Position::put_piece() puts a piece on the given square of the board,
1705 /// updating the board array, bitboards, and piece counts.
1706
1707 void Position::put_piece(Piece p, Square s) {
1708
1709   Color c = color_of_piece(p);
1710   PieceType pt = type_of_piece(p);
1711
1712   board[s] = p;
1713   index[s] = pieceCount[c][pt];
1714   pieceList[c][pt][index[s]] = s;
1715
1716   set_bit(&(byTypeBB[pt]), s);
1717   set_bit(&(byColorBB[c]), s);
1718   set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1719
1720   pieceCount[c][pt]++;
1721
1722   if (pt == KING)
1723       kingSquare[c] = s;
1724 }
1725
1726
1727 /// Position::allow_oo() gives the given side the right to castle kingside.
1728 /// Used when setting castling rights during parsing of FEN strings.
1729
1730 void Position::allow_oo(Color c) {
1731
1732   castleRights |= (1 + int(c));
1733 }
1734
1735
1736 /// Position::allow_ooo() gives the given side the right to castle queenside.
1737 /// Used when setting castling rights during parsing of FEN strings.
1738
1739 void Position::allow_ooo(Color c) {
1740
1741   castleRights |= (4 + 4*int(c));
1742 }
1743
1744
1745 /// Position::compute_key() computes the hash key of the position. The hash
1746 /// key is usually updated incrementally as moves are made and unmade, the
1747 /// compute_key() function is only used when a new position is set up, and
1748 /// to verify the correctness of the hash key when running in debug mode.
1749
1750 Key Position::compute_key() const {
1751
1752   Key result = Key(0ULL);
1753
1754   for (Square s = SQ_A1; s <= SQ_H8; s++)
1755       if (square_is_occupied(s))
1756           result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1757
1758   if (ep_square() != SQ_NONE)
1759       result ^= zobEp[ep_square()];
1760
1761   result ^= zobCastle[castleRights];
1762   if (side_to_move() == BLACK)
1763       result ^= zobSideToMove;
1764
1765   return result;
1766 }
1767
1768
1769 /// Position::compute_pawn_key() computes the hash key of the position. The
1770 /// hash key is usually updated incrementally as moves are made and unmade,
1771 /// the compute_pawn_key() function is only used when a new position is set
1772 /// up, and to verify the correctness of the pawn hash key when running in
1773 /// debug mode.
1774
1775 Key Position::compute_pawn_key() const {
1776
1777   Key result = Key(0ULL);
1778   Bitboard b;
1779   Square s;
1780
1781   for (Color c = WHITE; c <= BLACK; c++)
1782   {
1783       b = pawns(c);
1784       while(b)
1785       {
1786           s = pop_1st_bit(&b);
1787           result ^= zobrist[c][PAWN][s];
1788       }
1789   }
1790   return result;
1791 }
1792
1793
1794 /// Position::compute_material_key() computes the hash key of the position.
1795 /// The hash key is usually updated incrementally as moves are made and unmade,
1796 /// the compute_material_key() function is only used when a new position is set
1797 /// up, and to verify the correctness of the material hash key when running in
1798 /// debug mode.
1799
1800 Key Position::compute_material_key() const {
1801
1802   Key result = Key(0ULL);
1803   for (Color c = WHITE; c <= BLACK; c++)
1804       for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1805       {
1806           int count = piece_count(c, pt);
1807           for (int i = 0; i <= count; i++)
1808               result ^= zobMaterial[c][pt][i];
1809       }
1810   return result;
1811 }
1812
1813
1814 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1815 /// incremental scores for the middle game and the endgame. These functions
1816 /// are used to initialize the incremental scores when a new position is set
1817 /// up, and to verify that the scores are correctly updated by do_move
1818 /// and undo_move when the program is running in debug mode.
1819
1820 Value Position::compute_mg_value() const {
1821
1822   Value result = Value(0);
1823   Bitboard b;
1824   Square s;
1825
1826   for (Color c = WHITE; c <= BLACK; c++)
1827       for (PieceType pt = PAWN; pt <= KING; pt++)
1828       {
1829           b = pieces_of_color_and_type(c, pt);
1830           while(b)
1831           {
1832               s = pop_1st_bit(&b);
1833               assert(piece_on(s) == piece_of_color_and_type(c, pt));
1834               result += mg_pst(c, pt, s);
1835           }
1836       }
1837   result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1838   return result;
1839 }
1840
1841 Value Position::compute_eg_value() const {
1842
1843   Value result = Value(0);
1844   Bitboard b;
1845   Square s;
1846
1847   for (Color c = WHITE; c <= BLACK; c++)
1848     for (PieceType pt = PAWN; pt <= KING; pt++)
1849     {
1850         b = pieces_of_color_and_type(c, pt);
1851         while(b)
1852         {
1853             s = pop_1st_bit(&b);
1854             assert(piece_on(s) == piece_of_color_and_type(c, pt));
1855             result += eg_pst(c, pt, s);
1856         }
1857     }
1858   result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1859   return result;
1860 }
1861
1862
1863 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1864 /// game material score for the given side. Material scores are updated
1865 /// incrementally during the search, this function is only used while
1866 /// initializing a new Position object.
1867
1868 Value Position::compute_non_pawn_material(Color c) const {
1869
1870   Value result = Value(0);
1871   Square s;
1872
1873   for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1874   {
1875       Bitboard b = pieces_of_color_and_type(c, pt);
1876       while(b)
1877       {
1878           s = pop_1st_bit(&b);
1879           assert(piece_on(s) == piece_of_color_and_type(c, pt));
1880           result += piece_value_midgame(pt);
1881       }
1882   }
1883   return result;
1884 }
1885
1886
1887 /// Position::is_mate() returns true or false depending on whether the
1888 /// side to move is checkmated. Note that this function is currently very
1889 /// slow, and shouldn't be used frequently inside the search.
1890
1891 bool Position::is_mate() const {
1892
1893   if (is_check())
1894   {
1895       MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1896       return mp.get_next_move() == MOVE_NONE;
1897   }
1898   return false;
1899 }
1900
1901
1902 /// Position::is_draw() tests whether the position is drawn by material,
1903 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1904 /// must be done by the search.
1905
1906 bool Position::is_draw() const {
1907
1908   // Draw by material?
1909   if (   !pawns()
1910       && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1911       return true;
1912
1913   // Draw by the 50 moves rule?
1914   if (rule50 > 100 || (rule50 == 100 && !is_check()))
1915       return true;
1916
1917   // Draw by repetition?
1918   for (int i = 2; i < Min(gamePly, rule50); i += 2)
1919       if (history[gamePly - i] == key)
1920           return true;
1921
1922   return false;
1923 }
1924
1925
1926 /// Position::has_mate_threat() tests whether a given color has a mate in one
1927 /// from the current position. This function is quite slow, but it doesn't
1928 /// matter, because it is currently only called from PV nodes, which are rare.
1929
1930 bool Position::has_mate_threat(Color c) {
1931
1932   UndoInfo u1, u2;
1933   Color stm = side_to_move();
1934
1935   // The following lines are useless and silly, but prevents gcc from
1936   // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1937   // be used uninitialized.
1938   u1.lastMove = lastMove;
1939   u1.epSquare = epSquare;
1940
1941   if (is_check())
1942       return false;
1943
1944   // If the input color is not equal to the side to move, do a null move
1945   if (c != stm)
1946       do_null_move(u1);
1947
1948   MoveStack mlist[120];
1949   int count;
1950   bool result = false;
1951
1952   // Generate legal moves
1953   count = generate_legal_moves(*this, mlist);
1954
1955   // Loop through the moves, and see if one of them is mate
1956   for (int i = 0; i < count; i++)
1957   {
1958       do_move(mlist[i].move, u2);
1959       if (is_mate())
1960           result = true;
1961
1962       undo_move(mlist[i].move, u2);
1963   }
1964
1965   // Undo null move, if necessary
1966   if (c != stm)
1967       undo_null_move(u1);
1968
1969   return result;
1970 }
1971
1972
1973 /// Position::init_zobrist() is a static member function which initializes the
1974 /// various arrays used to compute hash keys.
1975
1976 void Position::init_zobrist() {
1977
1978   for (int i = 0; i < 2; i++)
1979       for (int j = 0; j < 8; j++)
1980           for (int k = 0; k < 64; k++)
1981               zobrist[i][j][k] = Key(genrand_int64());
1982
1983   for (int i = 0; i < 64; i++)
1984       zobEp[i] = Key(genrand_int64());
1985
1986   for (int i = 0; i < 16; i++)
1987       zobCastle[i] = genrand_int64();
1988
1989   zobSideToMove = genrand_int64();
1990
1991   for (int i = 0; i < 2; i++)
1992       for (int j = 0; j < 8; j++)
1993           for (int k = 0; k < 16; k++)
1994               zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1995
1996   for (int i = 0; i < 16; i++)
1997       zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1998 }
1999
2000
2001 /// Position::init_piece_square_tables() initializes the piece square tables.
2002 /// This is a two-step operation:  First, the white halves of the tables are
2003 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2004 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2005 /// Second, the black halves of the tables are initialized by mirroring
2006 /// and changing the sign of the corresponding white scores.
2007
2008 void Position::init_piece_square_tables() {
2009
2010   int r = get_option_value_int("Randomness"), i;
2011   for (Square s = SQ_A1; s <= SQ_H8; s++)
2012       for (Piece p = WP; p <= WK; p++)
2013       {
2014           i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2015           MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2016           EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2017       }
2018
2019   for (Square s = SQ_A1; s <= SQ_H8; s++)
2020       for (Piece p = BP; p <= BK; p++)
2021       {
2022           MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2023           EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2024       }
2025 }
2026
2027
2028 /// Position::flipped_copy() makes a copy of the input position, but with
2029 /// the white and black sides reversed. This is only useful for debugging,
2030 /// especially for finding evaluation symmetry bugs.
2031
2032 void Position::flipped_copy(const Position &pos) {
2033
2034   assert(pos.is_ok());
2035
2036   clear();
2037
2038   // Board
2039   for (Square s = SQ_A1; s <= SQ_H8; s++)
2040       if (!pos.square_is_empty(s))
2041           put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2042
2043   // Side to move
2044   sideToMove = opposite_color(pos.side_to_move());
2045
2046   // Castling rights
2047   if (pos.can_castle_kingside(WHITE))  allow_oo(BLACK);
2048   if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2049   if (pos.can_castle_kingside(BLACK))  allow_oo(WHITE);
2050   if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2051
2052   initialKFile  = pos.initialKFile;
2053   initialKRFile = pos.initialKRFile;
2054   initialQRFile = pos.initialQRFile;
2055
2056   for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2057       castleRightsMask[sq] = ALL_CASTLES;
2058
2059   castleRightsMask[make_square(initialKFile,  RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2060   castleRightsMask[make_square(initialKFile,  RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2061   castleRightsMask[make_square(initialKRFile, RANK_1)] ^=  WHITE_OO;
2062   castleRightsMask[make_square(initialKRFile, RANK_8)] ^=  BLACK_OO;
2063   castleRightsMask[make_square(initialQRFile, RANK_1)] ^=  WHITE_OOO;
2064   castleRightsMask[make_square(initialQRFile, RANK_8)] ^=  BLACK_OOO;
2065
2066   // En passant square
2067   if (pos.epSquare != SQ_NONE)
2068       epSquare = flip_square(pos.epSquare);
2069
2070   // Checkers
2071   find_checkers();
2072
2073   // Hash keys
2074   key = compute_key();
2075   pawnKey = compute_pawn_key();
2076   materialKey = compute_material_key();
2077
2078   // Incremental scores
2079   mgValue = compute_mg_value();
2080   egValue = compute_eg_value();
2081
2082   // Material
2083   npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2084   npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2085
2086   assert(is_ok());
2087 }
2088
2089
2090 /// Position::is_ok() performs some consitency checks for the position object.
2091 /// This is meant to be helpful when debugging.
2092
2093 bool Position::is_ok(int* failedStep) const {
2094
2095   // What features of the position should be verified?
2096   static const bool debugBitboards = false;
2097   static const bool debugKingCount = false;
2098   static const bool debugKingCapture = false;
2099   static const bool debugCheckerCount = false;
2100   static const bool debugKey = false;
2101   static const bool debugMaterialKey = false;
2102   static const bool debugPawnKey = false;
2103   static const bool debugIncrementalEval = false;
2104   static const bool debugNonPawnMaterial = false;
2105   static const bool debugPieceCounts = false;
2106   static const bool debugPieceList = false;
2107
2108   if (failedStep) *failedStep = 1;
2109
2110   // Side to move OK?
2111   if (!color_is_ok(side_to_move()))
2112       return false;
2113
2114   // Are the king squares in the position correct?
2115   if (failedStep) (*failedStep)++;
2116   if (piece_on(king_square(WHITE)) != WK)
2117       return false;
2118
2119   if (failedStep) (*failedStep)++;
2120   if (piece_on(king_square(BLACK)) != BK)
2121       return false;
2122
2123   // Castle files OK?
2124   if (failedStep) (*failedStep)++;
2125   if (!file_is_ok(initialKRFile))
2126       return false;
2127
2128   if (!file_is_ok(initialQRFile))
2129       return false;
2130
2131   // Do both sides have exactly one king?
2132   if (failedStep) (*failedStep)++;
2133   if (debugKingCount)
2134   {
2135       int kingCount[2] = {0, 0};
2136       for (Square s = SQ_A1; s <= SQ_H8; s++)
2137           if (type_of_piece_on(s) == KING)
2138               kingCount[color_of_piece_on(s)]++;
2139
2140       if (kingCount[0] != 1 || kingCount[1] != 1)
2141           return false;
2142   }
2143
2144   // Can the side to move capture the opponent's king?
2145   if (failedStep) (*failedStep)++;
2146   if (debugKingCapture)
2147   {
2148       Color us = side_to_move();
2149       Color them = opposite_color(us);
2150       Square ksq = king_square(them);
2151       if (square_is_attacked(ksq, us))
2152           return false;
2153   }
2154
2155   // Is there more than 2 checkers?
2156   if (failedStep) (*failedStep)++;
2157   if (debugCheckerCount && count_1s(checkersBB) > 2)
2158       return false;
2159
2160   // Bitboards OK?
2161   if (failedStep) (*failedStep)++;
2162   if (debugBitboards)
2163   {
2164       // The intersection of the white and black pieces must be empty
2165       if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2166           return false;
2167
2168       // The union of the white and black pieces must be equal to all
2169       // occupied squares
2170       if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2171           return false;
2172
2173       // Separate piece type bitboards must have empty intersections
2174       for (PieceType p1 = PAWN; p1 <= KING; p1++)
2175           for (PieceType p2 = PAWN; p2 <= KING; p2++)
2176               if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2177                   return false;
2178   }
2179
2180   // En passant square OK?
2181   if (failedStep) (*failedStep)++;
2182   if (ep_square() != SQ_NONE)
2183   {
2184       // The en passant square must be on rank 6, from the point of view of the
2185       // side to move.
2186       if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2187           return false;
2188   }
2189
2190   // Hash key OK?
2191   if (failedStep) (*failedStep)++;
2192   if (debugKey && key != compute_key())
2193       return false;
2194
2195   // Pawn hash key OK?
2196   if (failedStep) (*failedStep)++;
2197   if (debugPawnKey && pawnKey != compute_pawn_key())
2198       return false;
2199
2200   // Material hash key OK?
2201   if (failedStep) (*failedStep)++;
2202   if (debugMaterialKey && materialKey != compute_material_key())
2203       return false;
2204
2205   // Incremental eval OK?
2206   if (failedStep) (*failedStep)++;
2207   if (debugIncrementalEval)
2208   {
2209       if (mgValue != compute_mg_value())
2210           return false;
2211
2212       if (egValue != compute_eg_value())
2213           return false;
2214   }
2215
2216   // Non-pawn material OK?
2217   if (failedStep) (*failedStep)++;
2218   if (debugNonPawnMaterial)
2219   {
2220       if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2221           return false;
2222
2223       if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2224           return false;
2225   }
2226
2227   // Piece counts OK?
2228   if (failedStep) (*failedStep)++;
2229   if (debugPieceCounts)
2230       for (Color c = WHITE; c <= BLACK; c++)
2231           for (PieceType pt = PAWN; pt <= KING; pt++)
2232               if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2233                   return false;
2234
2235   if (failedStep) (*failedStep)++;
2236   if (debugPieceList)
2237   {
2238       for(Color c = WHITE; c <= BLACK; c++)
2239           for(PieceType pt = PAWN; pt <= KING; pt++)
2240               for(int i = 0; i < pieceCount[c][pt]; i++)
2241               {
2242                   if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2243                       return false;
2244
2245                   if (index[piece_list(c, pt, i)] != i)
2246                       return false;
2247               }
2248   }
2249   if (failedStep) *failedStep = 0;
2250   return true;
2251 }