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