]> git.sesse.net Git - stockfish/blob - src/position.cpp
c6c315271f1f27a79ccf15ea616564127e6be4fd
[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_value<MidGame>();
214   egValue = compute_value<EndGame>();
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   previous = &u;
710
711   // Save the current key to the history[] array, in order to be able to
712   // detect repetition draws.
713   history[gamePly] = key;
714
715   // Increment the 50 moves rule draw counter. Resetting it to zero in the
716   // case of non-reversible moves is taken care of later.
717   rule50++;
718
719   // Reset pinned bitboard and its friends
720   for (Color c = WHITE; c <= BLACK; c++)
721       pinners[c] = pinned[c] = dcCandidates[c] = ~EmptyBoardBB;
722
723   if (move_is_castle(m))
724       do_castle_move(m);
725   else if (move_promotion(m))
726       do_promotion_move(m);
727   else if (move_is_ep(m))
728       do_ep_move(m);
729   else
730   {
731     Color us = side_to_move();
732     Color them = opposite_color(us);
733     Square from = move_from(m);
734     Square to = move_to(m);
735
736     assert(color_of_piece_on(from) == us);
737     assert(color_of_piece_on(to) == them || piece_on(to) == EMPTY);
738
739     PieceType piece = type_of_piece_on(from);
740     PieceType capture = type_of_piece_on(to);
741
742     if (capture)
743     {
744       u.capture = capture;
745       do_capture_move(m, capture, them, to);
746     }
747
748     // Move the piece
749     clear_bit(&(byColorBB[us]), from);
750     clear_bit(&(byTypeBB[piece]), from);
751     clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
752     set_bit(&(byColorBB[us]), to);
753     set_bit(&(byTypeBB[piece]), to);
754     set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
755     board[to] = board[from];
756     board[from] = EMPTY;
757
758     // Update hash key
759     key ^= zobrist[us][piece][from] ^ zobrist[us][piece][to];
760
761     // Update incremental scores
762     mgValue -= pst<MidGame>(us, piece, from);
763     mgValue += pst<MidGame>(us, piece, to);
764     egValue -= pst<EndGame>(us, piece, from);
765     egValue += pst<EndGame>(us, piece, to);
766
767     // If the moving piece was a king, update the king square
768     if (piece == KING)
769         kingSquare[us] = to;
770
771     // Reset en passant square
772     if (epSquare != SQ_NONE)
773     {
774         key ^= zobEp[epSquare];
775         epSquare = SQ_NONE;
776     }
777
778     // If the moving piece was a pawn do some special extra work
779     if (piece == PAWN)
780     {
781         // Reset rule 50 draw counter
782         rule50 = 0;
783
784         // Update pawn hash key
785         pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
786
787         // Set en passant square, only if moved pawn can be captured
788         if (abs(int(to) - int(from)) == 16)
789         {
790             if (   (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
791                 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
792             {
793                 epSquare = Square((int(from) + int(to)) / 2);
794                 key ^= zobEp[epSquare];
795             }
796         }
797     }
798
799     // Update piece lists
800     pieceList[us][piece][index[from]] = to;
801     index[to] = index[from];
802
803     // Update castle rights
804     key ^= zobCastle[castleRights];
805     castleRights &= castleRightsMask[from];
806     castleRights &= castleRightsMask[to];
807     key ^= zobCastle[castleRights];
808
809     // Update checkers bitboard, piece must be already moved
810     checkersBB = EmptyBoardBB;
811     Square ksq = king_square(them);
812     switch (piece)
813     {
814     case PAWN:   update_checkers<PAWN>(&checkersBB, ksq, from, to, oldDcCandidates);   break;
815     case KNIGHT: update_checkers<KNIGHT>(&checkersBB, ksq, from, to, oldDcCandidates); break;
816     case BISHOP: update_checkers<BISHOP>(&checkersBB, ksq, from, to, oldDcCandidates); break;
817     case ROOK:   update_checkers<ROOK>(&checkersBB, ksq, from, to, oldDcCandidates);   break;
818     case QUEEN:  update_checkers<QUEEN>(&checkersBB, ksq, from, to, oldDcCandidates);  break;
819     case KING:   update_checkers<KING>(&checkersBB, ksq, from, to, oldDcCandidates);   break;
820     default: assert(false); break;
821     }
822   }
823
824   // Finish
825   key ^= zobSideToMove;
826   sideToMove = opposite_color(sideToMove);
827   gamePly++;
828
829   mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
830   egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
831
832   assert(is_ok());
833 }
834
835
836 /// Position::do_capture_move() is a private method used to update captured
837 /// piece info. It is called from the main Position::do_move function.
838
839 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
840
841     assert(capture != KING);
842
843     // Remove captured piece
844     clear_bit(&(byColorBB[them]), to);
845     clear_bit(&(byTypeBB[capture]), to);
846
847     // Update hash key
848     key ^= zobrist[them][capture][to];
849
850     // If the captured piece was a pawn, update pawn hash key
851     if (capture == PAWN)
852         pawnKey ^= zobrist[them][PAWN][to];
853
854     // Update incremental scores
855     mgValue -= pst<MidGame>(them, capture, to);
856     egValue -= pst<EndGame>(them, capture, to);
857
858     assert(!move_promotion(m) || capture != PAWN);
859
860     // Update material
861     if (capture != PAWN)
862         npMaterial[them] -= piece_value_midgame(capture);
863
864     // Update material hash key
865     materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
866
867     // Update piece count
868     pieceCount[them][capture]--;
869
870     // Update piece list
871     pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
872     index[pieceList[them][capture][index[to]]] = index[to];
873
874     // Reset rule 50 counter
875     rule50 = 0;
876 }
877
878
879 /// Position::do_castle_move() is a private method used to make a castling
880 /// move. It is called from the main Position::do_move function. Note that
881 /// castling moves are encoded as "king captures friendly rook" moves, for
882 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
883
884 void Position::do_castle_move(Move m) {
885
886   assert(is_ok());
887   assert(move_is_ok(m));
888   assert(move_is_castle(m));
889
890   Color us = side_to_move();
891   Color them = opposite_color(us);
892
893   // Find source squares for king and rook
894   Square kfrom = move_from(m);
895   Square rfrom = move_to(m);  // HACK: See comment at beginning of function
896   Square kto, rto;
897
898   assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
899   assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
900
901   // Find destination squares for king and rook
902   if (rfrom > kfrom) // O-O
903   {
904       kto = relative_square(us, SQ_G1);
905       rto = relative_square(us, SQ_F1);
906   } else { // O-O-O
907       kto = relative_square(us, SQ_C1);
908       rto = relative_square(us, SQ_D1);
909   }
910
911   // Remove pieces from source squares
912   clear_bit(&(byColorBB[us]), kfrom);
913   clear_bit(&(byTypeBB[KING]), kfrom);
914   clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
915   clear_bit(&(byColorBB[us]), rfrom);
916   clear_bit(&(byTypeBB[ROOK]), rfrom);
917   clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
918
919   // Put pieces on destination squares
920   set_bit(&(byColorBB[us]), kto);
921   set_bit(&(byTypeBB[KING]), kto);
922   set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
923   set_bit(&(byColorBB[us]), rto);
924   set_bit(&(byTypeBB[ROOK]), rto);
925   set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
926
927   // Update board array
928   board[kfrom] = board[rfrom] = EMPTY;
929   board[kto] = piece_of_color_and_type(us, KING);
930   board[rto] = piece_of_color_and_type(us, ROOK);
931
932   // Update king square
933   kingSquare[us] = kto;
934
935   // Update piece lists
936   pieceList[us][KING][index[kfrom]] = kto;
937   pieceList[us][ROOK][index[rfrom]] = rto;
938   int tmp = index[rfrom];
939   index[kto] = index[kfrom];
940   index[rto] = tmp;
941
942   // Update incremental scores
943   mgValue -= pst<MidGame>(us, KING, kfrom);
944   mgValue += pst<MidGame>(us, KING, kto);
945   egValue -= pst<EndGame>(us, KING, kfrom);
946   egValue += pst<EndGame>(us, KING, kto);
947   mgValue -= pst<MidGame>(us, ROOK, rfrom);
948   mgValue += pst<MidGame>(us, ROOK, rto);
949   egValue -= pst<EndGame>(us, ROOK, rfrom);
950   egValue += pst<EndGame>(us, ROOK, rto);
951
952   // Update hash key
953   key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
954   key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
955
956   // Clear en passant square
957   if (epSquare != SQ_NONE)
958   {
959       key ^= zobEp[epSquare];
960       epSquare = SQ_NONE;
961   }
962
963   // Update castling rights
964   key ^= zobCastle[castleRights];
965   castleRights &= castleRightsMask[kfrom];
966   key ^= zobCastle[castleRights];
967
968   // Reset rule 50 counter
969   rule50 = 0;
970
971   // Update checkers BB
972   checkersBB = attacks_to(king_square(them), us);
973 }
974
975
976 /// Position::do_promotion_move() is a private method used to make a promotion
977 /// move. It is called from the main Position::do_move function. The
978 /// UndoInfo object, which has been initialized in Position::do_move, is
979 /// used to store the captured piece (if any).
980
981 void Position::do_promotion_move(Move m) {
982
983   Color us, them;
984   Square from, to;
985   PieceType capture, promotion;
986
987   assert(is_ok());
988   assert(move_is_ok(m));
989   assert(move_promotion(m));
990
991   us = side_to_move();
992   them = opposite_color(us);
993   from = move_from(m);
994   to = move_to(m);
995
996   assert(relative_rank(us, to) == RANK_8);
997   assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
998   assert(color_of_piece_on(to) == them || square_is_empty(to));
999
1000   capture = type_of_piece_on(to);
1001
1002   if (capture)
1003   {
1004     previous->capture = capture;
1005     do_capture_move(m, capture, them, to);
1006   }
1007
1008   // Remove pawn
1009   clear_bit(&(byColorBB[us]), from);
1010   clear_bit(&(byTypeBB[PAWN]), from);
1011   clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1012   board[from] = EMPTY;
1013
1014   // Insert promoted piece
1015   promotion = move_promotion(m);
1016   assert(promotion >= KNIGHT && promotion <= QUEEN);
1017   set_bit(&(byColorBB[us]), to);
1018   set_bit(&(byTypeBB[promotion]), to);
1019   set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1020   board[to] = piece_of_color_and_type(us, promotion);
1021
1022   // Update hash key
1023   key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1024
1025   // Update pawn hash key
1026   pawnKey ^= zobrist[us][PAWN][from];
1027
1028   // Update material key
1029   materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1030   materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1031
1032   // Update piece counts
1033   pieceCount[us][PAWN]--;
1034   pieceCount[us][promotion]++;
1035
1036   // Update piece lists
1037   pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1038   index[pieceList[us][PAWN][index[from]]] = index[from];
1039   pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1040   index[to] = pieceCount[us][promotion] - 1;
1041
1042   // Update incremental scores
1043   mgValue -= pst<MidGame>(us, PAWN, from);
1044   mgValue += pst<MidGame>(us, promotion, to);
1045   egValue -= pst<EndGame>(us, PAWN, from);
1046   egValue += pst<EndGame>(us, promotion, to);
1047
1048   // Update material
1049   npMaterial[us] += piece_value_midgame(promotion);
1050
1051   // Clear the en passant square
1052   if (epSquare != SQ_NONE)
1053   {
1054       key ^= zobEp[epSquare];
1055       epSquare = SQ_NONE;
1056   }
1057
1058   // Update castle rights
1059   key ^= zobCastle[castleRights];
1060   castleRights &= castleRightsMask[to];
1061   key ^= zobCastle[castleRights];
1062
1063   // Reset rule 50 counter
1064   rule50 = 0;
1065
1066   // Update checkers BB
1067   checkersBB = attacks_to(king_square(them), us);
1068 }
1069
1070
1071 /// Position::do_ep_move() is a private method used to make an en passant
1072 /// capture. It is called from the main Position::do_move function. Because
1073 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1074 /// object in which to store the captured piece.
1075
1076 void Position::do_ep_move(Move m) {
1077
1078   Color us, them;
1079   Square from, to, capsq;
1080
1081   assert(is_ok());
1082   assert(move_is_ok(m));
1083   assert(move_is_ep(m));
1084
1085   us = side_to_move();
1086   them = opposite_color(us);
1087   from = move_from(m);
1088   to = move_to(m);
1089   capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1090
1091   assert(to == epSquare);
1092   assert(relative_rank(us, to) == RANK_6);
1093   assert(piece_on(to) == EMPTY);
1094   assert(piece_on(from) == piece_of_color_and_type(us, PAWN));
1095   assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
1096
1097   // Remove captured piece
1098   clear_bit(&(byColorBB[them]), capsq);
1099   clear_bit(&(byTypeBB[PAWN]), capsq);
1100   clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1101   board[capsq] = EMPTY;
1102
1103   // Remove moving piece from source square
1104   clear_bit(&(byColorBB[us]), from);
1105   clear_bit(&(byTypeBB[PAWN]), from);
1106   clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1107
1108   // Put moving piece on destination square
1109   set_bit(&(byColorBB[us]), to);
1110   set_bit(&(byTypeBB[PAWN]), to);
1111   set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1112   board[to] = board[from];
1113   board[from] = EMPTY;
1114
1115   // Update material hash key
1116   materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1117
1118   // Update piece count
1119   pieceCount[them][PAWN]--;
1120
1121   // Update piece list
1122   pieceList[us][PAWN][index[from]] = to;
1123   index[to] = index[from];
1124   pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1125   index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1126
1127   // Update hash key
1128   key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1129   key ^= zobrist[them][PAWN][capsq];
1130   key ^= zobEp[epSquare];
1131
1132   // Update pawn hash key
1133   pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1134   pawnKey ^= zobrist[them][PAWN][capsq];
1135
1136   // Update incremental scores
1137   mgValue -= pst<MidGame>(them, PAWN, capsq);
1138   mgValue -= pst<MidGame>(us, PAWN, from);
1139   mgValue += pst<MidGame>(us, PAWN, to);
1140   egValue -= pst<EndGame>(them, PAWN, capsq);
1141   egValue -= pst<EndGame>(us, PAWN, from);
1142   egValue += pst<EndGame>(us, PAWN, to);
1143
1144   // Reset en passant square
1145   epSquare = SQ_NONE;
1146
1147   // Reset rule 50 counter
1148   rule50 = 0;
1149
1150   // Update checkers BB
1151   checkersBB = attacks_to(king_square(them), us);
1152 }
1153
1154
1155 /// Position::undo_move() unmakes a move. When it returns, the position should
1156 /// be restored to exactly the same state as before the move was made. It is
1157 /// important that Position::undo_move is called with the same move and UndoInfo
1158 /// object as the earlier call to Position::do_move.
1159
1160 void Position::undo_move(Move m) {
1161
1162   assert(is_ok());
1163   assert(move_is_ok(m));
1164
1165   gamePly--;
1166   sideToMove = opposite_color(sideToMove);
1167
1168   // Restore information from our UndoInfo object (except the captured piece,
1169   // which is taken care of later)
1170   undoInfoUnion = *previous;
1171
1172   if (move_is_castle(m))
1173       undo_castle_move(m);
1174   else if (move_promotion(m))
1175       undo_promotion_move(m);
1176   else if (move_is_ep(m))
1177       undo_ep_move(m);
1178   else
1179   {
1180       Color us, them;
1181       Square from, to;
1182       PieceType piece;
1183
1184       us = side_to_move();
1185       them = opposite_color(us);
1186       from = move_from(m);
1187       to = move_to(m);
1188
1189       assert(piece_on(from) == EMPTY);
1190       assert(color_of_piece_on(to) == us);
1191
1192       // Put the piece back at the source square
1193       piece = type_of_piece_on(to);
1194       set_bit(&(byColorBB[us]), from);
1195       set_bit(&(byTypeBB[piece]), from);
1196       set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1197       board[from] = piece_of_color_and_type(us, piece);
1198
1199       // Clear the destination square
1200       clear_bit(&(byColorBB[us]), to);
1201       clear_bit(&(byTypeBB[piece]), to);
1202       clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1203
1204       // If the moving piece was a king, update the king square
1205       if (piece == KING)
1206           kingSquare[us] = from;
1207
1208       // Update piece list
1209       pieceList[us][piece][index[to]] = from;
1210       index[from] = index[to];
1211
1212       if (capture)
1213       {
1214           assert(capture != KING);
1215
1216           // Replace the captured piece
1217           set_bit(&(byColorBB[them]), to);
1218           set_bit(&(byTypeBB[capture]), to);
1219           set_bit(&(byTypeBB[0]), to);
1220           board[to] = piece_of_color_and_type(them, capture);
1221
1222           // Update material
1223           if (capture != PAWN)
1224               npMaterial[them] += piece_value_midgame(capture);
1225
1226           // Update piece list
1227           pieceList[them][capture][pieceCount[them][capture]] = to;
1228           index[to] = pieceCount[them][capture];
1229
1230           // Update piece count
1231           pieceCount[them][capture]++;
1232       } else
1233           board[to] = EMPTY;
1234   }
1235
1236   assert(is_ok());
1237 }
1238
1239
1240 /// Position::undo_castle_move() is a private method used to unmake a castling
1241 /// move. It is called from the main Position::undo_move function. Note that
1242 /// castling moves are encoded as "king captures friendly rook" moves, for
1243 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1244
1245 void Position::undo_castle_move(Move m) {
1246
1247   assert(move_is_ok(m));
1248   assert(move_is_castle(m));
1249
1250   // When we have arrived here, some work has already been done by
1251   // Position::undo_move.  In particular, the side to move has been switched,
1252   // so the code below is correct.
1253   Color us = side_to_move();
1254
1255   // Find source squares for king and rook
1256   Square kfrom = move_from(m);
1257   Square rfrom = move_to(m);  // HACK: See comment at beginning of function
1258   Square kto, rto;
1259
1260   // Find destination squares for king and rook
1261   if (rfrom > kfrom) // O-O
1262   {
1263       kto = relative_square(us, SQ_G1);
1264       rto = relative_square(us, SQ_F1);
1265   } else { // O-O-O
1266       kto = relative_square(us, SQ_C1);
1267       rto = relative_square(us, SQ_D1);
1268   }
1269
1270   assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1271   assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1272
1273   // Remove pieces from destination squares
1274   clear_bit(&(byColorBB[us]), kto);
1275   clear_bit(&(byTypeBB[KING]), kto);
1276   clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1277   clear_bit(&(byColorBB[us]), rto);
1278   clear_bit(&(byTypeBB[ROOK]), rto);
1279   clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1280
1281   // Put pieces on source squares
1282   set_bit(&(byColorBB[us]), kfrom);
1283   set_bit(&(byTypeBB[KING]), kfrom);
1284   set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1285   set_bit(&(byColorBB[us]), rfrom);
1286   set_bit(&(byTypeBB[ROOK]), rfrom);
1287   set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1288
1289   // Update board
1290   board[rto] = board[kto] = EMPTY;
1291   board[rfrom] = piece_of_color_and_type(us, ROOK);
1292   board[kfrom] = piece_of_color_and_type(us, KING);
1293
1294   // Update king square
1295   kingSquare[us] = kfrom;
1296
1297   // Update piece lists
1298   pieceList[us][KING][index[kto]] = kfrom;
1299   pieceList[us][ROOK][index[rto]] = rfrom;
1300   int tmp = index[rto];  // Necessary because we may have rto == kfrom in FRC.
1301   index[kfrom] = index[kto];
1302   index[rfrom] = tmp;
1303 }
1304
1305
1306 /// Position::undo_promotion_move() is a private method used to unmake a
1307 /// promotion move. It is called from the main Position::do_move
1308 /// function. The UndoInfo object, which has been initialized in
1309 /// Position::do_move, is used to put back the captured piece (if any).
1310
1311 void Position::undo_promotion_move(Move m) {
1312
1313   Color us, them;
1314   Square from, to;
1315   PieceType promotion;
1316
1317   assert(move_is_ok(m));
1318   assert(move_promotion(m));
1319
1320   // When we have arrived here, some work has already been done by
1321   // Position::undo_move.  In particular, the side to move has been switched,
1322   // so the code below is correct.
1323   us = side_to_move();
1324   them = opposite_color(us);
1325   from = move_from(m);
1326   to = move_to(m);
1327
1328   assert(relative_rank(us, to) == RANK_8);
1329   assert(piece_on(from) == EMPTY);
1330
1331   // Remove promoted piece
1332   promotion = move_promotion(m);
1333   assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1334   assert(promotion >= KNIGHT && promotion <= QUEEN);
1335   clear_bit(&(byColorBB[us]), to);
1336   clear_bit(&(byTypeBB[promotion]), to);
1337   clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1338
1339   // Insert pawn at source square
1340   set_bit(&(byColorBB[us]), from);
1341   set_bit(&(byTypeBB[PAWN]), from);
1342   set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1343   board[from] = piece_of_color_and_type(us, PAWN);
1344
1345   // Update material
1346   npMaterial[us] -= piece_value_midgame(promotion);
1347
1348   // Update piece list
1349   pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1350   index[from] = pieceCount[us][PAWN];
1351   pieceList[us][promotion][index[to]] =
1352     pieceList[us][promotion][pieceCount[us][promotion] - 1];
1353   index[pieceList[us][promotion][index[to]]] = index[to];
1354
1355   // Update piece counts
1356   pieceCount[us][promotion]--;
1357   pieceCount[us][PAWN]++;
1358
1359   if (capture)
1360   {
1361       assert(capture != KING);
1362
1363       // Insert captured piece:
1364       set_bit(&(byColorBB[them]), to);
1365       set_bit(&(byTypeBB[capture]), to);
1366       set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1367       board[to] = piece_of_color_and_type(them, capture);
1368
1369       // Update material. Because the move is a promotion move, we know
1370       // that the captured piece cannot be a pawn.
1371       assert(capture != PAWN);
1372       npMaterial[them] += piece_value_midgame(capture);
1373
1374       // Update piece list
1375       pieceList[them][capture][pieceCount[them][capture]] = to;
1376       index[to] = pieceCount[them][capture];
1377
1378       // Update piece count
1379       pieceCount[them][capture]++;
1380   } else
1381       board[to] = EMPTY;
1382 }
1383
1384
1385 /// Position::undo_ep_move() is a private method used to unmake an en passant
1386 /// capture. It is called from the main Position::undo_move function.  Because
1387 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1388 /// object from which to retrieve the captured piece.
1389
1390 void Position::undo_ep_move(Move m) {
1391
1392   assert(move_is_ok(m));
1393   assert(move_is_ep(m));
1394
1395   // When we have arrived here, some work has already been done by
1396   // Position::undo_move. In particular, the side to move has been switched,
1397   // so the code below is correct.
1398   Color us = side_to_move();
1399   Color them = opposite_color(us);
1400   Square from = move_from(m);
1401   Square to = move_to(m);
1402   Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1403
1404   assert(to == ep_square());
1405   assert(relative_rank(us, to) == RANK_6);
1406   assert(piece_on(to) == piece_of_color_and_type(us, PAWN));
1407   assert(piece_on(from) == EMPTY);
1408   assert(piece_on(capsq) == EMPTY);
1409
1410   // Replace captured piece
1411   set_bit(&(byColorBB[them]), capsq);
1412   set_bit(&(byTypeBB[PAWN]), capsq);
1413   set_bit(&(byTypeBB[0]), capsq);
1414   board[capsq] = piece_of_color_and_type(them, PAWN);
1415
1416   // Remove moving piece from destination square
1417   clear_bit(&(byColorBB[us]), to);
1418   clear_bit(&(byTypeBB[PAWN]), to);
1419   clear_bit(&(byTypeBB[0]), to);
1420   board[to] = EMPTY;
1421
1422   // Replace moving piece at source square
1423   set_bit(&(byColorBB[us]), from);
1424   set_bit(&(byTypeBB[PAWN]), from);
1425   set_bit(&(byTypeBB[0]), from);
1426   board[from] = piece_of_color_and_type(us, PAWN);
1427
1428   // Update piece list:
1429   pieceList[us][PAWN][index[to]] = from;
1430   index[from] = index[to];
1431   pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1432   index[capsq] = pieceCount[them][PAWN];
1433
1434   // Update piece count:
1435   pieceCount[them][PAWN]++;
1436 }
1437
1438
1439 /// Position::do_null_move makes() a "null move": It switches the side to move
1440 /// and updates the hash key without executing any move on the board.
1441
1442 void Position::do_null_move(UndoInfo& u) {
1443
1444   assert(is_ok());
1445   assert(!is_check());
1446
1447   // Back up the information necessary to undo the null move to the supplied
1448   // UndoInfo object. In the case of a null move, the only thing we need to
1449   // remember is the last move made and the en passant square.
1450   u.lastMove = lastMove;
1451   u.epSquare = epSquare;
1452   u.previous = previous;
1453   previous = &u;
1454
1455   // Save the current key to the history[] array, in order to be able to
1456   // detect repetition draws.
1457   history[gamePly] = key;
1458
1459   // Update the necessary information
1460   sideToMove = opposite_color(sideToMove);
1461   if (epSquare != SQ_NONE)
1462       key ^= zobEp[epSquare];
1463
1464   epSquare = SQ_NONE;
1465   rule50++;
1466   gamePly++;
1467   key ^= zobSideToMove;
1468
1469   mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1470   egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1471
1472   assert(is_ok());
1473 }
1474
1475
1476 /// Position::undo_null_move() unmakes a "null move".
1477
1478 void Position::undo_null_move() {
1479
1480   assert(is_ok());
1481   assert(!is_check());
1482
1483   // Restore information from the our UndoInfo object
1484   lastMove = previous->lastMove;
1485   epSquare = previous->epSquare;
1486   previous = previous->previous;
1487
1488   if (epSquare != SQ_NONE)
1489       key ^= zobEp[epSquare];
1490
1491   // Update the necessary information
1492   sideToMove = opposite_color(sideToMove);
1493   rule50--;
1494   gamePly--;
1495   key ^= zobSideToMove;
1496
1497   mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1498   egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1499
1500   assert(is_ok());
1501 }
1502
1503
1504 /// Position::see() is a static exchange evaluator: It tries to estimate the
1505 /// material gain or loss resulting from a move.  There are three versions of
1506 /// this function: One which takes a destination square as input, one takes a
1507 /// move, and one which takes a 'from' and a 'to' square. The function does
1508 /// not yet understand promotions captures.
1509
1510 int Position::see(Square to) const {
1511
1512   assert(square_is_ok(to));
1513   return see(SQ_NONE, to);
1514 }
1515
1516 int Position::see(Move m) const {
1517
1518   assert(move_is_ok(m));
1519   return see(move_from(m), move_to(m));
1520 }
1521
1522 int Position::see(Square from, Square to) const {
1523
1524   // Material values
1525   static const int seeValues[18] = {
1526     0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1527        RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1528     0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1529        RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1530     0, 0
1531   };
1532
1533   Bitboard attackers, occ, b;
1534
1535   assert(square_is_ok(from) || from == SQ_NONE);
1536   assert(square_is_ok(to));
1537
1538   // Initialize colors
1539   Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1540   Color them = opposite_color(us);
1541
1542   // Initialize pieces
1543   Piece piece = piece_on(from);
1544   Piece capture = piece_on(to);
1545
1546   // Find all attackers to the destination square, with the moving piece
1547   // removed, but possibly an X-ray attacker added behind it.
1548   occ = occupied_squares();
1549
1550   // Handle en passant moves
1551   if (epSquare == to && type_of_piece_on(from) == PAWN)
1552   {
1553       assert(capture == EMPTY);
1554
1555       Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1556       capture = piece_on(capQq);
1557
1558       assert(type_of_piece_on(capQq) == PAWN);
1559
1560       // Remove the captured pawn
1561       clear_bit(&occ, capQq);
1562   }
1563
1564   while (true)
1565   {
1566       clear_bit(&occ, from);
1567       attackers =  (rook_attacks_bb(to, occ)   & rooks_and_queens())
1568                  | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1569                  | (piece_attacks<KNIGHT>(to)  & knights())
1570                  | (piece_attacks<KING>(to)    & kings())
1571                  | (pawn_attacks(WHITE, to)    & pawns(BLACK))
1572                  | (pawn_attacks(BLACK, to)    & pawns(WHITE));
1573
1574       if (from != SQ_NONE)
1575           break;
1576
1577       // If we don't have any attacker we are finished
1578       if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1579           return 0;
1580
1581       // Locate the least valuable attacker to the destination square
1582       // and use it to initialize from square.
1583       PieceType pt;
1584       for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1585           assert(pt < KING);
1586
1587       from = first_1(attackers & pieces_of_color_and_type(us, pt));
1588       piece = piece_on(from);
1589   }
1590
1591   // If the opponent has no attackers we are finished
1592   if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1593       return seeValues[capture];
1594
1595   attackers &= occ; // Remove the moving piece
1596
1597   // The destination square is defended, which makes things rather more
1598   // difficult to compute. We proceed by building up a "swap list" containing
1599   // the material gain or loss at each stop in a sequence of captures to the
1600   // destination square, where the sides alternately capture, and always
1601   // capture with the least valuable piece. After each capture, we look for
1602   // new X-ray attacks from behind the capturing piece.
1603   int lastCapturingPieceValue = seeValues[piece];
1604   int swapList[32], n = 1;
1605   Color c = them;
1606   PieceType pt;
1607
1608   swapList[0] = seeValues[capture];
1609
1610   do {
1611       // Locate the least valuable attacker for the side to move.  The loop
1612       // below looks like it is potentially infinite, but it isn't. We know
1613       // that the side to move still has at least one attacker left.
1614       for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1615           assert(pt < KING);
1616
1617       // Remove the attacker we just found from the 'attackers' bitboard,
1618       // and scan for new X-ray attacks behind the attacker.
1619       b = attackers & pieces_of_color_and_type(c, pt);
1620       occ ^= (b & -b);
1621       attackers |=  (rook_attacks_bb(to, occ) & rooks_and_queens())
1622                   | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1623
1624       attackers &= occ;
1625
1626       // Add the new entry to the swap list
1627       assert(n < 32);
1628       swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1629       n++;
1630
1631       // Remember the value of the capturing piece, and change the side to move
1632       // before beginning the next iteration
1633       lastCapturingPieceValue = seeValues[pt];
1634       c = opposite_color(c);
1635
1636       // Stop after a king capture
1637       if (pt == KING && (attackers & pieces_of_color(c)))
1638       {
1639           assert(n < 32);
1640           swapList[n++] = 100;
1641           break;
1642       }
1643   } while (attackers & pieces_of_color(c));
1644
1645   // Having built the swap list, we negamax through it to find the best
1646   // achievable score from the point of view of the side to move
1647   while (--n)
1648       swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1649
1650   return swapList[0];
1651 }
1652
1653
1654 /// Position::clear() erases the position object to a pristine state, with an
1655 /// empty board, white to move, and no castling rights.
1656
1657 void Position::clear() {
1658
1659   for (int i = 0; i < 64; i++)
1660   {
1661       board[i] = EMPTY;
1662       index[i] = 0;
1663   }
1664
1665   for (int i = 0; i < 2; i++)
1666       byColorBB[i] = EmptyBoardBB;
1667
1668   for (int i = 0; i < 7; i++)
1669   {
1670       byTypeBB[i] = EmptyBoardBB;
1671       pieceCount[0][i] = pieceCount[1][i] = 0;
1672       for (int j = 0; j < 8; j++)
1673           pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1674   }
1675
1676   checkersBB = EmptyBoardBB;
1677   for (Color c = WHITE; c <= BLACK; c++)
1678       pinners[c] = pinned[c] = dcCandidates[c] = ~EmptyBoardBB;
1679
1680   lastMove = MOVE_NONE;
1681
1682   sideToMove = WHITE;
1683   castleRights = NO_CASTLES;
1684   initialKFile = FILE_E;
1685   initialKRFile = FILE_H;
1686   initialQRFile = FILE_A;
1687   epSquare = SQ_NONE;
1688   rule50 = 0;
1689   gamePly = 0;
1690   previous = NULL;
1691 }
1692
1693
1694 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1695 /// UCI interface code, whenever a non-reversible move is made in a
1696 /// 'position fen <fen> moves m1 m2 ...' command.  This makes it possible
1697 /// for the program to handle games of arbitrary length, as long as the GUI
1698 /// handles draws by the 50 move rule correctly.
1699
1700 void Position::reset_game_ply() {
1701
1702   gamePly = 0;
1703 }
1704
1705
1706 /// Position::put_piece() puts a piece on the given square of the board,
1707 /// updating the board array, bitboards, and piece counts.
1708
1709 void Position::put_piece(Piece p, Square s) {
1710
1711   Color c = color_of_piece(p);
1712   PieceType pt = type_of_piece(p);
1713
1714   board[s] = p;
1715   index[s] = pieceCount[c][pt];
1716   pieceList[c][pt][index[s]] = s;
1717
1718   set_bit(&(byTypeBB[pt]), s);
1719   set_bit(&(byColorBB[c]), s);
1720   set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1721
1722   pieceCount[c][pt]++;
1723
1724   if (pt == KING)
1725       kingSquare[c] = s;
1726 }
1727
1728
1729 /// Position::allow_oo() gives the given side the right to castle kingside.
1730 /// Used when setting castling rights during parsing of FEN strings.
1731
1732 void Position::allow_oo(Color c) {
1733
1734   castleRights |= (1 + int(c));
1735 }
1736
1737
1738 /// Position::allow_ooo() gives the given side the right to castle queenside.
1739 /// Used when setting castling rights during parsing of FEN strings.
1740
1741 void Position::allow_ooo(Color c) {
1742
1743   castleRights |= (4 + 4*int(c));
1744 }
1745
1746
1747 /// Position::compute_key() computes the hash key of the position. The hash
1748 /// key is usually updated incrementally as moves are made and unmade, the
1749 /// compute_key() function is only used when a new position is set up, and
1750 /// to verify the correctness of the hash key when running in debug mode.
1751
1752 Key Position::compute_key() const {
1753
1754   Key result = Key(0ULL);
1755
1756   for (Square s = SQ_A1; s <= SQ_H8; s++)
1757       if (square_is_occupied(s))
1758           result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1759
1760   if (ep_square() != SQ_NONE)
1761       result ^= zobEp[ep_square()];
1762
1763   result ^= zobCastle[castleRights];
1764   if (side_to_move() == BLACK)
1765       result ^= zobSideToMove;
1766
1767   return result;
1768 }
1769
1770
1771 /// Position::compute_pawn_key() computes the hash key of the position. The
1772 /// hash key is usually updated incrementally as moves are made and unmade,
1773 /// the compute_pawn_key() function is only used when a new position is set
1774 /// up, and to verify the correctness of the pawn hash key when running in
1775 /// debug mode.
1776
1777 Key Position::compute_pawn_key() const {
1778
1779   Key result = Key(0ULL);
1780   Bitboard b;
1781   Square s;
1782
1783   for (Color c = WHITE; c <= BLACK; c++)
1784   {
1785       b = pawns(c);
1786       while(b)
1787       {
1788           s = pop_1st_bit(&b);
1789           result ^= zobrist[c][PAWN][s];
1790       }
1791   }
1792   return result;
1793 }
1794
1795
1796 /// Position::compute_material_key() computes the hash key of the position.
1797 /// The hash key is usually updated incrementally as moves are made and unmade,
1798 /// the compute_material_key() function is only used when a new position is set
1799 /// up, and to verify the correctness of the material hash key when running in
1800 /// debug mode.
1801
1802 Key Position::compute_material_key() const {
1803
1804   Key result = Key(0ULL);
1805   for (Color c = WHITE; c <= BLACK; c++)
1806       for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1807       {
1808           int count = piece_count(c, pt);
1809           for (int i = 0; i <= count; i++)
1810               result ^= zobMaterial[c][pt][i];
1811       }
1812   return result;
1813 }
1814
1815
1816 /// Position::compute_value() compute the incremental scores for the middle
1817 /// game and the endgame. These functions are used to initialize the incremental
1818 /// scores when a new position is set up, and to verify that the scores are correctly
1819 /// updated by do_move and undo_move when the program is running in debug mode.
1820 template<Position::GamePhase Phase>
1821 Value Position::compute_value() const {
1822
1823   Value result = Value(0);
1824   Bitboard b;
1825   Square s;
1826
1827   for (Color c = WHITE; c <= BLACK; c++)
1828       for (PieceType pt = PAWN; pt <= KING; pt++)
1829       {
1830           b = pieces_of_color_and_type(c, pt);
1831           while(b)
1832           {
1833               s = pop_1st_bit(&b);
1834               assert(piece_on(s) == piece_of_color_and_type(c, pt));
1835               result += pst<Phase>(c, pt, s);
1836           }
1837       }
1838
1839   const Value TempoValue = (Phase == MidGame ? TempoValueMidgame : TempoValueEndgame);
1840   result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;
1841   return result;
1842 }
1843
1844
1845 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1846 /// game material score for the given side. Material scores are updated
1847 /// incrementally during the search, this function is only used while
1848 /// initializing a new Position object.
1849
1850 Value Position::compute_non_pawn_material(Color c) const {
1851
1852   Value result = Value(0);
1853   Square s;
1854
1855   for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1856   {
1857       Bitboard b = pieces_of_color_and_type(c, pt);
1858       while(b)
1859       {
1860           s = pop_1st_bit(&b);
1861           assert(piece_on(s) == piece_of_color_and_type(c, pt));
1862           result += piece_value_midgame(pt);
1863       }
1864   }
1865   return result;
1866 }
1867
1868
1869 /// Position::is_mate() returns true or false depending on whether the
1870 /// side to move is checkmated. Note that this function is currently very
1871 /// slow, and shouldn't be used frequently inside the search.
1872
1873 bool Position::is_mate() const {
1874
1875   if (is_check())
1876   {
1877       MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1878       return mp.get_next_move() == MOVE_NONE;
1879   }
1880   return false;
1881 }
1882
1883
1884 /// Position::is_draw() tests whether the position is drawn by material,
1885 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1886 /// must be done by the search.
1887
1888 bool Position::is_draw() const {
1889
1890   // Draw by material?
1891   if (   !pawns()
1892       && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1893       return true;
1894
1895   // Draw by the 50 moves rule?
1896   if (rule50 > 100 || (rule50 == 100 && !is_check()))
1897       return true;
1898
1899   // Draw by repetition?
1900   for (int i = 2; i < Min(gamePly, rule50); i += 2)
1901       if (history[gamePly - i] == key)
1902           return true;
1903
1904   return false;
1905 }
1906
1907
1908 /// Position::has_mate_threat() tests whether a given color has a mate in one
1909 /// from the current position. This function is quite slow, but it doesn't
1910 /// matter, because it is currently only called from PV nodes, which are rare.
1911
1912 bool Position::has_mate_threat(Color c) {
1913
1914   UndoInfo u1, u2;
1915   Color stm = side_to_move();
1916
1917   // The following lines are useless and silly, but prevents gcc from
1918   // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1919   // be used uninitialized.
1920   u1.lastMove = lastMove;
1921   u1.epSquare = epSquare;
1922
1923   if (is_check())
1924       return false;
1925
1926   // If the input color is not equal to the side to move, do a null move
1927   if (c != stm)
1928       do_null_move(u1);
1929
1930   MoveStack mlist[120];
1931   int count;
1932   bool result = false;
1933
1934   // Generate legal moves
1935   count = generate_legal_moves(*this, mlist);
1936
1937   // Loop through the moves, and see if one of them is mate
1938   for (int i = 0; i < count; i++)
1939   {
1940       do_move(mlist[i].move, u2);
1941       if (is_mate())
1942           result = true;
1943
1944       undo_move(mlist[i].move);
1945   }
1946
1947   // Undo null move, if necessary
1948   if (c != stm)
1949       undo_null_move();
1950
1951   return result;
1952 }
1953
1954
1955 /// Position::init_zobrist() is a static member function which initializes the
1956 /// various arrays used to compute hash keys.
1957
1958 void Position::init_zobrist() {
1959
1960   for (int i = 0; i < 2; i++)
1961       for (int j = 0; j < 8; j++)
1962           for (int k = 0; k < 64; k++)
1963               zobrist[i][j][k] = Key(genrand_int64());
1964
1965   for (int i = 0; i < 64; i++)
1966       zobEp[i] = Key(genrand_int64());
1967
1968   for (int i = 0; i < 16; i++)
1969       zobCastle[i] = genrand_int64();
1970
1971   zobSideToMove = genrand_int64();
1972
1973   for (int i = 0; i < 2; i++)
1974       for (int j = 0; j < 8; j++)
1975           for (int k = 0; k < 16; k++)
1976               zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1977
1978   for (int i = 0; i < 16; i++)
1979       zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1980 }
1981
1982
1983 /// Position::init_piece_square_tables() initializes the piece square tables.
1984 /// This is a two-step operation:  First, the white halves of the tables are
1985 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1986 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1987 /// Second, the black halves of the tables are initialized by mirroring
1988 /// and changing the sign of the corresponding white scores.
1989
1990 void Position::init_piece_square_tables() {
1991
1992   int r = get_option_value_int("Randomness"), i;
1993   for (Square s = SQ_A1; s <= SQ_H8; s++)
1994       for (Piece p = WP; p <= WK; p++)
1995       {
1996           i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1997           MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
1998           EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
1999       }
2000
2001   for (Square s = SQ_A1; s <= SQ_H8; s++)
2002       for (Piece p = BP; p <= BK; p++)
2003       {
2004           MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2005           EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2006       }
2007 }
2008
2009
2010 /// Position::flipped_copy() makes a copy of the input position, but with
2011 /// the white and black sides reversed. This is only useful for debugging,
2012 /// especially for finding evaluation symmetry bugs.
2013
2014 void Position::flipped_copy(const Position &pos) {
2015
2016   assert(pos.is_ok());
2017
2018   clear();
2019
2020   // Board
2021   for (Square s = SQ_A1; s <= SQ_H8; s++)
2022       if (!pos.square_is_empty(s))
2023           put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2024
2025   // Side to move
2026   sideToMove = opposite_color(pos.side_to_move());
2027
2028   // Castling rights
2029   if (pos.can_castle_kingside(WHITE))  allow_oo(BLACK);
2030   if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2031   if (pos.can_castle_kingside(BLACK))  allow_oo(WHITE);
2032   if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2033
2034   initialKFile  = pos.initialKFile;
2035   initialKRFile = pos.initialKRFile;
2036   initialQRFile = pos.initialQRFile;
2037
2038   for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2039       castleRightsMask[sq] = ALL_CASTLES;
2040
2041   castleRightsMask[make_square(initialKFile,  RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2042   castleRightsMask[make_square(initialKFile,  RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2043   castleRightsMask[make_square(initialKRFile, RANK_1)] ^=  WHITE_OO;
2044   castleRightsMask[make_square(initialKRFile, RANK_8)] ^=  BLACK_OO;
2045   castleRightsMask[make_square(initialQRFile, RANK_1)] ^=  WHITE_OOO;
2046   castleRightsMask[make_square(initialQRFile, RANK_8)] ^=  BLACK_OOO;
2047
2048   // En passant square
2049   if (pos.epSquare != SQ_NONE)
2050       epSquare = flip_square(pos.epSquare);
2051
2052   // Checkers
2053   find_checkers();
2054
2055   // Hash keys
2056   key = compute_key();
2057   pawnKey = compute_pawn_key();
2058   materialKey = compute_material_key();
2059
2060   // Incremental scores
2061   mgValue = compute_value<MidGame>();
2062   egValue = compute_value<EndGame>();
2063
2064   // Material
2065   npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2066   npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2067
2068   assert(is_ok());
2069 }
2070
2071
2072 /// Position::is_ok() performs some consitency checks for the position object.
2073 /// This is meant to be helpful when debugging.
2074
2075 bool Position::is_ok(int* failedStep) const {
2076
2077   // What features of the position should be verified?
2078   static const bool debugBitboards = false;
2079   static const bool debugKingCount = false;
2080   static const bool debugKingCapture = false;
2081   static const bool debugCheckerCount = false;
2082   static const bool debugKey = false;
2083   static const bool debugMaterialKey = false;
2084   static const bool debugPawnKey = false;
2085   static const bool debugIncrementalEval = false;
2086   static const bool debugNonPawnMaterial = false;
2087   static const bool debugPieceCounts = false;
2088   static const bool debugPieceList = false;
2089
2090   if (failedStep) *failedStep = 1;
2091
2092   // Side to move OK?
2093   if (!color_is_ok(side_to_move()))
2094       return false;
2095
2096   // Are the king squares in the position correct?
2097   if (failedStep) (*failedStep)++;
2098   if (piece_on(king_square(WHITE)) != WK)
2099       return false;
2100
2101   if (failedStep) (*failedStep)++;
2102   if (piece_on(king_square(BLACK)) != BK)
2103       return false;
2104
2105   // Castle files OK?
2106   if (failedStep) (*failedStep)++;
2107   if (!file_is_ok(initialKRFile))
2108       return false;
2109
2110   if (!file_is_ok(initialQRFile))
2111       return false;
2112
2113   // Do both sides have exactly one king?
2114   if (failedStep) (*failedStep)++;
2115   if (debugKingCount)
2116   {
2117       int kingCount[2] = {0, 0};
2118       for (Square s = SQ_A1; s <= SQ_H8; s++)
2119           if (type_of_piece_on(s) == KING)
2120               kingCount[color_of_piece_on(s)]++;
2121
2122       if (kingCount[0] != 1 || kingCount[1] != 1)
2123           return false;
2124   }
2125
2126   // Can the side to move capture the opponent's king?
2127   if (failedStep) (*failedStep)++;
2128   if (debugKingCapture)
2129   {
2130       Color us = side_to_move();
2131       Color them = opposite_color(us);
2132       Square ksq = king_square(them);
2133       if (square_is_attacked(ksq, us))
2134           return false;
2135   }
2136
2137   // Is there more than 2 checkers?
2138   if (failedStep) (*failedStep)++;
2139   if (debugCheckerCount && count_1s(checkersBB) > 2)
2140       return false;
2141
2142   // Bitboards OK?
2143   if (failedStep) (*failedStep)++;
2144   if (debugBitboards)
2145   {
2146       // The intersection of the white and black pieces must be empty
2147       if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2148           return false;
2149
2150       // The union of the white and black pieces must be equal to all
2151       // occupied squares
2152       if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2153           return false;
2154
2155       // Separate piece type bitboards must have empty intersections
2156       for (PieceType p1 = PAWN; p1 <= KING; p1++)
2157           for (PieceType p2 = PAWN; p2 <= KING; p2++)
2158               if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2159                   return false;
2160   }
2161
2162   // En passant square OK?
2163   if (failedStep) (*failedStep)++;
2164   if (ep_square() != SQ_NONE)
2165   {
2166       // The en passant square must be on rank 6, from the point of view of the
2167       // side to move.
2168       if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2169           return false;
2170   }
2171
2172   // Hash key OK?
2173   if (failedStep) (*failedStep)++;
2174   if (debugKey && key != compute_key())
2175       return false;
2176
2177   // Pawn hash key OK?
2178   if (failedStep) (*failedStep)++;
2179   if (debugPawnKey && pawnKey != compute_pawn_key())
2180       return false;
2181
2182   // Material hash key OK?
2183   if (failedStep) (*failedStep)++;
2184   if (debugMaterialKey && materialKey != compute_material_key())
2185       return false;
2186
2187   // Incremental eval OK?
2188   if (failedStep) (*failedStep)++;
2189   if (debugIncrementalEval)
2190   {
2191       if (mgValue != compute_value<MidGame>())
2192           return false;
2193
2194       if (egValue != compute_value<EndGame>())
2195           return false;
2196   }
2197
2198   // Non-pawn material OK?
2199   if (failedStep) (*failedStep)++;
2200   if (debugNonPawnMaterial)
2201   {
2202       if (npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2203           return false;
2204
2205       if (npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2206           return false;
2207   }
2208
2209   // Piece counts OK?
2210   if (failedStep) (*failedStep)++;
2211   if (debugPieceCounts)
2212       for (Color c = WHITE; c <= BLACK; c++)
2213           for (PieceType pt = PAWN; pt <= KING; pt++)
2214               if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2215                   return false;
2216
2217   if (failedStep) (*failedStep)++;
2218   if (debugPieceList)
2219   {
2220       for(Color c = WHITE; c <= BLACK; c++)
2221           for(PieceType pt = PAWN; pt <= KING; pt++)
2222               for(int i = 0; i < pieceCount[c][pt]; i++)
2223               {
2224                   if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2225                       return false;
2226
2227                   if (index[piece_list(c, pt, i)] != i)
2228                       return false;
2229               }
2230   }
2231   if (failedStep) *failedStep = 0;
2232   return true;
2233 }