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