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