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