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