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