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