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