]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
Don't update gamePly after each move
[stockfish] / src / movegen.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-2010 Marco Costalba, Joona Kiiski, Tord Romstad
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 #include <cassert>
21
22 #include "bitcount.h"
23 #include "movegen.h"
24 #include "position.h"
25
26 // Simple macro to wrap a very common while loop, no facny, no flexibility,
27 // hardcoded list name 'mlist' and from square 'from'.
28 #define SERIALIZE_MOVES(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
29
30 // Version used for pawns, where the 'from' square is given as a delta from the 'to' square
31 #define SERIALIZE_MOVES_D(b, d) while (b) { to = pop_1st_bit(&b); (*mlist++).move = make_move(to + (d), to); }
32
33 namespace {
34
35   enum CastlingSide {
36     KING_SIDE,
37     QUEEN_SIDE
38   };
39
40   template<CastlingSide>
41   MoveStack* generate_castle_moves(const Position&, MoveStack*, Color us);
42
43   template<Color, MoveType>
44   MoveStack* generate_pawn_moves(const Position&, MoveStack*, Bitboard, Square);
45
46   template<PieceType Pt>
47   inline MoveStack* generate_discovered_checks(const Position& pos, MoveStack* mlist, Square from) {
48
49     assert(Pt != QUEEN);
50     assert(Pt != PAWN);
51
52     Bitboard b = pos.attacks_from<Pt>(from) & pos.empty_squares();
53
54     if (Pt == KING)
55         b &= ~QueenPseudoAttacks[pos.king_square(opposite_color(pos.side_to_move()))];
56
57     SERIALIZE_MOVES(b);
58     return mlist;
59   }
60
61   template<PieceType Pt>
62   inline MoveStack* generate_direct_checks(const Position& pos, MoveStack* mlist, Color us,
63                                            Bitboard dc, Square ksq) {
64     assert(Pt != KING);
65     assert(Pt != PAWN);
66
67     Bitboard checkSqs, b;
68     Square from;
69     const Square* pl = pos.piece_list(us, Pt);
70
71     if ((from = *pl++) == SQ_NONE)
72         return mlist;
73
74     checkSqs = pos.attacks_from<Pt>(ksq) & pos.empty_squares();
75
76     do
77     {
78         if (   (Pt == QUEEN  && !(QueenPseudoAttacks[from]  & checkSqs))
79             || (Pt == ROOK   && !(RookPseudoAttacks[from]   & checkSqs))
80             || (Pt == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
81             continue;
82
83         if (dc && bit_is_set(dc, from))
84             continue;
85
86         b = pos.attacks_from<Pt>(from) & checkSqs;
87         SERIALIZE_MOVES(b);
88
89     } while ((from = *pl++) != SQ_NONE);
90
91     return mlist;
92   }
93
94   template<>
95   FORCE_INLINE MoveStack* generate_direct_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
96
97     return (us == WHITE ? generate_pawn_moves<WHITE, MV_CHECK>(p, m, dc, ksq)
98                         : generate_pawn_moves<BLACK, MV_CHECK>(p, m, dc, ksq));
99   }
100
101   template<PieceType Pt, MoveType Type>
102   FORCE_INLINE MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us, Bitboard t) {
103
104     assert(Pt == PAWN);
105     assert(Type == MV_CAPTURE || Type == MV_NON_CAPTURE || Type == MV_EVASION);
106
107     return (us == WHITE ? generate_pawn_moves<WHITE, Type>(p, m, t, SQ_NONE)
108                         : generate_pawn_moves<BLACK, Type>(p, m, t, SQ_NONE));
109   }
110
111   template<PieceType Pt>
112   FORCE_INLINE MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
113
114     Bitboard b;
115     Square from;
116     const Square* pl = pos.piece_list(us, Pt);
117
118     if (*pl != SQ_NONE)
119     {
120         do {
121             from = *pl;
122             b = pos.attacks_from<Pt>(from) & target;
123             SERIALIZE_MOVES(b);
124         } while (*++pl != SQ_NONE);
125     }
126     return mlist;
127   }
128
129   template<>
130   FORCE_INLINE MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
131
132     Bitboard b;
133     Square from = pos.king_square(us);
134
135     b = pos.attacks_from<KING>(from) & target;
136     SERIALIZE_MOVES(b);
137     return mlist;
138   }
139
140 }
141
142
143 /// generate<MV_CAPTURE> generates all pseudo-legal captures and queen
144 /// promotions. Returns a pointer to the end of the move list.
145 ///
146 /// generate<MV_NON_CAPTURE> generates all pseudo-legal non-captures and
147 /// underpromotions. Returns a pointer to the end of the move list.
148 ///
149 /// generate<MV_NON_EVASION> generates all pseudo-legal captures and
150 /// non-captures. Returns a pointer to the end of the move list.
151
152 template<MoveType Type>
153 MoveStack* generate(const Position& pos, MoveStack* mlist) {
154
155   assert(!pos.in_check());
156
157   Color us = pos.side_to_move();
158   Bitboard target;
159
160   if (Type == MV_CAPTURE || Type == MV_NON_EVASION)
161       target = pos.pieces(opposite_color(us));
162   else if (Type == MV_NON_CAPTURE)
163       target = pos.empty_squares();
164   else
165       assert(false);
166
167   if (Type == MV_NON_EVASION)
168   {
169       mlist = generate_piece_moves<PAWN, MV_CAPTURE>(pos, mlist, us, target);
170       mlist = generate_piece_moves<PAWN, MV_NON_CAPTURE>(pos, mlist, us, pos.empty_squares());
171       target |= pos.empty_squares();
172   }
173   else
174       mlist = generate_piece_moves<PAWN, Type>(pos, mlist, us, target);
175
176   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
177   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
178   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
179   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
180   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
181
182   if (Type != MV_CAPTURE && pos.can_castle(us))
183   {
184       if (pos.can_castle(us == WHITE ? WHITE_OO : BLACK_OO))
185           mlist = generate_castle_moves<KING_SIDE>(pos, mlist, us);
186
187       if (pos.can_castle(us == WHITE ? WHITE_OOO : BLACK_OOO))
188           mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist, us);
189   }
190
191   return mlist;
192 }
193
194 // Explicit template instantiations
195 template MoveStack* generate<MV_CAPTURE>(const Position& pos, MoveStack* mlist);
196 template MoveStack* generate<MV_NON_CAPTURE>(const Position& pos, MoveStack* mlist);
197 template MoveStack* generate<MV_NON_EVASION>(const Position& pos, MoveStack* mlist);
198
199
200 /// generate_non_capture_checks() generates all pseudo-legal non-captures and knight
201 /// underpromotions that give check. Returns a pointer to the end of the move list.
202 template<>
203 MoveStack* generate<MV_NON_CAPTURE_CHECK>(const Position& pos, MoveStack* mlist) {
204
205   assert(!pos.in_check());
206
207   Bitboard b, dc;
208   Square from;
209   Color us = pos.side_to_move();
210   Square ksq = pos.king_square(opposite_color(us));
211
212   assert(pos.piece_on(ksq) == make_piece(opposite_color(us), KING));
213
214   // Discovered non-capture checks
215   b = dc = pos.discovered_check_candidates();
216
217   while (b)
218   {
219      from = pop_1st_bit(&b);
220      switch (piece_type(pos.piece_on(from)))
221      {
222       case PAWN:   /* Will be generated togheter with pawns direct checks */     break;
223       case KNIGHT: mlist = generate_discovered_checks<KNIGHT>(pos, mlist, from); break;
224       case BISHOP: mlist = generate_discovered_checks<BISHOP>(pos, mlist, from); break;
225       case ROOK:   mlist = generate_discovered_checks<ROOK>(pos, mlist, from);   break;
226       case KING:   mlist = generate_discovered_checks<KING>(pos, mlist, from);   break;
227       default: assert(false); break;
228      }
229   }
230
231   // Direct non-capture checks
232   mlist = generate_direct_checks<PAWN>(pos, mlist, us, dc, ksq);
233   mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, dc, ksq);
234   mlist = generate_direct_checks<BISHOP>(pos, mlist, us, dc, ksq);
235   mlist = generate_direct_checks<ROOK>(pos, mlist, us, dc, ksq);
236   return  generate_direct_checks<QUEEN>(pos, mlist, us, dc, ksq);
237 }
238
239
240 /// generate_evasions() generates all pseudo-legal check evasions when
241 /// the side to move is in check. Returns a pointer to the end of the move list.
242 template<>
243 MoveStack* generate<MV_EVASION>(const Position& pos, MoveStack* mlist) {
244
245   assert(pos.in_check());
246
247   Bitboard b, target;
248   Square from, checksq;
249   int checkersCnt = 0;
250   Color us = pos.side_to_move();
251   Square ksq = pos.king_square(us);
252   Bitboard checkers = pos.checkers();
253   Bitboard sliderAttacks = EmptyBoardBB;
254
255   assert(pos.piece_on(ksq) == make_piece(us, KING));
256   assert(checkers);
257
258   // Find squares attacked by slider checkers, we will remove
259   // them from the king evasions set so to early skip known
260   // illegal moves and avoid an useless legality check later.
261   b = checkers;
262   do
263   {
264       checkersCnt++;
265       checksq = pop_1st_bit(&b);
266
267       assert(piece_color(pos.piece_on(checksq)) == opposite_color(us));
268
269       switch (piece_type(pos.piece_on(checksq)))
270       {
271       case BISHOP: sliderAttacks |= BishopPseudoAttacks[checksq]; break;
272       case ROOK:   sliderAttacks |= RookPseudoAttacks[checksq];   break;
273       case QUEEN:
274           // If queen and king are far we can safely remove all the squares attacked
275           // in the other direction becuase are not reachable by the king anyway.
276           if (squares_between(ksq, checksq) || (RookPseudoAttacks[checksq] & (1ULL << ksq)))
277               sliderAttacks |= QueenPseudoAttacks[checksq];
278
279           // Otherwise, if king and queen are adjacent and on a diagonal line, we need to
280           // use real rook attacks to check if king is safe to move in the other direction.
281           // For example: king in B2, queen in A1 a knight in B1, and we can safely move to C1.
282           else
283               sliderAttacks |= BishopPseudoAttacks[checksq] | pos.attacks_from<ROOK>(checksq);
284
285       default:
286           break;
287       }
288   } while (b);
289
290   // Generate evasions for king, capture and non capture moves
291   b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
292   from = ksq;
293   SERIALIZE_MOVES(b);
294
295   // Generate evasions for other pieces only if not double check
296   if (checkersCnt > 1)
297       return mlist;
298
299   // Find squares where a blocking evasion or a capture of the
300   // checker piece is possible.
301   target = squares_between(checksq, ksq) | checkers;
302
303   mlist = generate_piece_moves<PAWN, MV_EVASION>(pos, mlist, us, target);
304   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
305   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
306   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
307   return  generate_piece_moves<QUEEN>(pos, mlist, us, target);
308 }
309
310
311 /// generate<MV_LEGAL> computes a complete list of legal moves in the current position
312
313 template<>
314 MoveStack* generate<MV_LEGAL>(const Position& pos, MoveStack* mlist) {
315
316   MoveStack *last, *cur = mlist;
317   Bitboard pinned = pos.pinned_pieces();
318
319   last = pos.in_check() ? generate<MV_EVASION>(pos, mlist)
320                         : generate<MV_NON_EVASION>(pos, mlist);
321
322   // Remove illegal moves from the list
323   while (cur != last)
324       if (!pos.pl_move_is_legal(cur->move, pinned))
325           cur->move = (--last)->move;
326       else
327           cur++;
328
329   return last;
330 }
331
332
333 namespace {
334
335   template<Square Delta>
336   inline Bitboard move_pawns(Bitboard p) {
337
338     return Delta == DELTA_N  ? p << 8 : Delta == DELTA_S  ? p >> 8 :
339            Delta == DELTA_NE ? p << 9 : Delta == DELTA_SE ? p >> 7 :
340            Delta == DELTA_NW ? p << 7 : Delta == DELTA_SW ? p >> 9 : p;
341   }
342
343   template<MoveType Type, Square Delta>
344   inline MoveStack* generate_pawn_captures(MoveStack* mlist, Bitboard pawns, Bitboard target) {
345
346     const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
347
348     Bitboard b;
349     Square to;
350
351     // Captures in the a1-h8 (a8-h1 for black) diagonal or in the h1-a8 (h8-a1 for black)
352     b = move_pawns<Delta>(pawns) & target & ~TFileABB;
353     SERIALIZE_MOVES_D(b, -Delta);
354     return mlist;
355   }
356
357   template<MoveType Type, Square Delta>
358   inline MoveStack* generate_promotions(const Position& pos, MoveStack* mlist, Bitboard pawnsOn7, Bitboard target) {
359
360     const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
361
362     Bitboard b;
363     Square to;
364
365     // Promotions and under-promotions, both captures and non-captures
366     b = move_pawns<Delta>(pawnsOn7) & target;
367
368     if (Delta != DELTA_N && Delta != DELTA_S)
369         b &= ~TFileABB;
370
371     while (b)
372     {
373         to = pop_1st_bit(&b);
374
375         if (Type == MV_CAPTURE || Type == MV_EVASION)
376             (*mlist++).move = make_promotion_move(to - Delta, to, QUEEN);
377
378         if (Type == MV_NON_CAPTURE || Type == MV_EVASION)
379         {
380             (*mlist++).move = make_promotion_move(to - Delta, to, ROOK);
381             (*mlist++).move = make_promotion_move(to - Delta, to, BISHOP);
382             (*mlist++).move = make_promotion_move(to - Delta, to, KNIGHT);
383         }
384
385         // This is the only possible under promotion that can give a check
386         // not already included in the queen-promotion.
387         if (   Type == MV_CHECK
388             && bit_is_set(pos.attacks_from<KNIGHT>(to), pos.king_square(Delta > 0 ? BLACK : WHITE)))
389             (*mlist++).move = make_promotion_move(to - Delta, to, KNIGHT);
390         else (void)pos; // Silence a warning under MSVC
391     }
392     return mlist;
393   }
394
395   template<Color Us, MoveType Type>
396   MoveStack* generate_pawn_moves(const Position& pos, MoveStack* mlist, Bitboard target, Square ksq) {
397
398     // Calculate our parametrized parameters at compile time, named
399     // according to the point of view of white side.
400     const Color    Them      = (Us == WHITE ? BLACK    : WHITE);
401     const Bitboard TRank7BB  = (Us == WHITE ? Rank7BB  : Rank2BB);
402     const Bitboard TRank3BB  = (Us == WHITE ? Rank3BB  : Rank6BB);
403     const Square   UP        = (Us == WHITE ? DELTA_N  : DELTA_S);
404     const Square   RIGHT_UP  = (Us == WHITE ? DELTA_NE : DELTA_SW);
405     const Square   LEFT_UP   = (Us == WHITE ? DELTA_NW : DELTA_SE);
406
407     Square to;
408     Bitboard b1, b2, dc1, dc2, pawnPushes, emptySquares;
409     Bitboard pawns = pos.pieces(PAWN, Us);
410     Bitboard pawnsOn7 = pawns & TRank7BB;
411     Bitboard enemyPieces = (Type == MV_CAPTURE ? target : pos.pieces(Them));
412
413     // Pre-calculate pawn pushes before changing emptySquares definition
414     if (Type != MV_CAPTURE)
415     {
416         emptySquares = (Type == MV_NON_CAPTURE ? target : pos.empty_squares());
417         pawnPushes = move_pawns<UP>(pawns & ~TRank7BB) & emptySquares;
418     }
419
420     if (Type == MV_EVASION)
421     {
422         emptySquares &= target; // Only blocking squares
423         enemyPieces  &= target; // Capture only the checker piece
424     }
425
426     // Promotions and underpromotions
427     if (pawnsOn7)
428     {
429         if (Type == MV_CAPTURE)
430             emptySquares = pos.empty_squares();
431
432         pawns &= ~TRank7BB;
433         mlist = generate_promotions<Type, RIGHT_UP>(pos, mlist, pawnsOn7, enemyPieces);
434         mlist = generate_promotions<Type, LEFT_UP>(pos, mlist, pawnsOn7, enemyPieces);
435         mlist = generate_promotions<Type, UP>(pos, mlist, pawnsOn7, emptySquares);
436     }
437
438     // Standard captures
439     if (Type == MV_CAPTURE || Type == MV_EVASION)
440     {
441         mlist = generate_pawn_captures<Type, RIGHT_UP>(mlist, pawns, enemyPieces);
442         mlist = generate_pawn_captures<Type, LEFT_UP>(mlist, pawns, enemyPieces);
443     }
444
445     // Single and double pawn pushes
446     if (Type != MV_CAPTURE)
447     {
448         b1 = (Type != MV_EVASION ? pawnPushes : pawnPushes & emptySquares);
449         b2 = move_pawns<UP>(pawnPushes & TRank3BB) & emptySquares;
450
451         if (Type == MV_CHECK)
452         {
453             // Consider only pawn moves which give direct checks
454             b1 &= pos.attacks_from<PAWN>(ksq, Them);
455             b2 &= pos.attacks_from<PAWN>(ksq, Them);
456
457             // Add pawn moves which gives discovered check. This is possible only
458             // if the pawn is not on the same file as the enemy king, because we
459             // don't generate captures.
460             if (pawns & target) // For CHECK type target is dc bitboard
461             {
462                 dc1 = move_pawns<UP>(pawns & target & ~file_bb(ksq)) & emptySquares;
463                 dc2 = move_pawns<UP>(dc1 & TRank3BB) & emptySquares;
464
465                 b1 |= dc1;
466                 b2 |= dc2;
467             }
468         }
469         SERIALIZE_MOVES_D(b1, -UP);
470         SERIALIZE_MOVES_D(b2, -UP -UP);
471     }
472
473     // En passant captures
474     if ((Type == MV_CAPTURE || Type == MV_EVASION) && pos.ep_square() != SQ_NONE)
475     {
476         assert(Us != WHITE || square_rank(pos.ep_square()) == RANK_6);
477         assert(Us != BLACK || square_rank(pos.ep_square()) == RANK_3);
478
479         // An en passant capture can be an evasion only if the checking piece
480         // is the double pushed pawn and so is in the target. Otherwise this
481         // is a discovery check and we are forced to do otherwise.
482         if (Type == MV_EVASION && !bit_is_set(target, pos.ep_square() - UP))
483             return mlist;
484
485         b1 = pawns & pos.attacks_from<PAWN>(pos.ep_square(), Them);
486
487         assert(b1 != EmptyBoardBB);
488
489         while (b1)
490         {
491             to = pop_1st_bit(&b1);
492             (*mlist++).move = make_ep_move(to, pos.ep_square());
493         }
494     }
495     return mlist;
496   }
497
498   template<CastlingSide Side>
499   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist, Color us) {
500
501     CastleRight f = CastleRight((Side == KING_SIDE ? WHITE_OO : WHITE_OOO) << us);
502     Color them = opposite_color(us);
503
504     // After castling, the rook and king's final positions are exactly the same
505     // in Chess960 as they would be in standard chess.
506     Square kfrom = pos.king_square(us);
507     Square rfrom = pos.castle_rook_square(f);
508     Square kto = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
509     Square rto = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
510
511     assert(!pos.in_check());
512     assert(pos.piece_on(kfrom) == make_piece(us, KING));
513     assert(pos.piece_on(rfrom) == make_piece(us, ROOK));
514
515     // Unimpeded rule: All the squares between the king's initial and final squares
516     // (including the final square), and all the squares between the rook's initial
517     // and final squares (including the final square), must be vacant except for
518     // the king and castling rook.
519     for (Square s = Min(kfrom, kto); s <= Max(kfrom, kto); s++)
520         if (  (s != kfrom && s != rfrom && !pos.square_is_empty(s))
521             ||(pos.attackers_to(s) & pos.pieces(them)))
522             return mlist;
523
524     for (Square s = Min(rfrom, rto); s <= Max(rfrom, rto); s++)
525         if (s != kfrom && s != rfrom && !pos.square_is_empty(s))
526             return mlist;
527
528     // Because we generate only legal castling moves we need to verify that
529     // when moving the castling rook we do not discover some hidden checker.
530     // For instance an enemy queen in SQ_A1 when castling rook is in SQ_B1.
531     if (pos.is_chess960())
532     {
533         Bitboard occ = pos.occupied_squares();
534         clear_bit(&occ, rfrom);
535         if (pos.attackers_to(kto, occ) & pos.pieces(them))
536             return mlist;
537     }
538
539     (*mlist++).move = make_castle_move(kfrom, rfrom);
540
541     return mlist;
542   }
543
544 } // namespace