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