]> git.sesse.net Git - stockfish/blob - src/position.cpp
ed7510101de89fbbd38270113019d82b710d8b7a
[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::update_checkers() updates checkers info, used in do_move()
321 template<PieceType Piece>
322 inline void Position::update_checkers(Bitboard* pCheckersBB, Square ksq, Square from,
323                                       Square to, Bitboard dcCandidates) {
324
325   if (Piece != KING && bit_is_set(piece_attacks<Piece>(ksq), to))
326       set_bit(pCheckersBB, to);
327
328   if (Piece != QUEEN && bit_is_set(dcCandidates, from))
329   {
330       if (Piece != ROOK)
331           (*pCheckersBB) |= (piece_attacks<ROOK>(ksq) & rooks_and_queens(side_to_move()));
332
333       if (Piece != BISHOP)
334           (*pCheckersBB) |= (piece_attacks<BISHOP>(ksq) & bishops_and_queens(side_to_move()));
335   }
336 }
337
338
339 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
340 /// king) pieces for the given color.
341 Bitboard Position::pinned_pieces(Color c) const {
342
343   Square ksq = king_square(c);
344   return hidden_checks<ROOK, true>(c, ksq) | hidden_checks<BISHOP, true>(c, ksq);
345 }
346
347
348 /// Position:discovered_check_candidates() returns a bitboard containing all
349 /// pieces for the given side which are candidates for giving a discovered
350 /// check.  The code is almost the same as the function for finding pinned
351 /// pieces.
352
353 Bitboard Position::discovered_check_candidates(Color c) const {
354
355   Square ksq = king_square(opposite_color(c));
356   return hidden_checks<ROOK, false>(c, ksq) | hidden_checks<BISHOP, false>(c, ksq);
357 }
358
359
360 /// Position:hidden_checks<>() returns a bitboard of all pinned (against the
361 /// king) pieces for the given color and for the given pinner type. Or, when
362 /// template parameter FindPinned is false, the pinned pieces of opposite color
363 /// that are, indeed, the pieces candidate for a discovery check.
364 template<PieceType Piece, bool FindPinned>
365 Bitboard Position::hidden_checks(Color c, Square ksq) const {
366
367   Square s;
368   Bitboard sliders, result = EmptyBoardBB;
369
370   if (Piece == ROOK) // Resolved at compile time
371       sliders = rooks_and_queens(FindPinned ? opposite_color(c) : c) & RookPseudoAttacks[ksq];
372   else
373       sliders = bishops_and_queens(FindPinned ? opposite_color(c) : c) & BishopPseudoAttacks[ksq];
374
375   if (sliders && (!FindPinned || (sliders & ~checkersBB)))
376   {
377        // King blockers are candidate pinned pieces
378       Bitboard candidate_pinned = piece_attacks<Piece>(ksq) & pieces_of_color(c);
379
380       // Pinners are sliders, not checkers, that give check when
381       // candidate pinned are removed.
382       Bitboard pinners = (FindPinned ? sliders & ~checkersBB : sliders);
383
384       if (Piece == ROOK)
385           pinners &= rook_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
386       else
387           pinners &= bishop_attacks_bb(ksq, occupied_squares() ^ candidate_pinned);
388
389       // Finally for each pinner find the corresponding pinned piece (if same color of king)
390       // or discovery checker (if opposite color) among the candidates.
391       while (pinners)
392       {
393           s = pop_1st_bit(&pinners);
394           result |= (squares_between(s, ksq) & candidate_pinned);
395       }
396   }
397   return result;
398 }
399
400
401 /// Position::attacks_to() computes a bitboard containing all pieces which
402 /// attacks a given square. There are two versions of this function: One
403 /// which finds attackers of both colors, and one which only finds the
404 /// attackers for one side.
405
406 Bitboard Position::attacks_to(Square s) const {
407
408   return  (pawn_attacks(BLACK, s)   & pawns(WHITE))
409         | (pawn_attacks(WHITE, s)   & pawns(BLACK))
410         | (piece_attacks<KNIGHT>(s) & pieces_of_type(KNIGHT))
411         | (piece_attacks<ROOK>(s)   & rooks_and_queens())
412         | (piece_attacks<BISHOP>(s) & bishops_and_queens())
413         | (piece_attacks<KING>(s)   & pieces_of_type(KING));
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     // Reset en passant square
812     if (epSquare != SQ_NONE)
813     {
814         key ^= zobEp[epSquare];
815         epSquare = SQ_NONE;
816     }
817
818     // If the moving piece was a pawn do some special extra work
819     if (piece == PAWN)
820     {
821         // Reset rule 50 draw counter
822         rule50 = 0;
823
824         // Update pawn hash key
825         pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
826
827         // Set en passant square, only if moved pawn can be captured
828         if (abs(int(to) - int(from)) == 16)
829         {
830             if (   (us == WHITE && (pawn_attacks(WHITE, from + DELTA_N) & pawns(BLACK)))
831                 || (us == BLACK && (pawn_attacks(BLACK, from + DELTA_S) & pawns(WHITE))))
832             {
833                 epSquare = Square((int(from) + int(to)) / 2);
834                 key ^= zobEp[epSquare];
835             }
836         }
837     }
838
839     // Update piece lists
840     pieceList[us][piece][index[from]] = to;
841     index[to] = index[from];
842
843     // Update castle rights
844     key ^= zobCastle[castleRights];
845     castleRights &= castleRightsMask[from];
846     castleRights &= castleRightsMask[to];
847     key ^= zobCastle[castleRights];
848
849     // Update checkers bitboard, piece must be already moved
850     checkersBB = EmptyBoardBB;
851     Square ksq = king_square(them);
852     switch (piece)
853     {
854     case PAWN:
855         update_checkers<PAWN>(&checkersBB, ksq, from, to, dcCandidates);
856         break;
857
858     case KNIGHT:
859         update_checkers<KNIGHT>(&checkersBB, ksq, from, to, dcCandidates);
860         break;
861
862     case BISHOP:
863         update_checkers<BISHOP>(&checkersBB, ksq, from, to, dcCandidates);
864         break;
865
866     case ROOK:
867         update_checkers<ROOK>(&checkersBB, ksq, from, to, dcCandidates);
868         break;
869
870     case QUEEN:
871         update_checkers<QUEEN>(&checkersBB, ksq, from, to, dcCandidates);
872         break;
873
874     case KING:
875         update_checkers<KING>(&checkersBB, ksq, from, to, dcCandidates);
876         break;
877
878     default:
879       assert(false);
880       break;
881     }
882   }
883
884   // Finish
885   key ^= zobSideToMove;
886   sideToMove = opposite_color(sideToMove);
887   gamePly++;
888
889   mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
890   egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
891
892   assert(is_ok());
893 }
894
895 /// Position::do_capture_move() is a private method used to update captured
896 /// piece info. It is called from the main Position::do_move function.
897
898 void Position::do_capture_move(Move m, PieceType capture, Color them, Square to) {
899
900     assert(capture != KING);
901
902     // Remove captured piece
903     clear_bit(&(byColorBB[them]), to);
904     clear_bit(&(byTypeBB[capture]), to);
905
906     // Update hash key
907     key ^= zobrist[them][capture][to];
908
909     // If the captured piece was a pawn, update pawn hash key
910     if (capture == PAWN)
911         pawnKey ^= zobrist[them][PAWN][to];
912
913     // Update incremental scores
914     mgValue -= mg_pst(them, capture, to);
915     egValue -= eg_pst(them, capture, to);
916
917     assert(!move_promotion(m) || capture != PAWN);
918
919     // Update material
920     if (capture != PAWN)
921         npMaterial[them] -= piece_value_midgame(capture);
922
923     // Update material hash key
924     materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
925
926     // Update piece count
927     pieceCount[them][capture]--;
928
929     // Update piece list
930     pieceList[them][capture][index[to]] = pieceList[them][capture][pieceCount[them][capture]];
931     index[pieceList[them][capture][index[to]]] = index[to];
932
933     // Reset rule 50 counter
934     rule50 = 0;
935 }
936
937
938 /// Position::do_castle_move() is a private method used to make a castling
939 /// move. It is called from the main Position::do_move function. Note that
940 /// castling moves are encoded as "king captures friendly rook" moves, for
941 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
942
943 void Position::do_castle_move(Move m) {
944
945   assert(is_ok());
946   assert(move_is_ok(m));
947   assert(move_is_castle(m));
948
949   Color us = side_to_move();
950   Color them = opposite_color(us);
951
952   // Find source squares for king and rook
953   Square kfrom = move_from(m);
954   Square rfrom = move_to(m);  // HACK: See comment at beginning of function
955   Square kto, rto;
956
957   assert(piece_on(kfrom) == king_of_color(us));
958   assert(piece_on(rfrom) == rook_of_color(us));
959
960   // Find destination squares for king and rook
961   if (rfrom > kfrom) // O-O
962   {
963       kto = relative_square(us, SQ_G1);
964       rto = relative_square(us, SQ_F1);
965   } else { // O-O-O
966       kto = relative_square(us, SQ_C1);
967       rto = relative_square(us, SQ_D1);
968   }
969
970   // Remove pieces from source squares
971   clear_bit(&(byColorBB[us]), kfrom);
972   clear_bit(&(byTypeBB[KING]), kfrom);
973   clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
974   clear_bit(&(byColorBB[us]), rfrom);
975   clear_bit(&(byTypeBB[ROOK]), rfrom);
976   clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
977
978   // Put pieces on destination squares
979   set_bit(&(byColorBB[us]), kto);
980   set_bit(&(byTypeBB[KING]), kto);
981   set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
982   set_bit(&(byColorBB[us]), rto);
983   set_bit(&(byTypeBB[ROOK]), rto);
984   set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
985
986   // Update board array
987   board[kfrom] = board[rfrom] = EMPTY;
988   board[kto] = king_of_color(us);
989   board[rto] = rook_of_color(us);
990
991   // Update king square
992   kingSquare[us] = kto;
993
994   // Update piece lists
995   pieceList[us][KING][index[kfrom]] = kto;
996   pieceList[us][ROOK][index[rfrom]] = rto;
997   int tmp = index[rfrom];
998   index[kto] = index[kfrom];
999   index[rto] = tmp;
1000
1001   // Update incremental scores
1002   mgValue -= mg_pst(us, KING, kfrom);
1003   mgValue += mg_pst(us, KING, kto);
1004   egValue -= eg_pst(us, KING, kfrom);
1005   egValue += eg_pst(us, KING, kto);
1006   mgValue -= mg_pst(us, ROOK, rfrom);
1007   mgValue += mg_pst(us, ROOK, rto);
1008   egValue -= eg_pst(us, ROOK, rfrom);
1009   egValue += eg_pst(us, ROOK, rto);
1010
1011   // Update hash key
1012   key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1013   key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1014
1015   // Clear en passant square
1016   if(epSquare != SQ_NONE)
1017   {
1018       key ^= zobEp[epSquare];
1019       epSquare = SQ_NONE;
1020   }
1021
1022   // Update castling rights
1023   key ^= zobCastle[castleRights];
1024   castleRights &= castleRightsMask[kfrom];
1025   key ^= zobCastle[castleRights];
1026
1027   // Reset rule 50 counter
1028   rule50 = 0;
1029
1030   // Update checkers BB
1031   checkersBB = attacks_to(king_square(them), us);
1032 }
1033
1034
1035 /// Position::do_promotion_move() is a private method used to make a promotion
1036 /// move. It is called from the main Position::do_move function. The
1037 /// UndoInfo object, which has been initialized in Position::do_move, is
1038 /// used to store the captured piece (if any).
1039
1040 void Position::do_promotion_move(Move m, UndoInfo &u) {
1041
1042   Color us, them;
1043   Square from, to;
1044   PieceType capture, promotion;
1045
1046   assert(is_ok());
1047   assert(move_is_ok(m));
1048   assert(move_promotion(m));
1049
1050   us = side_to_move();
1051   them = opposite_color(us);
1052   from = move_from(m);
1053   to = move_to(m);
1054
1055   assert(relative_rank(us, to) == RANK_8);
1056   assert(piece_on(from) == pawn_of_color(us));
1057   assert(color_of_piece_on(to) == them || square_is_empty(to));
1058
1059   capture = type_of_piece_on(to);
1060
1061   if (capture)
1062   {
1063     u.capture = capture;
1064     do_capture_move(m, capture, them, to);
1065   }
1066
1067   // Remove pawn
1068   clear_bit(&(byColorBB[us]), from);
1069   clear_bit(&(byTypeBB[PAWN]), from);
1070   clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1071   board[from] = EMPTY;
1072
1073   // Insert promoted piece
1074   promotion = move_promotion(m);
1075   assert(promotion >= KNIGHT && promotion <= QUEEN);
1076   set_bit(&(byColorBB[us]), to);
1077   set_bit(&(byTypeBB[promotion]), to);
1078   set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1079   board[to] = piece_of_color_and_type(us, promotion);
1080
1081   // Update hash key
1082   key ^= zobrist[us][PAWN][from] ^ zobrist[us][promotion][to];
1083
1084   // Update pawn hash key
1085   pawnKey ^= zobrist[us][PAWN][from];
1086
1087   // Update material key
1088   materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
1089   materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
1090
1091   // Update piece counts
1092   pieceCount[us][PAWN]--;
1093   pieceCount[us][promotion]++;
1094
1095   // Update piece lists
1096   pieceList[us][PAWN][index[from]] = pieceList[us][PAWN][pieceCount[us][PAWN]];
1097   index[pieceList[us][PAWN][index[from]]] = index[from];
1098   pieceList[us][promotion][pieceCount[us][promotion] - 1] = to;
1099   index[to] = pieceCount[us][promotion] - 1;
1100
1101   // Update incremental scores
1102   mgValue -= mg_pst(us, PAWN, from);
1103   mgValue += mg_pst(us, promotion, to);
1104   egValue -= eg_pst(us, PAWN, from);
1105   egValue += eg_pst(us, promotion, to);
1106
1107   // Update material
1108   npMaterial[us] += piece_value_midgame(promotion);
1109
1110   // Clear the en passant square
1111   if (epSquare != SQ_NONE)
1112   {
1113       key ^= zobEp[epSquare];
1114       epSquare = SQ_NONE;
1115   }
1116
1117   // Update castle rights
1118   key ^= zobCastle[castleRights];
1119   castleRights &= castleRightsMask[to];
1120   key ^= zobCastle[castleRights];
1121
1122   // Reset rule 50 counter
1123   rule50 = 0;
1124
1125   // Update checkers BB
1126   checkersBB = attacks_to(king_square(them), us);
1127 }
1128
1129
1130 /// Position::do_ep_move() is a private method used to make an en passant
1131 /// capture. It is called from the main Position::do_move function. Because
1132 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1133 /// object in which to store the captured piece.
1134
1135 void Position::do_ep_move(Move m) {
1136
1137   Color us, them;
1138   Square from, to, capsq;
1139
1140   assert(is_ok());
1141   assert(move_is_ok(m));
1142   assert(move_is_ep(m));
1143
1144   us = side_to_move();
1145   them = opposite_color(us);
1146   from = move_from(m);
1147   to = move_to(m);
1148   capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1149
1150   assert(to == epSquare);
1151   assert(relative_rank(us, to) == RANK_6);
1152   assert(piece_on(to) == EMPTY);
1153   assert(piece_on(from) == pawn_of_color(us));
1154   assert(piece_on(capsq) == pawn_of_color(them));
1155
1156   // Remove captured piece
1157   clear_bit(&(byColorBB[them]), capsq);
1158   clear_bit(&(byTypeBB[PAWN]), capsq);
1159   clear_bit(&(byTypeBB[0]), capsq); // HACK: byTypeBB[0] == occupied squares
1160   board[capsq] = EMPTY;
1161
1162   // Remove moving piece from source square
1163   clear_bit(&(byColorBB[us]), from);
1164   clear_bit(&(byTypeBB[PAWN]), from);
1165   clear_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1166
1167   // Put moving piece on destination square
1168   set_bit(&(byColorBB[us]), to);
1169   set_bit(&(byTypeBB[PAWN]), to);
1170   set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1171   board[to] = board[from];
1172   board[from] = EMPTY;
1173
1174   // Update material hash key
1175   materialKey ^= zobMaterial[them][PAWN][pieceCount[them][PAWN]];
1176
1177   // Update piece count
1178   pieceCount[them][PAWN]--;
1179
1180   // Update piece list
1181   pieceList[us][PAWN][index[from]] = to;
1182   index[to] = index[from];
1183   pieceList[them][PAWN][index[capsq]] = pieceList[them][PAWN][pieceCount[them][PAWN]];
1184   index[pieceList[them][PAWN][index[capsq]]] = index[capsq];
1185
1186   // Update hash key
1187   key ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1188   key ^= zobrist[them][PAWN][capsq];
1189   key ^= zobEp[epSquare];
1190
1191   // Update pawn hash key
1192   pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
1193   pawnKey ^= zobrist[them][PAWN][capsq];
1194
1195   // Update incremental scores
1196   mgValue -= mg_pst(them, PAWN, capsq);
1197   mgValue -= mg_pst(us, PAWN, from);
1198   mgValue += mg_pst(us, PAWN, to);
1199   egValue -= eg_pst(them, PAWN, capsq);
1200   egValue -= eg_pst(us, PAWN, from);
1201   egValue += eg_pst(us, PAWN, to);
1202
1203   // Reset en passant square
1204   epSquare = SQ_NONE;
1205
1206   // Reset rule 50 counter
1207   rule50 = 0;
1208
1209   // Update checkers BB
1210   checkersBB = attacks_to(king_square(them), us);
1211 }
1212
1213
1214 /// Position::undo_move() unmakes a move.  When it returns, the position should
1215 /// be restored to exactly the same state as before the move was made.  It is
1216 /// important that Position::undo_move is called with the same move and UndoInfo
1217 /// object as the earlier call to Position::do_move.
1218
1219 void Position::undo_move(Move m, const UndoInfo &u) {
1220
1221   assert(is_ok());
1222   assert(move_is_ok(m));
1223
1224   gamePly--;
1225   sideToMove = opposite_color(sideToMove);
1226
1227   // Restore information from our UndoInfo object (except the captured piece,
1228   // which is taken care of later)
1229   restore(u);
1230
1231   if (move_is_castle(m))
1232       undo_castle_move(m);
1233   else if (move_promotion(m))
1234       undo_promotion_move(m, u);
1235   else if (move_is_ep(m))
1236       undo_ep_move(m);
1237   else
1238   {
1239       Color us, them;
1240       Square from, to;
1241       PieceType piece, capture;
1242
1243       us = side_to_move();
1244       them = opposite_color(us);
1245       from = move_from(m);
1246       to = move_to(m);
1247
1248       assert(piece_on(from) == EMPTY);
1249       assert(color_of_piece_on(to) == us);
1250
1251       // Put the piece back at the source square
1252       piece = type_of_piece_on(to);
1253       set_bit(&(byColorBB[us]), from);
1254       set_bit(&(byTypeBB[piece]), from);
1255       set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1256       board[from] = piece_of_color_and_type(us, piece);
1257
1258       // Clear the destination square
1259       clear_bit(&(byColorBB[us]), to);
1260       clear_bit(&(byTypeBB[piece]), to);
1261       clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1262
1263       // If the moving piece was a king, update the king square
1264       if (piece == KING)
1265           kingSquare[us] = from;
1266
1267       // Update piece list
1268       pieceList[us][piece][index[to]] = from;
1269       index[from] = index[to];
1270
1271       capture = u.capture;
1272
1273       if (capture)
1274       {
1275           assert(capture != KING);
1276
1277           // Replace the captured piece
1278           set_bit(&(byColorBB[them]), to);
1279           set_bit(&(byTypeBB[capture]), to);
1280           set_bit(&(byTypeBB[0]), to);
1281           board[to] = piece_of_color_and_type(them, capture);
1282
1283           // Update material
1284           if (capture != PAWN)
1285               npMaterial[them] += piece_value_midgame(capture);
1286
1287           // Update piece list
1288           pieceList[them][capture][pieceCount[them][capture]] = to;
1289           index[to] = pieceCount[them][capture];
1290
1291           // Update piece count
1292           pieceCount[them][capture]++;
1293       } else
1294           board[to] = EMPTY;
1295   }
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) == king_of_color(us));
1332   assert(piece_on(rto) == rook_of_color(us));
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] = rook_of_color(us);
1353   board[kfrom] = king_of_color(us);
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. The UndoInfo object, which has been initialized in
1370 /// Position::do_move, is used to put back the captured piece (if any).
1371
1372 void Position::undo_promotion_move(Move m, const UndoInfo &u) {
1373
1374   Color us, them;
1375   Square from, to;
1376   PieceType capture, promotion;
1377
1378   assert(move_is_ok(m));
1379   assert(move_promotion(m));
1380
1381   // When we have arrived here, some work has already been done by
1382   // Position::undo_move.  In particular, the side to move has been switched,
1383   // so the code below is correct.
1384   us = side_to_move();
1385   them = opposite_color(us);
1386   from = move_from(m);
1387   to = move_to(m);
1388
1389   assert(relative_rank(us, to) == RANK_8);
1390   assert(piece_on(from) == EMPTY);
1391
1392   // Remove promoted piece
1393   promotion = move_promotion(m);
1394   assert(piece_on(to)==piece_of_color_and_type(us, promotion));
1395   assert(promotion >= KNIGHT && promotion <= QUEEN);
1396   clear_bit(&(byColorBB[us]), to);
1397   clear_bit(&(byTypeBB[promotion]), to);
1398   clear_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1399
1400   // Insert pawn at source square
1401   set_bit(&(byColorBB[us]), from);
1402   set_bit(&(byTypeBB[PAWN]), from);
1403   set_bit(&(byTypeBB[0]), from); // HACK: byTypeBB[0] == occupied squares
1404   board[from] = pawn_of_color(us);
1405
1406   // Update material
1407   npMaterial[us] -= piece_value_midgame(promotion);
1408
1409   // Update piece list
1410   pieceList[us][PAWN][pieceCount[us][PAWN]] = from;
1411   index[from] = pieceCount[us][PAWN];
1412   pieceList[us][promotion][index[to]] =
1413     pieceList[us][promotion][pieceCount[us][promotion] - 1];
1414   index[pieceList[us][promotion][index[to]]] = index[to];
1415
1416   // Update piece counts
1417   pieceCount[us][promotion]--;
1418   pieceCount[us][PAWN]++;
1419
1420   capture = u.capture;
1421
1422   if (capture)
1423   {
1424       assert(capture != KING);
1425
1426       // Insert captured piece:
1427       set_bit(&(byColorBB[them]), to);
1428       set_bit(&(byTypeBB[capture]), to);
1429       set_bit(&(byTypeBB[0]), to); // HACK: byTypeBB[0] == occupied squares
1430       board[to] = piece_of_color_and_type(them, capture);
1431
1432       // Update material. Because the move is a promotion move, we know
1433       // that the captured piece cannot be a pawn.
1434       assert(capture != PAWN);
1435       npMaterial[them] += piece_value_midgame(capture);
1436
1437       // Update piece list
1438       pieceList[them][capture][pieceCount[them][capture]] = to;
1439       index[to] = pieceCount[them][capture];
1440
1441       // Update piece count
1442       pieceCount[them][capture]++;
1443   } else
1444       board[to] = EMPTY;
1445 }
1446
1447
1448 /// Position::undo_ep_move() is a private method used to unmake an en passant
1449 /// capture. It is called from the main Position::undo_move function.  Because
1450 /// the captured piece is always a pawn, we don't need to pass an UndoInfo
1451 /// object from which to retrieve the captured piece.
1452
1453 void Position::undo_ep_move(Move m) {
1454
1455   assert(move_is_ok(m));
1456   assert(move_is_ep(m));
1457
1458   // When we have arrived here, some work has already been done by
1459   // Position::undo_move. In particular, the side to move has been switched,
1460   // so the code below is correct.
1461   Color us = side_to_move();
1462   Color them = opposite_color(us);
1463   Square from = move_from(m);
1464   Square to = move_to(m);
1465   Square capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1466
1467   assert(to == ep_square());
1468   assert(relative_rank(us, to) == RANK_6);
1469   assert(piece_on(to) == pawn_of_color(us));
1470   assert(piece_on(from) == EMPTY);
1471   assert(piece_on(capsq) == EMPTY);
1472
1473   // Replace captured piece
1474   set_bit(&(byColorBB[them]), capsq);
1475   set_bit(&(byTypeBB[PAWN]), capsq);
1476   set_bit(&(byTypeBB[0]), capsq);
1477   board[capsq] = pawn_of_color(them);
1478
1479   // Remove moving piece from destination square
1480   clear_bit(&(byColorBB[us]), to);
1481   clear_bit(&(byTypeBB[PAWN]), to);
1482   clear_bit(&(byTypeBB[0]), to);
1483   board[to] = EMPTY;
1484
1485   // Replace moving piece at source square
1486   set_bit(&(byColorBB[us]), from);
1487   set_bit(&(byTypeBB[PAWN]), from);
1488   set_bit(&(byTypeBB[0]), from);
1489   board[from] = pawn_of_color(us);
1490
1491   // Update piece list:
1492   pieceList[us][PAWN][index[to]] = from;
1493   index[from] = index[to];
1494   pieceList[them][PAWN][pieceCount[them][PAWN]] = capsq;
1495   index[capsq] = pieceCount[them][PAWN];
1496
1497   // Update piece count:
1498   pieceCount[them][PAWN]++;
1499 }
1500
1501
1502 /// Position::do_null_move makes() a "null move": It switches the side to move
1503 /// and updates the hash key without executing any move on the board.
1504
1505 void Position::do_null_move(UndoInfo &u) {
1506
1507   assert(is_ok());
1508   assert(!is_check());
1509
1510   // Back up the information necessary to undo the null move to the supplied
1511   // UndoInfo object.  In the case of a null move, the only thing we need to
1512   // remember is the last move made and the en passant square.
1513   u.lastMove = lastMove;
1514   u.epSquare = epSquare;
1515
1516   // Save the current key to the history[] array, in order to be able to
1517   // detect repetition draws.
1518   history[gamePly] = key;
1519
1520   // Update the necessary information
1521   sideToMove = opposite_color(sideToMove);
1522   if (epSquare != SQ_NONE)
1523       key ^= zobEp[epSquare];
1524
1525   epSquare = SQ_NONE;
1526   rule50++;
1527   gamePly++;
1528   key ^= zobSideToMove;
1529
1530   mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1531   egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1532
1533   assert(is_ok());
1534 }
1535
1536
1537 /// Position::undo_null_move() unmakes a "null move".
1538
1539 void Position::undo_null_move(const UndoInfo &u) {
1540
1541   assert(is_ok());
1542   assert(!is_check());
1543
1544   // Restore information from the supplied UndoInfo object:
1545   lastMove = u.lastMove;
1546   epSquare = u.epSquare;
1547   if (epSquare != SQ_NONE)
1548       key ^= zobEp[epSquare];
1549
1550   // Update the necessary information.
1551   sideToMove = opposite_color(sideToMove);
1552   rule50--;
1553   gamePly--;
1554   key ^= zobSideToMove;
1555
1556   mgValue += (sideToMove == WHITE)? TempoValueMidgame : -TempoValueMidgame;
1557   egValue += (sideToMove == WHITE)? TempoValueEndgame : -TempoValueEndgame;
1558
1559   assert(is_ok());
1560 }
1561
1562
1563 /// Position::see() is a static exchange evaluator:  It tries to estimate the
1564 /// material gain or loss resulting from a move.  There are three versions of
1565 /// this function: One which takes a destination square as input, one takes a
1566 /// move, and one which takes a 'from' and a 'to' square.  The function does
1567 /// not yet understand promotions or en passant captures.
1568
1569 int Position::see(Square to) const {
1570
1571   assert(square_is_ok(to));
1572   return see(SQ_NONE, to);
1573 }
1574
1575 int Position::see(Move m) const {
1576
1577   assert(move_is_ok(m));
1578   return see(move_from(m), move_to(m));
1579 }
1580
1581 int Position::see(Square from, Square to) const {
1582
1583   // Material values
1584   static const int seeValues[18] = {
1585     0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1586        RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1587     0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1588        RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1589     0, 0
1590   };
1591
1592   Bitboard attackers, occ, b;
1593
1594   assert(square_is_ok(from) || from == SQ_NONE);
1595   assert(square_is_ok(to));
1596
1597   // Initialize colors
1598   Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1599   Color them = opposite_color(us);
1600
1601   // Initialize pieces
1602   Piece piece = piece_on(from);
1603   Piece capture = piece_on(to);
1604
1605   // Find all attackers to the destination square, with the moving piece
1606   // removed, but possibly an X-ray attacker added behind it.
1607   occ = occupied_squares();
1608
1609   // Handle enpassant moves
1610   if (ep_square() == to && type_of_piece_on(from) == PAWN)
1611   {
1612       assert(capture == EMPTY);
1613
1614       Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1615       capture = piece_on(capQq);
1616
1617       assert(type_of_piece_on(capQq) == PAWN);
1618
1619       // Remove the captured pawn
1620       clear_bit(&occ, capQq);
1621   }
1622
1623   while (true)
1624   {
1625       clear_bit(&occ, from);
1626       attackers =  (rook_attacks_bb(to, occ)   & rooks_and_queens())
1627                  | (bishop_attacks_bb(to, occ) & bishops_and_queens())
1628                  | (piece_attacks<KNIGHT>(to)  & knights())
1629                  | (piece_attacks<KING>(to)    & kings())
1630                  | (pawn_attacks(WHITE, to)    & pawns(BLACK))
1631                  | (pawn_attacks(BLACK, to)    & pawns(WHITE));
1632
1633       if (from != SQ_NONE)
1634           break;
1635
1636       // If we don't have any attacker we are finished
1637       if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1638           return 0;
1639
1640       // Locate the least valuable attacker to the destination square
1641       // and use it to initialize from square.
1642       PieceType pt;
1643       for (pt = PAWN; !(attackers & pieces_of_color_and_type(us, pt)); pt++)
1644           assert(pt < KING);
1645
1646       from = first_1(attackers & pieces_of_color_and_type(us, pt));
1647       piece = piece_on(from);
1648   }
1649
1650   // If the opponent has no attackers we are finished
1651   if ((attackers & pieces_of_color(them)) == EmptyBoardBB)
1652       return seeValues[capture];
1653
1654   attackers &= occ; // Remove the moving piece
1655
1656   // The destination square is defended, which makes things rather more
1657   // difficult to compute. We proceed by building up a "swap list" containing
1658   // the material gain or loss at each stop in a sequence of captures to the
1659   // destination square, where the sides alternately capture, and always
1660   // capture with the least valuable piece. After each capture, we look for
1661   // new X-ray attacks from behind the capturing piece.
1662   int lastCapturingPieceValue = seeValues[piece];
1663   int swapList[32], n = 1;
1664   Color c = them;
1665   PieceType pt;
1666
1667   swapList[0] = seeValues[capture];
1668
1669   do {
1670       // Locate the least valuable attacker for the side to move.  The loop
1671       // below looks like it is potentially infinite, but it isn't. We know
1672       // that the side to move still has at least one attacker left.
1673       for (pt = PAWN; !(attackers & pieces_of_color_and_type(c, pt)); pt++)
1674           assert(pt < KING);
1675
1676       // Remove the attacker we just found from the 'attackers' bitboard,
1677       // and scan for new X-ray attacks behind the attacker.
1678       b = attackers & pieces_of_color_and_type(c, pt);
1679       occ ^= (b & -b);
1680       attackers |=  (rook_attacks_bb(to, occ) & rooks_and_queens())
1681                   | (bishop_attacks_bb(to, occ) & bishops_and_queens());
1682
1683       attackers &= occ;
1684
1685       // Add the new entry to the swap list
1686       assert(n < 32);
1687       swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1688       n++;
1689
1690       // Remember the value of the capturing piece, and change the side to move
1691       // before beginning the next iteration
1692       lastCapturingPieceValue = seeValues[pt];
1693       c = opposite_color(c);
1694
1695       // Stop after a king capture
1696       if (pt == KING && (attackers & pieces_of_color(c)))
1697       {
1698           assert(n < 32);
1699           swapList[n++] = 100;
1700           break;
1701       }
1702   } while (attackers & pieces_of_color(c));
1703
1704   // Having built the swap list, we negamax through it to find the best
1705   // achievable score from the point of view of the side to move
1706   while (--n)
1707       swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1708
1709   return swapList[0];
1710 }
1711
1712
1713 /// Position::clear() erases the position object to a pristine state, with an
1714 /// empty board, white to move, and no castling rights.
1715
1716 void Position::clear() {
1717
1718   for (int i = 0; i < 64; i++)
1719   {
1720       board[i] = EMPTY;
1721       index[i] = 0;
1722   }
1723
1724   for (int i = 0; i < 2; i++)
1725       byColorBB[i] = EmptyBoardBB;
1726
1727   for (int i = 0; i < 7; i++)
1728   {
1729       byTypeBB[i] = EmptyBoardBB;
1730       pieceCount[0][i] = pieceCount[1][i] = 0;
1731       for (int j = 0; j < 8; j++)
1732           pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1733   }
1734
1735   checkersBB = EmptyBoardBB;
1736
1737   lastMove = MOVE_NONE;
1738
1739   sideToMove = WHITE;
1740   castleRights = NO_CASTLES;
1741   initialKFile = FILE_E;
1742   initialKRFile = FILE_H;
1743   initialQRFile = FILE_A;
1744   epSquare = SQ_NONE;
1745   rule50 = 0;
1746   gamePly = 0;
1747 }
1748
1749
1750 /// Position::reset_game_ply() simply sets gamePly to 0.  It is used from the
1751 /// UCI interface code, whenever a non-reversible move is made in a
1752 /// 'position fen <fen> moves m1 m2 ...' command.  This makes it possible
1753 /// for the program to handle games of arbitrary length, as long as the GUI
1754 /// handles draws by the 50 move rule correctly.
1755
1756 void Position::reset_game_ply() {
1757
1758   gamePly = 0;
1759 }
1760
1761
1762 /// Position::put_piece() puts a piece on the given square of the board,
1763 /// updating the board array, bitboards, and piece counts.
1764
1765 void Position::put_piece(Piece p, Square s) {
1766
1767   Color c = color_of_piece(p);
1768   PieceType pt = type_of_piece(p);
1769
1770   board[s] = p;
1771   index[s] = pieceCount[c][pt];
1772   pieceList[c][pt][index[s]] = s;
1773
1774   set_bit(&(byTypeBB[pt]), s);
1775   set_bit(&(byColorBB[c]), s);
1776   set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1777
1778   pieceCount[c][pt]++;
1779
1780   if (pt == KING)
1781       kingSquare[c] = s;
1782 }
1783
1784
1785 /// Position::allow_oo() gives the given side the right to castle kingside.
1786 /// Used when setting castling rights during parsing of FEN strings.
1787
1788 void Position::allow_oo(Color c) {
1789
1790   castleRights |= (1 + int(c));
1791 }
1792
1793
1794 /// Position::allow_ooo() gives the given side the right to castle queenside.
1795 /// Used when setting castling rights during parsing of FEN strings.
1796
1797 void Position::allow_ooo(Color c) {
1798
1799   castleRights |= (4 + 4*int(c));
1800 }
1801
1802
1803 /// Position::compute_key() computes the hash key of the position. The hash
1804 /// key is usually updated incrementally as moves are made and unmade, the
1805 /// compute_key() function is only used when a new position is set up, and
1806 /// to verify the correctness of the hash key when running in debug mode.
1807
1808 Key Position::compute_key() const {
1809
1810   Key result = Key(0ULL);
1811
1812   for (Square s = SQ_A1; s <= SQ_H8; s++)
1813       if (square_is_occupied(s))
1814           result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1815
1816   if (ep_square() != SQ_NONE)
1817       result ^= zobEp[ep_square()];
1818
1819   result ^= zobCastle[castleRights];
1820   if (side_to_move() == BLACK)
1821       result ^= zobSideToMove;
1822
1823   return result;
1824 }
1825
1826
1827 /// Position::compute_pawn_key() computes the hash key of the position.  The
1828 /// hash key is usually updated incrementally as moves are made and unmade,
1829 /// the compute_pawn_key() function is only used when a new position is set
1830 /// up, and to verify the correctness of the pawn hash key when running in
1831 /// debug mode.
1832
1833 Key Position::compute_pawn_key() const {
1834
1835   Key result = Key(0ULL);
1836   Bitboard b;
1837   Square s;
1838
1839   for (Color c = WHITE; c <= BLACK; c++)
1840   {
1841       b = pawns(c);
1842       while(b)
1843       {
1844           s = pop_1st_bit(&b);
1845           result ^= zobrist[c][PAWN][s];
1846       }
1847   }
1848   return result;
1849 }
1850
1851
1852 /// Position::compute_material_key() computes the hash key of the position.
1853 /// The hash key is usually updated incrementally as moves are made and unmade,
1854 /// the compute_material_key() function is only used when a new position is set
1855 /// up, and to verify the correctness of the material hash key when running in
1856 /// debug mode.
1857
1858 Key Position::compute_material_key() const {
1859
1860   Key result = Key(0ULL);
1861   for (Color c = WHITE; c <= BLACK; c++)
1862       for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1863       {
1864           int count = piece_count(c, pt);
1865           for (int i = 0; i <= count; i++)
1866               result ^= zobMaterial[c][pt][i];
1867       }
1868   return result;
1869 }
1870
1871
1872 /// Position::compute_mg_value() and Position::compute_eg_value() compute the
1873 /// incremental scores for the middle game and the endgame.  These functions
1874 /// are used to initialize the incremental scores when a new position is set
1875 /// up, and to verify that the scores are correctly updated by do_move
1876 /// and undo_move when the program is running in debug mode.
1877
1878 Value Position::compute_mg_value() const {
1879
1880   Value result = Value(0);
1881   Bitboard b;
1882   Square s;
1883
1884   for (Color c = WHITE; c <= BLACK; c++)
1885       for (PieceType pt = PAWN; pt <= KING; pt++)
1886       {
1887           b = pieces_of_color_and_type(c, pt);
1888           while(b)
1889           {
1890               s = pop_1st_bit(&b);
1891               assert(piece_on(s) == piece_of_color_and_type(c, pt));
1892               result += mg_pst(c, pt, s);
1893           }
1894       }
1895   result += (side_to_move() == WHITE)? TempoValueMidgame / 2 : -TempoValueMidgame / 2;
1896   return result;
1897 }
1898
1899 Value Position::compute_eg_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 += eg_pst(c, pt, s);
1914         }
1915     }
1916   result += (side_to_move() == WHITE)? TempoValueEndgame / 2 : -TempoValueEndgame / 2;
1917   return result;
1918 }
1919
1920
1921 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1922 /// game material score for the given side.  Material scores are updated
1923 /// incrementally during the search, this function is only used while
1924 /// initializing a new Position object.
1925
1926 Value Position::compute_non_pawn_material(Color c) const {
1927
1928   Value result = Value(0);
1929   Square s;
1930
1931   for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1932   {
1933       Bitboard b = pieces_of_color_and_type(c, pt);
1934       while(b)
1935       {
1936           s = pop_1st_bit(&b);
1937           assert(piece_on(s) == piece_of_color_and_type(c, pt));
1938           result += piece_value_midgame(pt);
1939       }
1940   }
1941   return result;
1942 }
1943
1944
1945 /// Position::is_mate() returns true or false depending on whether the
1946 /// side to move is checkmated. Note that this function is currently very
1947 /// slow, and shouldn't be used frequently inside the search.
1948
1949 bool Position::is_mate() const {
1950
1951   if (is_check())
1952   {
1953       MovePicker mp = MovePicker(*this, false, MOVE_NONE, EmptySearchStack, Depth(0));
1954       return mp.get_next_move() == MOVE_NONE;
1955   }
1956   return false;
1957 }
1958
1959
1960 /// Position::is_draw() tests whether the position is drawn by material,
1961 /// repetition, or the 50 moves rule.  It does not detect stalemates, this
1962 /// must be done by the search.
1963
1964 bool Position::is_draw() const {
1965
1966   // Draw by material?
1967   if (   !pawns()
1968       && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1969       return true;
1970
1971   // Draw by the 50 moves rule?
1972   if (rule50 > 100 || (rule50 == 100 && !is_check()))
1973       return true;
1974
1975   // Draw by repetition?
1976   for (int i = 2; i < Min(gamePly, rule50); i += 2)
1977       if (history[gamePly - i] == key)
1978           return true;
1979
1980   return false;
1981 }
1982
1983
1984 /// Position::has_mate_threat() tests whether a given color has a mate in one
1985 /// from the current position. This function is quite slow, but it doesn't
1986 /// matter, because it is currently only called from PV nodes, which are rare.
1987
1988 bool Position::has_mate_threat(Color c) {
1989
1990   UndoInfo u1, u2;
1991   Color stm = side_to_move();
1992
1993   // The following lines are useless and silly, but prevents gcc from
1994   // emitting a stupid warning stating that u1.lastMove and u1.epSquare might
1995   // be used uninitialized.
1996   u1.lastMove = lastMove;
1997   u1.epSquare = epSquare;
1998
1999   if (is_check())
2000       return false;
2001
2002   // If the input color is not equal to the side to move, do a null move
2003   if (c != stm)
2004       do_null_move(u1);
2005
2006   MoveStack mlist[120];
2007   int count;
2008   bool result = false;
2009
2010   // Generate legal moves
2011   count = generate_legal_moves(*this, mlist);
2012
2013   // Loop through the moves, and see if one of them is mate
2014   for (int i = 0; i < count; i++)
2015   {
2016       do_move(mlist[i].move, u2);
2017       if (is_mate())
2018           result = true;
2019
2020       undo_move(mlist[i].move, u2);
2021   }
2022
2023   // Undo null move, if necessary
2024   if (c != stm)
2025       undo_null_move(u1);
2026
2027   return result;
2028 }
2029
2030
2031 /// Position::init_zobrist() is a static member function which initializes the
2032 /// various arrays used to compute hash keys.
2033
2034 void Position::init_zobrist() {
2035
2036   for (int i = 0; i < 2; i++)
2037       for (int j = 0; j < 8; j++)
2038           for (int k = 0; k < 64; k++)
2039               zobrist[i][j][k] = Key(genrand_int64());
2040
2041   for (int i = 0; i < 64; i++)
2042       zobEp[i] = Key(genrand_int64());
2043
2044   for (int i = 0; i < 16; i++)
2045       zobCastle[i] = genrand_int64();
2046
2047   zobSideToMove = genrand_int64();
2048
2049   for (int i = 0; i < 2; i++)
2050       for (int j = 0; j < 8; j++)
2051           for (int k = 0; k < 16; k++)
2052               zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
2053
2054   for (int i = 0; i < 16; i++)
2055       zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
2056 }
2057
2058
2059 /// Position::init_piece_square_tables() initializes the piece square tables.
2060 /// This is a two-step operation:  First, the white halves of the tables are
2061 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
2062 /// added to each entry if the "Randomness" UCI parameter is non-zero.
2063 /// Second, the black halves of the tables are initialized by mirroring
2064 /// and changing the sign of the corresponding white scores.
2065
2066 void Position::init_piece_square_tables() {
2067
2068   int r = get_option_value_int("Randomness"), i;
2069   for (Square s = SQ_A1; s <= SQ_H8; s++)
2070       for (Piece p = WP; p <= WK; p++)
2071       {
2072           i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
2073           MgPieceSquareTable[p][s] = Value(MgPST[p][s] + i);
2074           EgPieceSquareTable[p][s] = Value(EgPST[p][s] + i);
2075       }
2076
2077   for (Square s = SQ_A1; s <= SQ_H8; s++)
2078       for (Piece p = BP; p <= BK; p++)
2079       {
2080           MgPieceSquareTable[p][s] = -MgPieceSquareTable[p-8][flip_square(s)];
2081           EgPieceSquareTable[p][s] = -EgPieceSquareTable[p-8][flip_square(s)];
2082       }
2083 }
2084
2085
2086 /// Position::flipped_copy() makes a copy of the input position, but with
2087 /// the white and black sides reversed.  This is only useful for debugging,
2088 /// especially for finding evaluation symmetry bugs.
2089
2090 void Position::flipped_copy(const Position &pos) {
2091
2092   assert(pos.is_ok());
2093
2094   clear();
2095
2096   // Board
2097   for (Square s = SQ_A1; s <= SQ_H8; s++)
2098       if (!pos.square_is_empty(s))
2099           put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
2100
2101   // Side to move
2102   sideToMove = opposite_color(pos.side_to_move());
2103
2104   // Castling rights
2105   if (pos.can_castle_kingside(WHITE))  allow_oo(BLACK);
2106   if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
2107   if (pos.can_castle_kingside(BLACK))  allow_oo(WHITE);
2108   if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
2109
2110   initialKFile  = pos.initialKFile;
2111   initialKRFile = pos.initialKRFile;
2112   initialQRFile = pos.initialQRFile;
2113
2114   for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
2115       castleRightsMask[sq] = ALL_CASTLES;
2116
2117   castleRightsMask[make_square(initialKFile,  RANK_1)] ^= (WHITE_OO | WHITE_OOO);
2118   castleRightsMask[make_square(initialKFile,  RANK_8)] ^= (BLACK_OO | BLACK_OOO);
2119   castleRightsMask[make_square(initialKRFile, RANK_1)] ^=  WHITE_OO;
2120   castleRightsMask[make_square(initialKRFile, RANK_8)] ^=  BLACK_OO;
2121   castleRightsMask[make_square(initialQRFile, RANK_1)] ^=  WHITE_OOO;
2122   castleRightsMask[make_square(initialQRFile, RANK_8)] ^=  BLACK_OOO;
2123
2124   // En passant square
2125   if (pos.epSquare != SQ_NONE)
2126       epSquare = flip_square(pos.epSquare);
2127
2128   // Checkers
2129   find_checkers();
2130
2131   // Hash keys
2132   key = compute_key();
2133   pawnKey = compute_pawn_key();
2134   materialKey = compute_material_key();
2135
2136   // Incremental scores
2137   mgValue = compute_mg_value();
2138   egValue = compute_eg_value();
2139
2140   // Material
2141   npMaterial[WHITE] = compute_non_pawn_material(WHITE);
2142   npMaterial[BLACK] = compute_non_pawn_material(BLACK);
2143
2144   assert(is_ok());
2145 }
2146
2147
2148 /// Position::is_ok() performs some consitency checks for the position object.
2149 /// This is meant to be helpful when debugging.
2150
2151 bool Position::is_ok(int* failedStep) const {
2152
2153   // What features of the position should be verified?
2154   static const bool debugBitboards = false;
2155   static const bool debugKingCount = false;
2156   static const bool debugKingCapture = false;
2157   static const bool debugCheckerCount = false;
2158   static const bool debugKey = false;
2159   static const bool debugMaterialKey = false;
2160   static const bool debugPawnKey = false;
2161   static const bool debugIncrementalEval = false;
2162   static const bool debugNonPawnMaterial = false;
2163   static const bool debugPieceCounts = false;
2164   static const bool debugPieceList = false;
2165
2166   if (failedStep) *failedStep = 1;
2167
2168   // Side to move OK?
2169   if (!color_is_ok(side_to_move()))
2170       return false;
2171
2172   // Are the king squares in the position correct?
2173   if (failedStep) (*failedStep)++;
2174   if (piece_on(king_square(WHITE)) != WK)
2175       return false;
2176
2177   if (failedStep) (*failedStep)++;
2178   if (piece_on(king_square(BLACK)) != BK)
2179       return false;
2180
2181   // Castle files OK?
2182   if (failedStep) (*failedStep)++;
2183   if (!file_is_ok(initialKRFile))
2184       return false;
2185
2186   if (!file_is_ok(initialQRFile))
2187       return false;
2188
2189   // Do both sides have exactly one king?
2190   if (failedStep) (*failedStep)++;
2191   if (debugKingCount)
2192   {
2193       int kingCount[2] = {0, 0};
2194       for (Square s = SQ_A1; s <= SQ_H8; s++)
2195           if (type_of_piece_on(s) == KING)
2196               kingCount[color_of_piece_on(s)]++;
2197
2198       if(kingCount[0] != 1 || kingCount[1] != 1)
2199           return false;
2200   }
2201
2202   // Can the side to move capture the opponent's king?
2203   if (failedStep) (*failedStep)++;
2204   if (debugKingCapture)
2205   {
2206       Color us = side_to_move();
2207       Color them = opposite_color(us);
2208       Square ksq = king_square(them);
2209       if (square_is_attacked(ksq, us))
2210           return false;
2211   }
2212
2213   // Is there more than 2 checkers?
2214   if (failedStep) (*failedStep)++;
2215   if (debugCheckerCount && count_1s(checkersBB) > 2)
2216       return false;
2217
2218   // Bitboards OK?
2219   if (failedStep) (*failedStep)++;
2220   if (debugBitboards)
2221   {
2222       // The intersection of the white and black pieces must be empty
2223       if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
2224           return false;
2225
2226       // The union of the white and black pieces must be equal to all
2227       // occupied squares
2228       if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
2229           return false;
2230
2231       // Separate piece type bitboards must have empty intersections
2232       for (PieceType p1 = PAWN; p1 <= KING; p1++)
2233           for (PieceType p2 = PAWN; p2 <= KING; p2++)
2234               if (p1 != p2 && (pieces_of_type(p1) & pieces_of_type(p2)))
2235                   return false;
2236   }
2237
2238   // En passant square OK?
2239   if (failedStep) (*failedStep)++;
2240   if (ep_square() != SQ_NONE)
2241   {
2242       // The en passant square must be on rank 6, from the point of view of the
2243       // side to move.
2244       if (relative_rank(side_to_move(), ep_square()) != RANK_6)
2245           return false;
2246   }
2247
2248   // Hash key OK?
2249   if (failedStep) (*failedStep)++;
2250   if (debugKey && key != compute_key())
2251       return false;
2252
2253   // Pawn hash key OK?
2254   if (failedStep) (*failedStep)++;
2255   if (debugPawnKey && pawnKey != compute_pawn_key())
2256       return false;
2257
2258   // Material hash key OK?
2259   if (failedStep) (*failedStep)++;
2260   if (debugMaterialKey && materialKey != compute_material_key())
2261       return false;
2262
2263   // Incremental eval OK?
2264   if (failedStep) (*failedStep)++;
2265   if (debugIncrementalEval)
2266   {
2267       if (mgValue != compute_mg_value())
2268           return false;
2269
2270       if (egValue != compute_eg_value())
2271           return false;
2272   }
2273
2274   // Non-pawn material OK?
2275   if (failedStep) (*failedStep)++;
2276   if (debugNonPawnMaterial)
2277   {
2278       if(npMaterial[WHITE] != compute_non_pawn_material(WHITE))
2279           return false;
2280
2281       if(npMaterial[BLACK] != compute_non_pawn_material(BLACK))
2282           return false;
2283   }
2284
2285   // Piece counts OK?
2286   if (failedStep) (*failedStep)++;
2287   if (debugPieceCounts)
2288       for (Color c = WHITE; c <= BLACK; c++)
2289           for (PieceType pt = PAWN; pt <= KING; pt++)
2290               if (pieceCount[c][pt] != count_1s(pieces_of_color_and_type(c, pt)))
2291                   return false;
2292
2293   if (failedStep) (*failedStep)++;
2294   if (debugPieceList)
2295   {
2296       for(Color c = WHITE; c <= BLACK; c++)
2297           for(PieceType pt = PAWN; pt <= KING; pt++)
2298               for(int i = 0; i < pieceCount[c][pt]; i++)
2299               {
2300                   if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2301                       return false;
2302
2303                   if (index[piece_list(c, pt, i)] != i)
2304                       return false;
2305               }
2306   }
2307   if (failedStep) *failedStep = 0;
2308   return true;
2309 }