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