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