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