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