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