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