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