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