2 * moves.c - Move generation and checking
4 * Copyright 1991 by Digital Equipment Corporation, Maynard,
7 * Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006,
8 * 2007, 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
10 * Enhancements Copyright 2005 Alessandro Scotti
12 * The following terms apply to Digital Equipment Corporation's copyright
14 * ------------------------------------------------------------------------
17 * Permission to use, copy, modify, and distribute this software and its
18 * documentation for any purpose and without fee is hereby granted,
19 * provided that the above copyright notice appear in all copies and that
20 * both that copyright notice and this permission notice appear in
21 * supporting documentation, and that the name of Digital not be
22 * used in advertising or publicity pertaining to distribution of the
23 * software without specific, written prior permission.
25 * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
26 * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
27 * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
28 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
29 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
30 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
32 * ------------------------------------------------------------------------
34 * The following terms apply to the enhanced version of XBoard
35 * distributed by the Free Software Foundation:
36 * ------------------------------------------------------------------------
38 * GNU XBoard is free software: you can redistribute it and/or modify
39 * it under the terms of the GNU General Public License as published by
40 * the Free Software Foundation, either version 3 of the License, or (at
41 * your option) any later version.
43 * GNU XBoard is distributed in the hope that it will be useful, but
44 * WITHOUT ANY WARRANTY; without even the implied warranty of
45 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
46 * General Public License for more details.
48 * You should have received a copy of the GNU General Public License
49 * along with this program. If not, see http://www.gnu.org/licenses/. *
51 *------------------------------------------------------------------------
52 ** See the file ChangeLog for a revision history. */
59 #else /* not HAVE_STRING_H */
61 #endif /* not HAVE_STRING_H */
67 int WhitePiece P((ChessSquare));
68 int BlackPiece P((ChessSquare));
69 int SameColor P((ChessSquare, ChessSquare));
70 int PosFlags(int index);
72 extern signed char initialRights[BOARD_FILES]; /* [HGM] all rights enabled, set in InitPosition */
76 WhitePiece (ChessSquare piece)
78 return (int) piece >= (int) WhitePawn && (int) piece < (int) BlackPawn;
82 BlackPiece (ChessSquare piece)
84 return (int) piece >= (int) BlackPawn && (int) piece < (int) EmptySquare;
89 SameColor (ChessSquare piece1, ChessSquare piece2)
91 return ((int) piece1 >= (int) WhitePawn && /* [HGM] can be > King ! */
92 (int) piece1 < (int) BlackPawn &&
93 (int) piece2 >= (int) WhitePawn &&
94 (int) piece2 < (int) BlackPawn)
95 || ((int) piece1 >= (int) BlackPawn &&
96 (int) piece1 < (int) EmptySquare &&
97 (int) piece2 >= (int) BlackPawn &&
98 (int) piece2 < (int) EmptySquare);
101 #define SameColor(piece1, piece2) (piece1 < EmptySquare && piece2 < EmptySquare && (piece1 < BlackPawn) == (piece2 < BlackPawn))
104 char pieceToChar[] = {
105 'P', 'N', 'B', 'R', 'Q', 'F', 'E', 'A', 'C', 'W', 'M',
106 'O', 'H', 'I', 'J', 'G', 'D', 'V', 'L', 'S', 'U', 'K',
107 'p', 'n', 'b', 'r', 'q', 'f', 'e', 'a', 'c', 'w', 'm',
108 'o', 'h', 'i', 'j', 'g', 'd', 'v', 'l', 's', 'u', 'k',
110 char pieceNickName[EmptySquare];
113 PieceToChar (ChessSquare p)
115 if((int)p < 0 || (int)p >= (int)EmptySquare) return('x'); /* [HGM] for safety */
116 return pieceToChar[(int) p];
120 PieceToNumber (ChessSquare p) /* [HGM] holdings: count piece type, ignoring non-participating piece types */
123 ChessSquare start = (int)p >= (int)BlackPawn ? BlackPawn : WhitePawn;
125 while(start++ != p) if(pieceToChar[(int)start-1] != '.') i++;
133 if(c == '.') return EmptySquare;
134 for(i=0; i< (int) EmptySquare; i++)
135 if(pieceNickName[i] == c) return (ChessSquare) i;
136 for(i=0; i< (int) EmptySquare; i++)
137 if(pieceToChar[i] == c) return (ChessSquare) i;
142 CopyBoard (Board to, Board from)
146 for (i = 0; i < BOARD_HEIGHT; i++)
147 for (j = 0; j < BOARD_WIDTH; j++)
148 to[i][j] = from[i][j];
149 for (j = 0; j < BOARD_FILES-1; j++) // [HGM] gamestate: copy castling rights and ep status
150 to[CASTLING][j] = from[CASTLING][j];
151 to[HOLDINGS_SET] = 0; // flag used in ICS play
155 CompareBoards (Board board1, Board board2)
159 for (i = 0; i < BOARD_HEIGHT; i++)
160 for (j = 0; j < BOARD_WIDTH; j++) {
161 if (board1[i][j] != board2[i][j])
168 /* Call callback once for each pseudo-legal move in the given
169 position, except castling moves. A move is pseudo-legal if it is
170 legal, or if it would be legal except that it leaves the king in
171 check. In the arguments, epfile is EP_NONE if the previous move
172 was not a double pawn push, or the file 0..7 if it was, or
173 EP_UNKNOWN if we don't know and want to allow all e.p. captures.
174 Promotion moves generated are to Queen only.
177 GenPseudoLegal (Board board, int flags, MoveCallback callback, VOIDSTAR closure, ChessSquare filter)
178 // speed: only do moves with this piece type
181 int i, j, d, s, fs, rs, rt, ft, m;
182 int epfile = (signed char)board[EP_STATUS]; // [HGM] gamestate: extract ep status from board
183 int promoRank = gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand ? 3 : 1;
185 for (rf = 0; rf < BOARD_HEIGHT; rf++)
186 for (ff = BOARD_LEFT; ff < BOARD_RGHT; ff++) {
190 if(board[rf][ff] == EmptySquare) continue;
191 if ((flags & F_WHITE_ON_MOVE) != (board[rf][ff] < BlackPawn)) continue; // [HGM] speed: wrong color
193 m = 0; piece = board[rf][ff];
194 if(PieceToChar(piece) == '~')
195 piece = (ChessSquare) ( DEMOTED piece );
196 if(filter != EmptySquare && piece != filter) continue;
197 if(gameInfo.variant == VariantShogi)
198 piece = (ChessSquare) ( SHOGI piece );
200 switch ((int)piece) {
201 /* case EmptySquare: [HGM] this is nonsense, and conflicts with Shogi cases */
203 /* can't happen ([HGM] except for faries...) */
207 if(gameInfo.variant == VariantXiangqi) {
208 /* [HGM] capture and move straight ahead in Xiangqi */
209 if (rf < BOARD_HEIGHT-1 &&
210 !SameColor(board[rf][ff], board[rf + 1][ff]) ) {
211 callback(board, flags, NormalMove,
212 rf, ff, rf + 1, ff, closure);
214 /* and move sideways when across the river */
215 for (s = -1; s <= 1; s += 2) {
216 if (rf >= BOARD_HEIGHT>>1 &&
217 ff + s >= BOARD_LEFT && ff + s < BOARD_RGHT &&
218 !WhitePiece(board[rf][ff+s]) ) {
219 callback(board, flags, NormalMove,
220 rf, ff, rf, ff+s, closure);
225 if (rf < BOARD_HEIGHT-1 && board[rf + 1][ff] == EmptySquare) {
226 callback(board, flags,
227 rf >= BOARD_HEIGHT-1-promoRank ? WhitePromotion : NormalMove,
228 rf, ff, rf + 1, ff, closure);
230 if (rf <= (BOARD_HEIGHT>>1)-3 && board[rf+1][ff] == EmptySquare && // [HGM] grand: also on 3rd rank on 10-board
231 gameInfo.variant != VariantShatranj && /* [HGM] */
232 gameInfo.variant != VariantCourier && /* [HGM] */
233 board[rf+2][ff] == EmptySquare ) {
234 callback(board, flags, NormalMove,
235 rf, ff, rf+2, ff, closure);
237 for (s = -1; s <= 1; s += 2) {
238 if (rf < BOARD_HEIGHT-1 && ff + s >= BOARD_LEFT && ff + s < BOARD_RGHT &&
239 ((flags & F_KRIEGSPIEL_CAPTURE) ||
240 BlackPiece(board[rf + 1][ff + s]))) {
241 callback(board, flags,
242 rf >= BOARD_HEIGHT-1-promoRank ? WhitePromotion : NormalMove,
243 rf, ff, rf + 1, ff + s, closure);
245 if (rf >= BOARD_HEIGHT+1>>1) {// [HGM] grand: 4th & 5th rank on 10-board
246 if (ff + s >= BOARD_LEFT && ff + s < BOARD_RGHT &&
247 (epfile == ff + s || epfile == EP_UNKNOWN) && rf < BOARD_HEIGHT-3 &&
248 board[rf][ff + s] == BlackPawn &&
249 board[rf+1][ff + s] == EmptySquare) {
250 callback(board, flags, WhiteCapturesEnPassant,
251 rf, ff, rf+1, ff + s, closure);
258 if(gameInfo.variant == VariantXiangqi) {
259 /* [HGM] capture straight ahead in Xiangqi */
260 if (rf > 0 && !SameColor(board[rf][ff], board[rf - 1][ff]) ) {
261 callback(board, flags, NormalMove,
262 rf, ff, rf - 1, ff, closure);
264 /* and move sideways when across the river */
265 for (s = -1; s <= 1; s += 2) {
266 if (rf < BOARD_HEIGHT>>1 &&
267 ff + s >= BOARD_LEFT && ff + s < BOARD_RGHT &&
268 !BlackPiece(board[rf][ff+s]) ) {
269 callback(board, flags, NormalMove,
270 rf, ff, rf, ff+s, closure);
275 if (rf > 0 && board[rf - 1][ff] == EmptySquare) {
276 callback(board, flags,
277 rf <= promoRank ? BlackPromotion : NormalMove,
278 rf, ff, rf - 1, ff, closure);
280 if (rf >= (BOARD_HEIGHT+1>>1)+2 && board[rf-1][ff] == EmptySquare && // [HGM] grand
281 gameInfo.variant != VariantShatranj && /* [HGM] */
282 gameInfo.variant != VariantCourier && /* [HGM] */
283 board[rf-2][ff] == EmptySquare) {
284 callback(board, flags, NormalMove,
285 rf, ff, rf-2, ff, closure);
287 for (s = -1; s <= 1; s += 2) {
288 if (rf > 0 && ff + s >= BOARD_LEFT && ff + s < BOARD_RGHT &&
289 ((flags & F_KRIEGSPIEL_CAPTURE) ||
290 WhitePiece(board[rf - 1][ff + s]))) {
291 callback(board, flags,
292 rf <= promoRank ? BlackPromotion : NormalMove,
293 rf, ff, rf - 1, ff + s, closure);
295 if (rf < BOARD_HEIGHT>>1) {
296 if (ff + s >= BOARD_LEFT && ff + s < BOARD_RGHT &&
297 (epfile == ff + s || epfile == EP_UNKNOWN) && rf > 2 &&
298 board[rf][ff + s] == WhitePawn &&
299 board[rf-1][ff + s] == EmptySquare) {
300 callback(board, flags, BlackCapturesEnPassant,
301 rf, ff, rf-1, ff + s, closure);
312 for (i = -1; i <= 1; i += 2)
313 for (j = -1; j <= 1; j += 2)
314 for (s = 1; s <= 2; s++) {
317 if (!(rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT)
318 && ( gameInfo.variant != VariantXiangqi || board[rf+i*(s-1)][ff+j*(2-s)] == EmptySquare)
319 && !SameColor(board[rf][ff], board[rt][ft]))
320 callback(board, flags, NormalMove,
321 rf, ff, rt, ft, closure);
325 case SHOGI WhiteKnight:
326 for (s = -1; s <= 1; s += 2) {
327 if (rf < BOARD_HEIGHT-2 && ff + s >= BOARD_LEFT && ff + s < BOARD_RGHT &&
328 !SameColor(board[rf][ff], board[rf + 2][ff + s])) {
329 callback(board, flags, NormalMove,
330 rf, ff, rf + 2, ff + s, closure);
335 case SHOGI BlackKnight:
336 for (s = -1; s <= 1; s += 2) {
337 if (rf > 1 && ff + s >= BOARD_LEFT && ff + s < BOARD_RGHT &&
338 !SameColor(board[rf][ff], board[rf - 2][ff + s])) {
339 callback(board, flags, NormalMove,
340 rf, ff, rf - 2, ff + s, closure);
347 for (d = 0; d <= 1; d++)
348 for (s = -1; s <= 1; s += 2) {
351 rt = rf + (i * s) * d;
352 ft = ff + (i * s) * (1 - d);
353 if (rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT) break;
354 if (m == 0 && board[rt][ft] == EmptySquare)
355 callback(board, flags, NormalMove,
356 rf, ff, rt, ft, closure);
357 if (m == 1 && board[rt][ft] != EmptySquare &&
358 !SameColor(board[rf][ff], board[rt][ft]) )
359 callback(board, flags, NormalMove,
360 rf, ff, rt, ft, closure);
361 if (board[rt][ft] != EmptySquare && m++) break;
366 /* Gold General (and all its promoted versions) . First do the */
367 /* diagonal forward steps, then proceed as normal Wazir */
368 case SHOGI WhiteWazir:
369 case SHOGI (PROMOTED WhitePawn):
370 case SHOGI (PROMOTED WhiteKnight):
371 case SHOGI (PROMOTED WhiteQueen):
372 case SHOGI (PROMOTED WhiteFerz):
373 for (s = -1; s <= 1; s += 2) {
374 if (rf < BOARD_HEIGHT-1 && ff + s >= BOARD_LEFT && ff + s < BOARD_RGHT &&
375 !SameColor(board[rf][ff], board[rf + 1][ff + s])) {
376 callback(board, flags, NormalMove,
377 rf, ff, rf + 1, ff + s, closure);
382 case SHOGI BlackWazir:
383 case SHOGI (PROMOTED BlackPawn):
384 case SHOGI (PROMOTED BlackKnight):
385 case SHOGI (PROMOTED BlackQueen):
386 case SHOGI (PROMOTED BlackFerz):
387 for (s = -1; s <= 1; s += 2) {
388 if (rf > 0 && ff + s >= BOARD_LEFT && ff + s < BOARD_RGHT &&
389 !SameColor(board[rf][ff], board[rf - 1][ff + s])) {
390 callback(board, flags, NormalMove,
391 rf, ff, rf - 1, ff + s, closure);
398 for (d = 0; d <= 1; d++)
399 for (s = -1; s <= 1; s += 2) {
401 ft = ff + s * (1 - d);
402 if (!(rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT)
403 && !SameColor(board[rf][ff], board[rt][ft]) &&
404 (gameInfo.variant != VariantXiangqi || InPalace(rt, ft) ) )
405 callback(board, flags, NormalMove,
406 rf, ff, rt, ft, closure);
412 /* [HGM] support Shatranj pieces */
413 for (rs = -1; rs <= 1; rs += 2)
414 for (fs = -1; fs <= 1; fs += 2) {
417 if (!(rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT)
418 && ( gameInfo.variant != VariantXiangqi ||
419 board[rf+rs][ff+fs] == EmptySquare && (2*rf < BOARD_HEIGHT) == (2*rt < BOARD_HEIGHT) )
421 && !SameColor(board[rf][ff], board[rt][ft]))
422 callback(board, flags, NormalMove,
423 rf, ff, rt, ft, closure);
424 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier
425 || gameInfo.variant == VariantXiangqi) continue; // classical Alfil
426 rt = rf + rs; // in unknown variant we assume Modern Elephant, which can also do one step
428 if (!(rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT)
429 && !SameColor(board[rf][ff], board[rt][ft]))
430 callback(board, flags, NormalMove,
431 rf, ff, rt, ft, closure);
433 if(gameInfo.variant == VariantSpartan)
434 for(fs = -1; fs <= 1; fs += 2) {
436 if (!(ft < BOARD_LEFT || ft >= BOARD_RGHT) && board[rf][ft] == EmptySquare)
437 callback(board, flags, NormalMove, rf, ff, rf, ft, closure);
441 /* Make Dragon-Horse also do Dababba moves outside Shogi, for better disambiguation in variant Fairy */
444 for (d = 0; d <= 1; d++) // Dababba moves that Rook cannot do
445 for (s = -2; s <= 2; s += 4) {
447 ft = ff + s * (1 - d);
448 if (rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT) continue;
449 if (SameColor(board[rf][ff], board[rt][ft])) continue;
450 callback(board, flags, NormalMove, rf, ff, rt, ft, closure);
453 /* Shogi Dragon Horse has to continue with Wazir after Bishop */
454 case SHOGI WhiteCardinal:
455 case SHOGI BlackCardinal:
458 /* Capablanca Archbishop continues as Knight */
463 /* Shogi Bishops are ordinary Bishops */
464 case SHOGI WhiteBishop:
465 case SHOGI BlackBishop:
468 for (rs = -1; rs <= 1; rs += 2)
469 for (fs = -1; fs <= 1; fs += 2)
473 if (rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT) break;
474 if (SameColor(board[rf][ff], board[rt][ft])) break;
475 callback(board, flags, NormalMove,
476 rf, ff, rt, ft, closure);
477 if (board[rt][ft] != EmptySquare) break;
479 if(m==1) goto mounted;
480 if(m==2) goto finishGold;
481 /* Bishop falls through */
484 /* Shogi Lance is unlike anything, and asymmetric at that */
485 case SHOGI WhiteQueen:
489 if (rt >= BOARD_HEIGHT) break;
490 if (SameColor(board[rf][ff], board[rt][ft])) break;
491 callback(board, flags, NormalMove,
492 rf, ff, rt, ft, closure);
493 if (board[rt][ft] != EmptySquare) break;
497 case SHOGI BlackQueen:
502 if (SameColor(board[rf][ff], board[rt][ft])) break;
503 callback(board, flags, NormalMove,
504 rf, ff, rt, ft, closure);
505 if (board[rt][ft] != EmptySquare) break;
509 /* Make Dragon-King Dababba & Rook-like outside Shogi, for better disambiguation in variant Fairy */
512 for (d = 0; d <= 1; d++) // Dababba moves that Rook cannot do
513 for (s = -2; s <= 2; s += 4) {
515 ft = ff + s * (1 - d);
516 if (rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT || board[rf+rt>>1][ff+ft>>1] == EmptySquare) continue;
517 if (SameColor(board[rf][ff], board[rt][ft])) continue;
518 callback(board, flags, NormalMove, rf, ff, rt, ft, closure);
520 if(gameInfo.variant == VariantSpartan) rookRange = 2; // in Spartan Chess restrict range to modern Dababba
523 /* Shogi Dragon King has to continue as Ferz after Rook moves */
524 case SHOGI WhiteDragon:
525 case SHOGI BlackDragon:
528 /* Capablanca Chancellor sets flag to continue as Knight */
532 m += (gameInfo.variant == VariantSpartan); // in Spartan Chess Chancellor is used for Dragon King.
534 /* Shogi Rooks are ordinary Rooks */
535 case SHOGI WhiteRook:
536 case SHOGI BlackRook:
540 for (d = 0; d <= 1; d++)
541 for (s = -1; s <= 1; s += 2)
543 rt = rf + (i * s) * d;
544 ft = ff + (i * s) * (1 - d);
545 if (rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT) break;
546 if (SameColor(board[rf][ff], board[rt][ft])) break;
547 callback(board, flags, NormalMove,
548 rf, ff, rt, ft, closure);
549 if (board[rt][ft] != EmptySquare || i == rookRange) break;
551 if(m==1) goto mounted;
552 if(m==2) goto finishSilver;
557 for (rs = -1; rs <= 1; rs++)
558 for (fs = -1; fs <= 1; fs++) {
559 if (rs == 0 && fs == 0) continue;
563 if (rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT) break;
564 if (SameColor(board[rf][ff], board[rt][ft])) break;
565 callback(board, flags, NormalMove,
566 rf, ff, rt, ft, closure);
567 if (board[rt][ft] != EmptySquare) break;
572 /* Shogi Pawn and Silver General: first the Pawn move, */
573 /* then the General continues like a Ferz */
575 if(gameInfo.variant != VariantMakruk) goto commoner;
576 case SHOGI WhitePawn:
577 case SHOGI WhiteFerz:
578 if (rf < BOARD_HEIGHT-1 &&
579 !SameColor(board[rf][ff], board[rf + 1][ff]) )
580 callback(board, flags, NormalMove,
581 rf, ff, rf + 1, ff, closure);
582 if(piece != SHOGI WhitePawn) goto finishSilver;
586 if(gameInfo.variant != VariantMakruk) goto commoner;
587 case SHOGI BlackPawn:
588 case SHOGI BlackFerz:
590 !SameColor(board[rf][ff], board[rf - 1][ff]) )
591 callback(board, flags, NormalMove,
592 rf, ff, rf - 1, ff, closure);
593 if(piece == SHOGI BlackPawn) break;
598 /* [HGM] support Shatranj pieces */
599 for (rs = -1; rs <= 1; rs += 2)
600 for (fs = -1; fs <= 1; fs += 2) {
603 if (rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT) continue;
604 if (!SameColor(board[rf][ff], board[rt][ft]) &&
605 (gameInfo.variant != VariantXiangqi || InPalace(rt, ft) ) )
606 callback(board, flags, NormalMove,
607 rf, ff, rt, ft, closure);
613 m++; // [HGM] superchess: use for Centaur
615 case SHOGI WhiteKing:
616 case SHOGI BlackKing:
620 for (i = -1; i <= 1; i++)
621 for (j = -1; j <= 1; j++) {
622 if (i == 0 && j == 0) continue;
625 if (rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT) continue;
626 if (SameColor(board[rf][ff], board[rt][ft])) continue;
627 callback(board, flags, NormalMove,
628 rf, ff, rt, ft, closure);
630 if(m==1) goto mounted;
633 case WhiteNightrider:
634 case BlackNightrider:
635 for (i = -1; i <= 1; i += 2)
636 for (j = -1; j <= 1; j += 2)
637 for (s = 1; s <= 2; s++) { int k;
641 if (rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT) break;
642 if (SameColor(board[rf][ff], board[rt][ft])) break;
643 callback(board, flags, NormalMove,
644 rf, ff, rt, ft, closure);
645 if (board[rt][ft] != EmptySquare) break;
651 /* First do Bishop,then continue like Chancellor */
652 for (rs = -1; rs <= 1; rs += 2)
653 for (fs = -1; fs <= 1; fs += 2)
657 if (rt < 0 || rt >= BOARD_HEIGHT || ft < BOARD_LEFT || ft >= BOARD_RGHT) break;
658 if (SameColor(board[rf][ff], board[rt][ft])) break;
659 callback(board, flags, NormalMove,
660 rf, ff, rt, ft, closure);
661 if (board[rt][ft] != EmptySquare) break;
666 // Use Lance as Berolina / Spartan Pawn.
668 if(gameInfo.variant == VariantSuper) goto Amazon;
669 if (rf < BOARD_HEIGHT-1 && BlackPiece(board[rf + 1][ff]))
670 callback(board, flags,
671 rf >= BOARD_HEIGHT-1-promoRank ? WhitePromotion : NormalMove,
672 rf, ff, rf + 1, ff, closure);
673 for (s = -1; s <= 1; s += 2) {
674 if (rf < BOARD_HEIGHT-1 && ff + s >= BOARD_LEFT && ff + s < BOARD_RGHT && board[rf + 1][ff + s] == EmptySquare)
675 callback(board, flags,
676 rf >= BOARD_HEIGHT-1-promoRank ? WhitePromotion : NormalMove,
677 rf, ff, rf + 1, ff + s, closure);
678 if (rf == 1 && ff + 2*s >= BOARD_LEFT && ff + 2*s < BOARD_RGHT && board[3][ff + 2*s] == EmptySquare )
679 callback(board, flags, NormalMove, rf, ff, 3, ff + 2*s, closure);
684 if(gameInfo.variant == VariantSuper) goto Amazon;
685 if (rf > 0 && WhitePiece(board[rf - 1][ff]))
686 callback(board, flags,
687 rf <= promoRank ? BlackPromotion : NormalMove,
688 rf, ff, rf - 1, ff, closure);
689 for (s = -1; s <= 1; s += 2) {
690 if (rf > 0 && ff + s >= BOARD_LEFT && ff + s < BOARD_RGHT && board[rf - 1][ff + s] == EmptySquare)
691 callback(board, flags,
692 rf <= promoRank ? BlackPromotion : NormalMove,
693 rf, ff, rf - 1, ff + s, closure);
694 if (rf == BOARD_HEIGHT-2 && ff + 2*s >= BOARD_LEFT && ff + 2*s < BOARD_RGHT && board[rf-2][ff + 2*s] == EmptySquare )
695 callback(board, flags, NormalMove, rf, ff, rf-2, ff + 2*s, closure);
699 case WhiteFalcon: // [HGM] wild: for wildcards, self-capture symbolizes move to anywhere
703 callback(board, flags, NormalMove, rf, ff, rf, ff, closure);
716 int rFilter, fFilter; // [HGM] speed: sorry, but I get a bit tired of this closure madness
717 Board xqCheckers, nullBoard;
719 extern void GenLegalCallback P((Board board, int flags, ChessMove kind,
720 int rf, int ff, int rt, int ft,
724 GenLegalCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
726 register GenLegalClosure *cl = (GenLegalClosure *) closure;
728 if(rFilter >= 0 && rFilter != rt || fFilter >= 0 && fFilter != ft) return; // [HGM] speed: ignore moves with wrong to-square
730 if (!(flags & F_IGNORE_CHECK) ) {
731 int check, promo = (gameInfo.variant == VariantSpartan && kind == BlackPromotion);
734 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
735 kings += (board[r][f] == BlackKing);
739 board[rf][ff] = BlackKing; // [HGM] spartan: promote to King before check-test
741 check = CheckTest(board, flags, rf, ff, rt, ft,
742 kind == WhiteCapturesEnPassant ||
743 kind == BlackCapturesEnPassant);
744 if(promo) board[rf][ff] = BlackLance;
747 if (flags & F_ATOMIC_CAPTURE) {
748 if (board[rt][ft] != EmptySquare ||
749 kind == WhiteCapturesEnPassant || kind == BlackCapturesEnPassant) {
751 ChessSquare king = (flags & F_WHITE_ON_MOVE) ? WhiteKing : BlackKing;
752 if (board[rf][ff] == king) return;
753 for (r = rt-1; r <= rt+1; r++) {
754 for (f = ft-1; f <= ft+1; f++) {
755 if (r >= 0 && r < BOARD_HEIGHT && f >= BOARD_LEFT && f < BOARD_RGHT &&
756 board[r][f] == king) return;
761 cl->cb(board, flags, kind, rf, ff, rt, ft, cl->cl);
768 int captures; // [HGM] losers
769 } LegalityTestClosure;
772 /* Like GenPseudoLegal, but (1) include castling moves, (2) unless
773 F_IGNORE_CHECK is set in the flags, omit moves that would leave the
774 king in check, and (3) if F_ATOMIC_CAPTURE is set in the flags, omit
775 moves that would destroy your own king. The CASTLE_OK flags are
776 true if castling is not yet ruled out by a move of the king or
777 rook. Return TRUE if the player on move is currently in check and
778 F_IGNORE_CHECK is not set. [HGM] add castlingRights parameter */
780 GenLegal (Board board, int flags, MoveCallback callback, VOIDSTAR closure, ChessSquare filter)
783 int ff, ft, k, left, right, swap;
784 int ignoreCheck = (flags & F_IGNORE_CHECK) != 0;
785 ChessSquare wKing = WhiteKing, bKing = BlackKing, *castlingRights = board[CASTLING];
786 int inCheck = !ignoreCheck && CheckTest(board, flags, -1, -1, -1, -1, FALSE); // kludge alert: this would mark pre-existing checkers if status==1
790 xqCheckers[EP_STATUS] *= 2; // quasi: if previous CheckTest has been marking, we now set flag for suspending same checkers
791 if(filter == EmptySquare) rFilter = fFilter = -1; // [HGM] speed: do not filter on square if we do not filter on piece
792 GenPseudoLegal(board, flags, GenLegalCallback, (VOIDSTAR) &cl, filter);
794 if (inCheck) return TRUE;
796 /* Generate castling moves */
797 if(gameInfo.variant == VariantKnightmate) { /* [HGM] Knightmate */
798 wKing = WhiteUnicorn; bKing = BlackUnicorn;
801 for (ff = BOARD_WIDTH>>1; ff >= (BOARD_WIDTH-1)>>1; ff-- /*ics wild 1*/) {
802 if ((flags & F_WHITE_ON_MOVE) &&
803 (flags & F_WHITE_KCASTLE_OK) &&
804 board[0][ff] == wKing &&
805 board[0][ff + 1] == EmptySquare &&
806 board[0][ff + 2] == EmptySquare &&
807 board[0][BOARD_RGHT-3] == EmptySquare &&
808 board[0][BOARD_RGHT-2] == EmptySquare &&
809 board[0][BOARD_RGHT-1] == WhiteRook &&
810 castlingRights[0] != NoRights && /* [HGM] check rights */
811 ( castlingRights[2] == ff || castlingRights[6] == ff ) &&
813 (!CheckTest(board, flags, 0, ff, 0, ff + 1, FALSE) &&
814 !CheckTest(board, flags, 0, ff, 0, BOARD_RGHT-3, FALSE) &&
815 (gameInfo.variant != VariantJanus || !CheckTest(board, flags, 0, ff, 0, BOARD_RGHT-2, FALSE)) &&
816 !CheckTest(board, flags, 0, ff, 0, ff + 2, FALSE)))) {
818 callback(board, flags,
819 ff==BOARD_WIDTH>>1 ? WhiteKingSideCastle : WhiteKingSideCastleWild,
820 0, ff, 0, ff + ((gameInfo.boardWidth+2)>>2) + (gameInfo.variant == VariantJanus), closure);
822 if ((flags & F_WHITE_ON_MOVE) &&
823 (flags & F_WHITE_QCASTLE_OK) &&
824 board[0][ff] == wKing &&
825 board[0][ff - 1] == EmptySquare &&
826 board[0][ff - 2] == EmptySquare &&
827 board[0][BOARD_LEFT+2] == EmptySquare &&
828 board[0][BOARD_LEFT+1] == EmptySquare &&
829 board[0][BOARD_LEFT+0] == WhiteRook &&
830 castlingRights[1] != NoRights && /* [HGM] check rights */
831 ( castlingRights[2] == ff || castlingRights[6] == ff ) &&
833 (!CheckTest(board, flags, 0, ff, 0, ff - 1, FALSE) &&
834 !CheckTest(board, flags, 0, ff, 0, BOARD_LEFT+3, FALSE) &&
835 !CheckTest(board, flags, 0, ff, 0, ff - 2, FALSE)))) {
837 callback(board, flags,
838 ff==BOARD_WIDTH>>1 ? WhiteQueenSideCastle : WhiteQueenSideCastleWild,
839 0, ff, 0, ff - ((gameInfo.boardWidth+2)>>2), closure);
841 if (!(flags & F_WHITE_ON_MOVE) &&
842 (flags & F_BLACK_KCASTLE_OK) &&
843 board[BOARD_HEIGHT-1][ff] == bKing &&
844 board[BOARD_HEIGHT-1][ff + 1] == EmptySquare &&
845 board[BOARD_HEIGHT-1][ff + 2] == EmptySquare &&
846 board[BOARD_HEIGHT-1][BOARD_RGHT-3] == EmptySquare &&
847 board[BOARD_HEIGHT-1][BOARD_RGHT-2] == EmptySquare &&
848 board[BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook &&
849 castlingRights[3] != NoRights && /* [HGM] check rights */
850 ( castlingRights[5] == ff || castlingRights[7] == ff ) &&
852 (!CheckTest(board, flags, BOARD_HEIGHT-1, ff, BOARD_HEIGHT-1, ff + 1, FALSE) &&
853 !CheckTest(board, flags, BOARD_HEIGHT-1, ff, BOARD_HEIGHT-1, BOARD_RGHT-3, FALSE) &&
854 (gameInfo.variant != VariantJanus || !CheckTest(board, flags, BOARD_HEIGHT-1, ff, BOARD_HEIGHT-1, BOARD_RGHT-2, FALSE)) &&
855 !CheckTest(board, flags, BOARD_HEIGHT-1, ff, BOARD_HEIGHT-1, ff + 2, FALSE)))) {
857 callback(board, flags,
858 ff==BOARD_WIDTH>>1 ? BlackKingSideCastle : BlackKingSideCastleWild,
859 BOARD_HEIGHT-1, ff, BOARD_HEIGHT-1, ff + ((gameInfo.boardWidth+2)>>2) + (gameInfo.variant == VariantJanus), closure);
861 if (!(flags & F_WHITE_ON_MOVE) &&
862 (flags & F_BLACK_QCASTLE_OK) &&
863 board[BOARD_HEIGHT-1][ff] == bKing &&
864 board[BOARD_HEIGHT-1][ff - 1] == EmptySquare &&
865 board[BOARD_HEIGHT-1][ff - 2] == EmptySquare &&
866 board[BOARD_HEIGHT-1][BOARD_LEFT+2] == EmptySquare &&
867 board[BOARD_HEIGHT-1][BOARD_LEFT+1] == EmptySquare &&
868 board[BOARD_HEIGHT-1][BOARD_LEFT+0] == BlackRook &&
869 castlingRights[4] != NoRights && /* [HGM] check rights */
870 ( castlingRights[5] == ff || castlingRights[7] == ff ) &&
872 (!CheckTest(board, flags, BOARD_HEIGHT-1, ff, BOARD_HEIGHT-1, ff - 1, FALSE) &&
873 !CheckTest(board, flags, BOARD_HEIGHT-1, ff, BOARD_HEIGHT-1, BOARD_LEFT+3, FALSE) &&
874 !CheckTest(board, flags, BOARD_HEIGHT-1, ff, BOARD_HEIGHT-1, ff - 2, FALSE)))) {
876 callback(board, flags,
877 ff==BOARD_WIDTH>>1 ? BlackQueenSideCastle : BlackQueenSideCastleWild,
878 BOARD_HEIGHT-1, ff, BOARD_HEIGHT-1, ff - ((gameInfo.boardWidth+2)>>2), closure);
882 if((swap = gameInfo.variant == VariantSChess) || flags & F_FRC_TYPE_CASTLING) {
884 /* generate all potential FRC castling moves (KxR), ignoring flags */
885 /* [HGM] test if the Rooks we find have castling rights */
886 /* In S-Chess we generate RxK for allowed castlings, for gating at Rook square */
889 if ((flags & F_WHITE_ON_MOVE) != 0) {
890 ff = castlingRights[2]; /* King file if we have any rights */
891 if(ff != NoRights && board[0][ff] == WhiteKing) {
892 if (appData.debugMode) {
893 fprintf(debugFP, "FRC castling, %d %d %d %d %d %d\n",
894 castlingRights[0],castlingRights[1],ff,castlingRights[3],castlingRights[4],castlingRights[5]);
896 ft = castlingRights[0]; /* Rook file if we have H-side rights */
898 right = BOARD_RGHT-2;
899 if(ff == BOARD_RGHT-2) left = right = ff-1; /* special case */
900 for(k=left; k<=right && ft != NoRights; k++) /* first test if blocked */
901 if(k != ft && board[0][k] != EmptySquare) ft = NoRights;
902 for(k=left; k<right && ft != NoRights; k++) /* then if not checked */
903 if(!ignoreCheck && CheckTest(board, flags, 0, ff, 0, k, FALSE)) ft = NoRights;
904 if(ft != NoRights && board[0][ft] == WhiteRook)
905 callback(board, flags, WhiteHSideCastleFR, 0, swap ? ft : ff, 0, swap ? ff : ft, closure);
907 ft = castlingRights[1]; /* Rook file if we have A-side rights */
910 if(ff <= BOARD_LEFT+2) { left = ff+1; right = BOARD_LEFT+3; }
911 for(k=left; k<=right && ft != NoRights; k++) /* first test if blocked */
912 if(k != ft && board[0][k] != EmptySquare) ft = NoRights;
913 if(ff > BOARD_LEFT+2)
914 for(k=left+1; k<=right && ft != NoRights; k++) /* then if not checked */
915 if(!ignoreCheck && CheckTest(board, flags, 0, ff, 0, k, FALSE)) ft = NoRights;
916 if(ft != NoRights && board[0][ft] == WhiteRook)
917 callback(board, flags, WhiteASideCastleFR, 0, swap ? ft : ff, 0, swap ? ff : ft, closure);
920 ff = castlingRights[5]; /* King file if we have any rights */
921 if(ff != NoRights && board[BOARD_HEIGHT-1][ff] == BlackKing) {
922 ft = castlingRights[3]; /* Rook file if we have H-side rights */
924 right = BOARD_RGHT-2;
925 if(ff == BOARD_RGHT-2) left = right = ff-1; /* special case */
926 for(k=left; k<=right && ft != NoRights; k++) /* first test if blocked */
927 if(k != ft && board[BOARD_HEIGHT-1][k] != EmptySquare) ft = NoRights;
928 for(k=left; k<right && ft != NoRights; k++) /* then if not checked */
929 if(!ignoreCheck && CheckTest(board, flags, BOARD_HEIGHT-1, ff, BOARD_HEIGHT-1, k, FALSE)) ft = NoRights;
930 if(ft != NoRights && board[BOARD_HEIGHT-1][ft] == BlackRook)
931 callback(board, flags, BlackHSideCastleFR, BOARD_HEIGHT-1, swap ? ft : ff, BOARD_HEIGHT-1, swap ? ff : ft, closure);
933 ft = castlingRights[4]; /* Rook file if we have A-side rights */
936 if(ff <= BOARD_LEFT+2) { left = ff+1; right = BOARD_LEFT+3; }
937 for(k=left; k<=right && ft != NoRights; k++) /* first test if blocked */
938 if(k != ft && board[BOARD_HEIGHT-1][k] != EmptySquare) ft = NoRights;
939 if(ff > BOARD_LEFT+2)
940 for(k=left+1; k<=right && ft != NoRights; k++) /* then if not checked */
941 if(!ignoreCheck && CheckTest(board, flags, BOARD_HEIGHT-1, ff, BOARD_HEIGHT-1, k, FALSE)) ft = NoRights;
942 if(ft != NoRights && board[BOARD_HEIGHT-1][ft] == BlackRook)
943 callback(board, flags, BlackASideCastleFR, BOARD_HEIGHT-1, swap ? ft : ff, BOARD_HEIGHT-1, swap ? ff : ft, closure);
959 extern void CheckTestCallback P((Board board, int flags, ChessMove kind,
960 int rf, int ff, int rt, int ft,
965 CheckTestCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
967 register CheckTestClosure *cl = (CheckTestClosure *) closure;
969 if (rt == cl->rking && ft == cl->fking) {
970 if(xqCheckers[EP_STATUS] >= 2 && xqCheckers[rf][ff]) return; // checker is piece with suspended checking power
972 xqCheckers[rf][ff] = xqCheckers[EP_STATUS] & 1; // remember who is checking (if status == 1)
977 /* If the player on move were to move from (rf, ff) to (rt, ft), would
978 he leave himself in check? Or if rf == -1, is the player on move
979 in check now? enPassant must be TRUE if the indicated move is an
980 e.p. capture. The possibility of castling out of a check along the
981 back rank is not accounted for (i.e., we still return nonzero), as
982 this is illegal anyway. Return value is the number of times the
985 CheckTest (Board board, int flags, int rf, int ff, int rt, int ft, int enPassant)
988 ChessSquare king = flags & F_WHITE_ON_MOVE ? WhiteKing : BlackKing;
989 ChessSquare captured = EmptySquare;
990 /* Suppress warnings on uninitialized variables */
992 if(gameInfo.variant == VariantXiangqi)
993 king = flags & F_WHITE_ON_MOVE ? WhiteWazir : BlackWazir;
994 if(gameInfo.variant == VariantKnightmate)
995 king = flags & F_WHITE_ON_MOVE ? WhiteUnicorn : BlackUnicorn;
999 captured = board[rf][ft];
1000 board[rf][ft] = EmptySquare;
1002 captured = board[rt][ft];
1004 if(rf == DROP_RANK) board[rt][ft] = ff; else { // [HGM] drop
1005 board[rt][ft] = board[rf][ff];
1006 board[rf][ff] = EmptySquare;
1010 /* For compatibility with ICS wild 9, we scan the board in the
1011 order a1, a2, a3, ... b1, b2, ..., h8 to find the first king,
1012 and we test only whether that one is in check. */
1013 for (cl.fking = BOARD_LEFT+0; cl.fking < BOARD_RGHT; cl.fking++)
1014 for (cl.rking = 0; cl.rking < BOARD_HEIGHT; cl.rking++) {
1015 if (board[cl.rking][cl.fking] == king) {
1017 if(gameInfo.variant == VariantXiangqi) {
1018 /* [HGM] In Xiangqi opposing Kings means check as well */
1020 dir = (king >= BlackPawn) ? -1 : 1;
1021 for( i=cl.rking+dir; i>=0 && i<BOARD_HEIGHT &&
1022 board[i][cl.fking] == EmptySquare; i+=dir );
1023 if(i>=0 && i<BOARD_HEIGHT &&
1024 board[i][cl.fking] == (dir>0 ? BlackWazir : WhiteWazir) )
1027 GenPseudoLegal(board, flags ^ F_WHITE_ON_MOVE, CheckTestCallback, (VOIDSTAR) &cl, EmptySquare);
1028 if(gameInfo.variant != VariantSpartan || cl.check == 0) // in Spartan Chess go on to test if other King is checked too
1029 goto undo_move; /* 2-level break */
1036 if(rf != DROP_RANK) // [HGM] drop
1037 board[rf][ff] = board[rt][ft];
1039 board[rf][ft] = captured;
1040 board[rt][ft] = EmptySquare;
1042 board[rt][ft] = captured;
1046 return cl.fking < BOARD_RGHT ? cl.check : 1000; // [HGM] atomic: return 1000 if we have no king
1050 LegalDrop (Board board, int flags, ChessSquare piece, int rt, int ft)
1051 { // [HGM] put drop legality testing in separate routine for clarity
1053 if(appData.debugMode) fprintf(debugFP, "LegalDrop: %d @ %d,%d)\n", piece, ft, rt);
1054 if(board[rt][ft] != EmptySquare) return ImpossibleMove; // must drop to empty square
1055 n = PieceToNumber(piece);
1056 if(gameInfo.holdingsWidth == 0 || (flags & F_WHITE_ON_MOVE ? board[n][BOARD_WIDTH-1] : board[BOARD_HEIGHT-1-n][0]) != piece)
1057 return ImpossibleMove; // piece not available
1058 if(gameInfo.variant == VariantShogi) { // in Shogi lots of drops are forbidden!
1059 if((piece == WhitePawn || piece == WhiteQueen) && rt == BOARD_HEIGHT-1 ||
1060 (piece == BlackPawn || piece == BlackQueen) && rt == 0 ||
1061 piece == WhiteKnight && rt > BOARD_HEIGHT-3 ||
1062 piece == BlackKnight && rt < 2 ) return IllegalMove; // e.g. where dropped piece has no moves
1063 if(piece == WhitePawn || piece == BlackPawn) {
1065 for(r=1; r<BOARD_HEIGHT-1; r++)
1066 if(board[r][ft] == piece) return IllegalMove; // or there already is a Pawn in file
1067 // should still test if we mate with this Pawn
1069 } else if(gameInfo.variant == VariantSChess) { // only back-rank drops
1070 if (rt != (piece < BlackPawn ? 0 : BOARD_HEIGHT-1)) return IllegalMove;
1072 if( (piece == WhitePawn || piece == BlackPawn) &&
1073 (rt == 0 || rt == BOARD_HEIGHT -1 ) )
1074 return IllegalMove; /* no pawn drops on 1st/8th */
1076 if(appData.debugMode) fprintf(debugFP, "LegalDrop: %d @ %d,%d)\n", piece, ft, rt);
1077 if (!(flags & F_IGNORE_CHECK) &&
1078 CheckTest(board, flags, DROP_RANK, piece, rt, ft, FALSE) ) return IllegalMove;
1079 return flags & F_WHITE_ON_MOVE ? WhiteDrop : BlackDrop;
1082 extern void LegalityTestCallback P((Board board, int flags, ChessMove kind,
1083 int rf, int ff, int rt, int ft,
1087 LegalityTestCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1089 register LegalityTestClosure *cl = (LegalityTestClosure *) closure;
1091 if(board[rt][ft] != EmptySquare || kind==WhiteCapturesEnPassant || kind==BlackCapturesEnPassant)
1092 cl->captures++; // [HGM] losers: count legal captures
1093 if (rf == cl->rf && ff == cl->ff && rt == cl->rt && ft == cl->ft)
1098 LegalityTest (Board board, int flags, int rf, int ff, int rt, int ft, int promoChar)
1100 LegalityTestClosure cl; ChessSquare piece, filterPiece;
1102 if(quickFlag) flags = flags & ~1 | quickFlag & 1; // [HGM] speed: in quick mode quickFlag specifies side-to-move.
1103 if(rf == DROP_RANK) return LegalDrop(board, flags, ff, rt, ft);
1104 piece = filterPiece = board[rf][ff];
1105 if(PieceToChar(piece) == '~') filterPiece = DEMOTED piece;
1107 /* [HGM] Cobra and Falcon are wildcard pieces; consider all their moves legal */
1108 /* (perhaps we should disallow moves that obviously leave us in check?) */
1109 if(piece == WhiteFalcon || piece == BlackFalcon ||
1110 piece == WhiteCobra || piece == BlackCobra)
1111 return CheckTest(board, flags, rf, ff, rt, ft, FALSE) ? IllegalMove : NormalMove;
1115 cl.rt = rFilter = rt; // [HGM] speed: filter on to-square
1116 cl.ft = fFilter = ft;
1117 cl.kind = IllegalMove;
1118 cl.captures = 0; // [HGM] losers: prepare to count legal captures.
1119 if(flags & F_MANDATORY_CAPTURE) filterPiece = EmptySquare; // [HGM] speed: do not filter in suicide, to find all captures
1120 GenLegal(board, flags, LegalityTestCallback, (VOIDSTAR) &cl, filterPiece);
1121 if((flags & F_MANDATORY_CAPTURE) && cl.captures && board[rt][ft] == EmptySquare
1122 && cl.kind != WhiteCapturesEnPassant && cl.kind != BlackCapturesEnPassant)
1123 return(IllegalMove); // [HGM] losers: if there are legal captures, non-capts are illegal
1125 if(promoChar == 'x') promoChar = NULLCHAR; // [HGM] is this ever the case?
1126 if(gameInfo.variant == VariantSChess && promoChar && promoChar != '=' && board[rf][ff] != WhitePawn && board[rf][ff] != BlackPawn) {
1127 if(board[rf][ff] < BlackPawn) { // white
1128 if(rf != 0) return IllegalMove; // must be on back rank
1129 if(board[PieceToNumber(CharToPiece(ToUpper(promoChar)))][BOARD_WIDTH-2] == 0) return ImpossibleMove;// must be in stock
1131 if(rf != BOARD_HEIGHT-1) return IllegalMove;
1132 if(board[BOARD_HEIGHT-1-PieceToNumber(CharToPiece(ToLower(promoChar)))][1] == 0) return ImpossibleMove;
1135 if(gameInfo.variant == VariantShogi) {
1136 /* [HGM] Shogi promotions. '=' means defer */
1137 if(rf != DROP_RANK && cl.kind == NormalMove) {
1138 ChessSquare piece = board[rf][ff];
1140 if(promoChar == PieceToChar(BlackQueen)) promoChar = NULLCHAR; /* [HGM] Kludge */
1141 if(promoChar == 'd' && (piece == WhiteRook || piece == BlackRook) ||
1142 promoChar == 'h' && (piece == WhiteBishop || piece == BlackBishop) ||
1143 promoChar == 'g' && (piece <= WhiteFerz || piece <= BlackFerz && piece >= BlackPawn) )
1144 promoChar = '+'; // allowed ICS notations
1145 if(appData.debugMode)fprintf(debugFP,"SHOGI promoChar = %c\n", promoChar ? promoChar : '-');
1146 if(promoChar != NULLCHAR && promoChar != '+' && promoChar != '=')
1147 return CharToPiece(promoChar) == EmptySquare ? ImpossibleMove : IllegalMove;
1148 else if(flags & F_WHITE_ON_MOVE) {
1149 if( (int) piece < (int) WhiteWazir &&
1150 (rf >= BOARD_HEIGHT*2/3 || rt >= BOARD_HEIGHT*2/3) ) {
1151 if( (piece == WhitePawn || piece == WhiteQueen) && rt > BOARD_HEIGHT-2 ||
1152 piece == WhiteKnight && rt > BOARD_HEIGHT-3) /* promotion mandatory */
1153 cl.kind = promoChar == '=' ? IllegalMove : WhitePromotion;
1154 else /* promotion optional, default is defer */
1155 cl.kind = promoChar == '+' ? WhitePromotion : WhiteNonPromotion;
1156 } else cl.kind = promoChar == '+' ? IllegalMove : NormalMove;
1158 if( (int) piece < (int) BlackWazir && (rf < BOARD_HEIGHT/3 || rt < BOARD_HEIGHT/3) ) {
1159 if( (piece == BlackPawn || piece == BlackQueen) && rt < 1 ||
1160 piece == BlackKnight && rt < 2 ) /* promotion obligatory */
1161 cl.kind = promoChar == '=' ? IllegalMove : BlackPromotion;
1162 else /* promotion optional, default is defer */
1163 cl.kind = promoChar == '+' ? BlackPromotion : BlackNonPromotion;
1164 } else cl.kind = promoChar == '+' ? IllegalMove : NormalMove;
1168 if (promoChar != NULLCHAR) {
1169 if(promoChar == '=') cl.kind = IllegalMove; else // [HGM] shogi: no deferred promotion outside Shogi
1170 if (cl.kind == WhitePromotion || cl.kind == BlackPromotion) {
1171 ChessSquare piece = CharToPiece(flags & F_WHITE_ON_MOVE ? ToUpper(promoChar) : ToLower(promoChar));
1172 if(piece == EmptySquare)
1173 cl.kind = ImpossibleMove; // non-existing piece
1174 if(gameInfo.variant == VariantSpartan && cl.kind == BlackPromotion ) {
1175 if(promoChar != PieceToChar(BlackKing)) {
1176 if(CheckTest(board, flags, rf, ff, rt, ft, FALSE)) cl.kind = IllegalMove; // [HGM] spartan: only promotion to King was possible
1177 if(piece == BlackLance) cl.kind = ImpossibleMove;
1178 } else { // promotion to King allowed only if we do not haave two yet
1179 int r, f, kings = 0;
1180 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) kings += (board[r][f] == BlackKing);
1181 if(kings == 2) cl.kind = IllegalMove;
1183 } else if(piece == WhitePawn && rt == BOARD_HEIGHT-1 ||
1184 piece == BlackPawn && rt == 0) cl.kind = IllegalMove; // cannot stay Pawn on last rank in any variant
1185 else if((piece == WhiteUnicorn || piece == BlackUnicorn) && gameInfo.variant == VariantKnightmate)
1186 cl.kind = IllegalMove; // promotion to Royal Knight not allowed
1187 else if((piece == WhiteKing || piece == BlackKing) && gameInfo.variant != VariantSuicide && gameInfo.variant != VariantGiveaway)
1188 cl.kind = IllegalMove; // promotion to King usually not allowed
1190 cl.kind = IllegalMove;
1200 extern void MateTestCallback P((Board board, int flags, ChessMove kind,
1201 int rf, int ff, int rt, int ft,
1205 MateTestCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1207 register MateTestClosure *cl = (MateTestClosure *) closure;
1212 /* Return MT_NONE, MT_CHECK, MT_CHECKMATE, or MT_STALEMATE */
1214 MateTest (Board board, int flags)
1217 int inCheck, r, f, myPieces=0, hisPieces=0, nrKing=0;
1218 ChessSquare king = flags & F_WHITE_ON_MOVE ? WhiteKing : BlackKing;
1220 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
1221 // [HGM] losers: Count pieces and kings, to detect other unorthodox winning conditions
1222 nrKing += (board[r][f] == king); // stm has king
1223 if( board[r][f] != EmptySquare ) {
1224 if((int)board[r][f] <= (int)king && (int)board[r][f] >= (int)king - (int)WhiteKing + (int)WhitePawn)
1229 switch(gameInfo.variant) { // [HGM] losers: extinction wins
1230 case VariantShatranj:
1231 if(hisPieces == 1) return myPieces > 1 ? MT_BARE : MT_DRAW;
1235 if(nrKing == 0) return MT_NOKING;
1238 if(myPieces == 1) return MT_BARE;
1241 inCheck = GenLegal(board, flags, MateTestCallback, (VOIDSTAR) &cl, EmptySquare);
1242 // [HGM] 3check: yet to do!
1244 return inCheck ? MT_CHECK : MT_NONE;
1246 if(gameInfo.holdingsWidth && gameInfo.variant != VariantSuper && gameInfo.variant != VariantGreat
1247 && gameInfo.variant != VariantSChess && gameInfo.variant != VariantGrand) { // drop game
1248 int r, f, n, holdings = flags & F_WHITE_ON_MOVE ? BOARD_WIDTH-1 : 0;
1249 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) if(board[r][f] == EmptySquare) // all empty squares
1250 for(n=0; n<BOARD_HEIGHT; n++) // all pieces in hand
1251 if(board[n][holdings] != EmptySquare) {
1252 int moveType = LegalDrop(board, flags, board[n][holdings], r, f);
1253 if(moveType == WhiteDrop || moveType == BlackDrop) return (inCheck ? MT_CHECK : MT_NONE); // we have legal drop
1256 if(gameInfo.variant == VariantSuicide) // [HGM] losers: always stalemate, since no check, but result varies
1257 return myPieces == hisPieces ? MT_STALEMATE :
1258 myPieces > hisPieces ? MT_STAINMATE : MT_STEALMATE;
1259 else if(gameInfo.variant == VariantLosers) return inCheck ? MT_TRICKMATE : MT_STEALMATE;
1260 else if(gameInfo.variant == VariantGiveaway) return MT_STEALMATE; // no check exists, stalemated = win
1262 return inCheck ? MT_CHECKMATE
1263 : (gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShatranj) ?
1264 MT_STAINMATE : MT_STALEMATE;
1269 extern void DisambiguateCallback P((Board board, int flags, ChessMove kind,
1270 int rf, int ff, int rt, int ft,
1274 DisambiguateCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1276 register DisambiguateClosure *cl = (DisambiguateClosure *) closure;
1277 int wildCard = FALSE; ChessSquare piece = board[rf][ff];
1279 // [HGM] wild: for wild-card pieces rt and rf are dummies
1280 if(piece == WhiteFalcon || piece == BlackFalcon ||
1281 piece == WhiteCobra || piece == BlackCobra)
1284 if ((cl->pieceIn == EmptySquare || cl->pieceIn == board[rf][ff]
1285 || PieceToChar(board[rf][ff]) == '~'
1286 && cl->pieceIn == (ChessSquare)(DEMOTED board[rf][ff])
1288 (cl->rfIn == -1 || cl->rfIn == rf) &&
1289 (cl->ffIn == -1 || cl->ffIn == ff) &&
1290 (cl->rtIn == -1 || cl->rtIn == rt || wildCard) &&
1291 (cl->ftIn == -1 || cl->ftIn == ft || wildCard)) {
1294 if(cl->count == 1 || board[rt][ft] != EmptySquare) {
1295 // [HGM] oneclick: if multiple moves, be sure we remember capture
1296 cl->piece = board[rf][ff];
1299 cl->rt = wildCard ? cl->rtIn : rt;
1300 cl->ft = wildCard ? cl->ftIn : ft;
1303 cl->captures += (board[rt][ft] != EmptySquare); // [HGM] oneclick: count captures
1308 Disambiguate (Board board, int flags, DisambiguateClosure *closure)
1310 int illegal = 0; char c = closure->promoCharIn;
1312 if(quickFlag) flags = flags & ~1 | quickFlag & 1; // [HGM] speed: in quick mode quickFlag specifies side-to-move.
1313 closure->count = closure->captures = 0;
1314 closure->rf = closure->ff = closure->rt = closure->ft = 0;
1315 closure->kind = ImpossibleMove;
1316 rFilter = closure->rtIn; // [HGM] speed: only consider moves to given to-square
1317 fFilter = closure->ftIn;
1318 if(quickFlag) { // [HGM] speed: try without check test first, because if that is not ambiguous, we are happy
1319 GenLegal(board, flags|F_IGNORE_CHECK, DisambiguateCallback, (VOIDSTAR) closure, closure->pieceIn);
1320 if(closure->count > 1) { // gamble did not pay off. retry with check test to resolve ambiguity
1321 closure->count = closure->captures = 0;
1322 closure->rf = closure->ff = closure->rt = closure->ft = 0;
1323 closure->kind = ImpossibleMove;
1324 GenLegal(board, flags, DisambiguateCallback, (VOIDSTAR) closure, closure->pieceIn); // [HGM] speed: only pieces of requested type
1327 GenLegal(board, flags, DisambiguateCallback, (VOIDSTAR) closure, closure->pieceIn); // [HGM] speed: only pieces of requested type
1328 if (closure->count == 0) {
1329 /* See if it's an illegal move due to check */
1331 GenLegal(board, flags|F_IGNORE_CHECK, DisambiguateCallback, (VOIDSTAR) closure, closure->pieceIn);
1332 if (closure->count == 0) {
1333 /* No, it's not even that */
1334 if (appData.debugMode) { int i, j;
1335 for(i=BOARD_HEIGHT-1; i>=0; i--) {
1336 for(j=0; j<BOARD_WIDTH; j++)
1337 fprintf(debugFP, "%3d", (int) board[i][j]);
1338 fprintf(debugFP, "\n");
1345 if (c == 'x') c = NULLCHAR; // get rid of any 'x' (which should never happen?)
1346 if(gameInfo.variant == VariantSChess && c && c != '=' && closure->piece != WhitePawn && closure->piece != BlackPawn) {
1347 if(closure->piece < BlackPawn) { // white
1348 if(closure->rf != 0) closure->kind = IllegalMove; // must be on back rank
1349 if(board[PieceToNumber(CharToPiece(ToUpper(c)))][BOARD_WIDTH-2] == 0) closure->kind = ImpossibleMove;// must be in stock
1351 if(closure->rf != BOARD_HEIGHT-1) closure->kind = IllegalMove;
1352 if(board[BOARD_HEIGHT-1-PieceToNumber(CharToPiece(ToLower(c)))][1] == 0) closure->kind = ImpossibleMove;
1355 if(gameInfo.variant == VariantShogi) {
1356 /* [HGM] Shogi promotions. On input, '=' means defer, '+' promote. Afterwards, c is set to '+' for promotions, NULL other */
1357 if(closure->rfIn != DROP_RANK && closure->kind == NormalMove) {
1358 ChessSquare piece = closure->piece;
1359 if (c == 'd' && (piece == WhiteRook || piece == BlackRook) ||
1360 c == 'h' && (piece == WhiteBishop || piece == BlackBishop) ||
1361 c == 'g' && (piece <= WhiteFerz || piece <= BlackFerz && piece >= BlackPawn) )
1362 c = '+'; // allowed ICS notations
1363 if(c != NULLCHAR && c != '+' && c != '=') closure->kind = IllegalMove; // otherwise specifying a piece is illegal
1364 else if(flags & F_WHITE_ON_MOVE) {
1365 if( (int) piece < (int) WhiteWazir &&
1366 (closure->rf >= BOARD_HEIGHT-(BOARD_HEIGHT/3) || closure->rt >= BOARD_HEIGHT-(BOARD_HEIGHT/3)) ) {
1367 if( (piece == WhitePawn || piece == WhiteQueen) && closure->rt > BOARD_HEIGHT-2 ||
1368 piece == WhiteKnight && closure->rt > BOARD_HEIGHT-3) /* promotion mandatory */
1369 closure->kind = c == '=' ? IllegalMove : WhitePromotion;
1370 else /* promotion optional, default is defer */
1371 closure->kind = c == '+' ? WhitePromotion : WhiteNonPromotion;
1372 } else closure->kind = c == '+' ? IllegalMove : NormalMove;
1374 if( (int) piece < (int) BlackWazir && (closure->rf < BOARD_HEIGHT/3 || closure->rt < BOARD_HEIGHT/3) ) {
1375 if( (piece == BlackPawn || piece == BlackQueen) && closure->rt < 1 ||
1376 piece == BlackKnight && closure->rt < 2 ) /* promotion obligatory */
1377 closure->kind = c == '=' ? IllegalMove : BlackPromotion;
1378 else /* promotion optional, default is defer */
1379 closure->kind = c == '+' ? BlackPromotion : BlackNonPromotion;
1380 } else closure->kind = c == '+' ? IllegalMove : NormalMove;
1383 if(closure->kind == WhitePromotion || closure->kind == BlackPromotion) c = '+'; else
1384 if(closure->kind == WhiteNonPromotion || closure->kind == BlackNonPromotion) c = '=';
1386 if (closure->kind == WhitePromotion || closure->kind == BlackPromotion) {
1387 if(c == NULLCHAR) { // missing promoChar on mandatory promotion; use default for variant
1388 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
1389 c = PieceToChar(BlackFerz);
1390 else if(gameInfo.variant == VariantGreat)
1391 c = PieceToChar(BlackMan);
1392 else if(gameInfo.variant == VariantGrand)
1393 closure->kind = closure->rt != 0 && closure->rt != BOARD_HEIGHT-1 ? NormalMove : AmbiguousMove; // no default in Grand Chess
1395 c = PieceToChar(BlackQueen);
1396 } else if(c == '=') closure->kind = IllegalMove; // no deferral outside Shogi
1397 } else if (c != NULLCHAR) closure->kind = IllegalMove;
1399 closure->promoChar = ToLower(c); // this can be NULLCHAR! Note we keep original promoChar even if illegal.
1400 if(c != '+' && c != '=' && c != NULLCHAR && CharToPiece(flags & F_WHITE_ON_MOVE ? ToUpper(c) : ToLower(c)) == EmptySquare)
1401 closure->kind = ImpossibleMove; // but we cannot handle non-existing piece types!
1402 if (closure->count > 1) {
1403 closure->kind = AmbiguousMove;
1406 /* Note: If more than one illegal move matches, but no legal
1407 moves, we return IllegalMove, not AmbiguousMove. Caller
1408 can look at closure->count to detect this.
1410 closure->kind = IllegalMove;
1424 } CoordsToAlgebraicClosure;
1426 extern void CoordsToAlgebraicCallback P((Board board, int flags,
1427 ChessMove kind, int rf, int ff,
1428 int rt, int ft, VOIDSTAR closure));
1431 CoordsToAlgebraicCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1433 register CoordsToAlgebraicClosure *cl =
1434 (CoordsToAlgebraicClosure *) closure;
1436 if ((rt == cl->rt && ft == cl->ft || rt == rf && ft == ff) && // [HGM] null move matches any toSquare
1437 (board[rf][ff] == cl->piece
1438 || PieceToChar(board[rf][ff]) == '~' &&
1439 (ChessSquare) (DEMOTED board[rf][ff]) == cl->piece)
1443 cl->kind = kind; /* this is the move we want */
1445 cl->file++; /* need file to rule out this move */
1449 cl->rank++; /* need rank to rule out this move */
1451 cl->either++; /* rank or file will rule out this move */
1457 /* Convert coordinates to normal algebraic notation.
1458 promoChar must be NULLCHAR or 'x' if not a promotion.
1461 CoordsToAlgebraic (Board board, int flags, int rf, int ff, int rt, int ft, int promoChar, char out[MOVE_LEN])
1465 char *outp = out, c;
1466 CoordsToAlgebraicClosure cl;
1468 if (rf == DROP_RANK) {
1469 if(ff == EmptySquare) { strncpy(outp, "--",3); return NormalMove; } // [HGM] pass
1470 /* Bughouse piece drop */
1471 *outp++ = ToUpper(PieceToChar((ChessSquare) ff));
1476 else { *outp++ = (rt+ONE-'0')/10 + '0';*outp++ = (rt+ONE-'0')%10 + '0'; }
1478 return (flags & F_WHITE_ON_MOVE) ? WhiteDrop : BlackDrop;
1481 if (promoChar == 'x') promoChar = NULLCHAR;
1482 piece = board[rf][ff];
1483 if(PieceToChar(piece)=='~') piece = (ChessSquare)(DEMOTED piece);
1488 kind = LegalityTest(board, flags, rf, ff, rt, ft, promoChar);
1489 if (kind == IllegalMove && !(flags&F_IGNORE_CHECK)) {
1490 /* Keep short notation if move is illegal only because it
1491 leaves the player in check, but still return IllegalMove */
1492 kind = LegalityTest(board, flags|F_IGNORE_CHECK, rf, ff, rt, ft, promoChar);
1493 if (kind == IllegalMove) break;
1498 if (ff == ft && board[rt][ft] == EmptySquare) { /* [HGM] Xiangqi has straight noncapts! */
1499 /* Non-capture; use style "e5" */
1502 else { *outp++ = (rt+ONE-'0')/10 + '0';*outp++ = (rt+ONE-'0')%10 + '0'; }
1504 /* Capture; use style "exd5" */
1505 if(gameInfo.variant != VariantXiangqi || board[rt][ft] != EmptySquare )
1506 *outp++ = 'x'; /* [HGM] Xiangqi has sideway noncaptures across river! */
1510 else { *outp++ = (rt+ONE-'0')/10 + '0';*outp++ = (rt+ONE-'0')%10 + '0'; }
1512 /* Use promotion suffix style "=Q" */
1514 if (promoChar != NULLCHAR) {
1515 if(gameInfo.variant == VariantShogi) {
1516 /* [HGM] ... but not in Shogi! */
1517 *outp++ = promoChar == '=' ? '=' : '+';
1520 *outp++ = ToUpper(promoChar);
1529 /* Fabien moved code: FRC castling first (if KxR), wild castling second */
1530 /* Code added by Tord: FRC castling. */
1531 if((piece == WhiteKing && board[rt][ft] == WhiteRook) ||
1532 (piece == BlackKing && board[rt][ft] == BlackRook)) {
1534 safeStrCpy(out, "O-O", MOVE_LEN);
1536 safeStrCpy(out, "O-O-O", MOVE_LEN);
1537 return LegalityTest(board, flags, rf, ff, rt, ft, promoChar);
1539 /* End of code added by Tord */
1540 /* Test for castling or ICS wild castling */
1541 /* Use style "O-O" (oh-oh) for PGN compatibility */
1542 else if (rf == rt &&
1543 rf == ((piece == WhiteKing) ? 0 : BOARD_HEIGHT-1) &&
1544 (ft - ff > 1 || ff - ft > 1) && // No castling if legal King move (on narrow boards!)
1545 ((ff == BOARD_WIDTH>>1 && (ft == BOARD_LEFT+2 || ft == BOARD_RGHT-2)) ||
1546 (ff == (BOARD_WIDTH-1)>>1 && (ft == BOARD_LEFT+1 || ft == BOARD_RGHT-3)))) {
1547 if(ft==BOARD_LEFT+1 || ft==BOARD_RGHT-2)
1548 snprintf(out, MOVE_LEN, "O-O%c%c", promoChar ? '/' : 0, ToUpper(promoChar));
1550 snprintf(out, MOVE_LEN, "O-O-O%c%c", promoChar ? '/' : 0, ToUpper(promoChar));
1552 /* This notation is always unambiguous, unless there are
1553 kings on both the d and e files, with "wild castling"
1554 possible for the king on the d file and normal castling
1555 possible for the other. ICS rules for wild 9
1556 effectively make castling illegal for either king in
1557 this situation. So I am not going to worry about it;
1558 I'll just generate an ambiguous O-O in this case.
1560 return LegalityTest(board, flags, rf, ff, rt, ft, promoChar);
1563 /* else fall through */
1568 cl.rt = rFilter = rt; // [HGM] speed: filter on to-square
1569 cl.ft = fFilter = ft;
1571 cl.kind = IllegalMove;
1572 cl.rank = cl.file = cl.either = 0;
1573 c = PieceToChar(piece) ;
1574 GenLegal(board, flags, CoordsToAlgebraicCallback, (VOIDSTAR) &cl, c!='~' ? piece : (DEMOTED piece)); // [HGM] speed
1576 if (cl.kind == IllegalMove && !(flags&F_IGNORE_CHECK)) {
1577 /* Generate pretty moves for moving into check, but
1578 still return IllegalMove.
1580 GenLegal(board, flags|F_IGNORE_CHECK, CoordsToAlgebraicCallback, (VOIDSTAR) &cl, c!='~' ? piece : (DEMOTED piece));
1581 if (cl.kind == IllegalMove) break;
1582 cl.kind = IllegalMove;
1585 /* Style is "Nf3" or "Nxf7" if this is unambiguous,
1586 else "Ngf3" or "Ngxf7",
1587 else "N1f3" or "N5xf7",
1588 else "Ng1f3" or "Ng5xf7".
1590 if( c == '~' || c == '+') {
1591 /* [HGM] print nonexistent piece as its demoted version */
1592 piece = (ChessSquare) (DEMOTED piece);
1594 if(c=='+') *outp++ = c;
1595 *outp++ = ToUpper(PieceToChar(piece));
1597 if (cl.file || (cl.either && !cl.rank)) {
1603 else { *outp++ = (rf+ONE-'0')/10 + '0';*outp++ = (rf+ONE-'0')%10 + '0'; }
1606 if(board[rt][ft] != EmptySquare)
1612 else { *outp++ = (rt+ONE-'0')/10 + '0';*outp++ = (rt+ONE-'0')%10 + '0'; }
1613 if (gameInfo.variant == VariantShogi) {
1614 /* [HGM] in Shogi non-pawns can promote */
1615 *outp++ = promoChar; // Don't bother to correct move type, return value is never used!
1617 else if (gameInfo.variant != VariantSuper && promoChar &&
1618 (piece == WhiteLance || piece == BlackLance) ) { // Lance sometimes represents Pawn
1620 *outp++ = ToUpper(promoChar);
1622 else if (gameInfo.variant == VariantSChess && promoChar) { // and in S-Chess we have gating
1624 *outp++ = ToUpper(promoChar);
1630 /* Moving a nonexistent piece */
1634 /* Not a legal move, even ignoring check.
1635 If there was a piece on the from square,
1636 use style "Ng1g3" or "Ng1xe8";
1637 if there was a pawn or nothing (!),
1638 use style "g1g3" or "g1xe8". Use "x"
1639 if a piece was on the to square, even
1640 a piece of the same color.
1644 if (piece != EmptySquare && piece != WhitePawn && piece != BlackPawn) {
1646 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<=BOARD_RGHT; f++)
1647 c += (board[r][f] == piece); // count on-board pieces of given type
1648 *outp++ = ToUpper(PieceToChar(piece));
1650 if(c != 1) { // [HGM] but if there is only one piece of the mentioned type, no from-square, thank you!
1654 else { *outp++ = (rf+ONE-'0')/10 + '0';*outp++ = (rf+ONE-'0')%10 + '0'; }
1656 if (board[rt][ft] != EmptySquare) *outp++ = 'x';
1660 else { *outp++ = (rt+ONE-'0')/10 + '0';*outp++ = (rt+ONE-'0')%10 + '0'; }
1661 /* Use promotion suffix style "=Q" */
1662 if (promoChar != NULLCHAR && promoChar != 'x') {
1664 *outp++ = ToUpper(promoChar);
1671 // [HGM] XQ: the following code serves to detect perpetual chasing (Asian rules)
1680 // I guess the following variables logically belong in the closure too, but I was too lazy and used globals
1682 int preyStackPointer, chaseStackPointer;
1685 unsigned char rf, ff, rt, ft;
1689 unsigned char rank, file;
1695 // there are three new callbacks for use with GenLegal: for adding captures, deleting them, and finding a recapture
1697 extern void AtacksCallback P((Board board, int flags, ChessMove kind,
1698 int rf, int ff, int rt, int ft,
1702 AttacksCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1703 { // For adding captures that can lead to chase indictment to the chaseStack
1704 if(board[rt][ft] == EmptySquare) return; // non-capture
1705 if(board[rt][ft] == WhitePawn && rt < BOARD_HEIGHT/2) return; // Pawn before river can be chased
1706 if(board[rt][ft] == BlackPawn && rt >= BOARD_HEIGHT/2) return; // Pawn before river can be chased
1707 if(board[rf][ff] == WhitePawn || board[rf][ff] == BlackPawn) return; // Pawns are allowed to chase
1708 if(board[rf][ff] == WhiteWazir || board[rf][ff] == BlackWazir) return; // King is allowed to chase
1709 // move cannot be excluded from being a chase trivially (based on attacker and victim); save it on chaseStack
1710 chaseStack[chaseStackPointer].rf = rf;
1711 chaseStack[chaseStackPointer].ff = ff;
1712 chaseStack[chaseStackPointer].rt = rt;
1713 chaseStack[chaseStackPointer].ft = ft;
1714 chaseStackPointer++;
1717 extern void ExistingAtacksCallback P((Board board, int flags, ChessMove kind,
1718 int rf, int ff, int rt, int ft,
1722 ExistingAttacksCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1723 { // for removing pre-exsting captures from the chaseStack, to be left with newly created ones
1725 register ChaseClosure *cl = (ChaseClosure *) closure; //closure tells us the move played in the repeat loop
1727 if(board[rt][ft] == EmptySquare) return; // no capture
1728 if(rf == cl->rf && ff == cl->ff) { // attacks with same piece from new position are not considered new
1729 rf = cl->rt; ff = cl->ft; // doctor their fromSquare so they will be recognized in chaseStack
1731 // search move in chaseStack, and delete it if it occurred there (as we know now it is not a new capture)
1732 for(i=0; i<chaseStackPointer; i++) {
1733 if(chaseStack[i].rf == rf && chaseStack[i].ff == ff &&
1734 chaseStack[i].rt == rt && chaseStack[i].ft == ft ) {
1735 // move found on chaseStack, delete it by overwriting with move popped from top of chaseStack
1736 chaseStack[i] = chaseStack[--chaseStackPointer];
1742 extern void ProtectedCallback P((Board board, int flags, ChessMove kind,
1743 int rf, int ff, int rt, int ft,
1747 ProtectedCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1748 { // for determining if a piece (given through the closure) is protected
1749 register ChaseClosure *cl = (ChaseClosure *) closure; // closure tells us where to recapture
1751 if(rt == cl->rt && ft == cl->ft) cl->recaptures++; // count legal recaptures to this square
1752 if(appData.debugMode && board[rt][ft] != EmptySquare)
1753 fprintf(debugFP, "try %c%c%c%c=%d\n", ff+AAA, rf+ONE,ft+AAA, rt+ONE, cl->recaptures);
1756 extern char moveList[MAX_MOVES][MOVE_LEN];
1759 PerpetualChase (int first, int last)
1760 { // this routine detects if the side to move in the 'first' position is perpetually chasing (when not checking)
1763 ChessSquare captured;
1765 preyStackPointer = 0; // clear stack of chased pieces
1766 for(i=first; i<last; i+=2) { // for all positions with same side to move
1767 if(appData.debugMode) fprintf(debugFP, "judge position %i\n", i);
1768 chaseStackPointer = 0; // clear stack that is going to hold possible chases
1769 // determine all captures possible after the move, and put them on chaseStack
1770 GenLegal(boards[i+1], PosFlags(i), AttacksCallback, &cl, EmptySquare);
1771 if(appData.debugMode) { int n;
1772 for(n=0; n<chaseStackPointer; n++)
1773 fprintf(debugFP, "%c%c%c%c ", chaseStack[n].ff+AAA, chaseStack[n].rf+ONE,
1774 chaseStack[n].ft+AAA, chaseStack[n].rt+ONE);
1775 fprintf(debugFP, ": all capts\n");
1777 // determine all captures possible before the move, and delete them from chaseStack
1778 cl.rf = moveList[i][1]-ONE; // prepare closure to pass move that led from i to i+1
1779 cl.ff = moveList[i][0]-AAA+BOARD_LEFT;
1780 cl.rt = moveList[i][3]-ONE;
1781 cl.ft = moveList[i][2]-AAA+BOARD_LEFT;
1782 CopyBoard(xqCheckers, nullBoard); xqCheckers[EP_STATUS] = 1; // giant kludge to make GenLegal ignore pre-existing checks
1783 GenLegal(boards[i], PosFlags(i), ExistingAttacksCallback, &cl, EmptySquare);
1784 xqCheckers[EP_STATUS] = 0; // disable the generation of quasi-legal moves again
1785 if(appData.debugMode) { int n;
1786 for(n=0; n<chaseStackPointer; n++)
1787 fprintf(debugFP, "%c%c%c%c ", chaseStack[n].ff+AAA, chaseStack[n].rf+ONE,
1788 chaseStack[n].ft+AAA, chaseStack[n].rt+ONE);
1789 fprintf(debugFP, ": new capts after %c%c%c%c\n", cl.ff+AAA, cl.rf+ONE, cl.ft+AAA, cl.rt+ONE);
1791 // chaseSack now contains all captures made possible by the move
1792 for(j=0; j<chaseStackPointer; j++) { // run through chaseStack to identify true chases
1793 int attacker = (int)boards[i+1][chaseStack[j].rf][chaseStack[j].ff];
1794 int victim = (int)boards[i+1][chaseStack[j].rt][chaseStack[j].ft];
1796 if(attacker >= (int) BlackPawn) attacker = BLACK_TO_WHITE attacker; // convert to white, as piecee type
1797 if(victim >= (int) BlackPawn) victim = BLACK_TO_WHITE victim;
1799 if((attacker == WhiteKnight || attacker == WhiteCannon) && victim == WhiteRook)
1800 continue; // C or H attack on R is always chase; leave on chaseStack
1802 if(attacker == victim) {
1803 if(LegalityTest(boards[i+1], PosFlags(i+1), chaseStack[j].rt,
1804 chaseStack[j].ft, chaseStack[j].rf, chaseStack[j].ff, NULLCHAR) == NormalMove) {
1805 // we can capture back with equal piece, so this is no chase but a sacrifice
1806 chaseStack[j] = chaseStack[--chaseStackPointer]; // delete the capture from the chaseStack
1807 j--; /* ! */ continue;
1812 // the attack is on a lower piece, or on a pinned or blocked equal one
1813 CopyBoard(xqCheckers, nullBoard); xqCheckers[EP_STATUS] = 1;
1814 CheckTest(boards[i+1], PosFlags(i+1), -1, -1, -1, -1, FALSE); // if we deliver check with our move, the checkers get marked
1815 // test if the victim is protected by a true protector. First make the capture.
1816 captured = boards[i+1][chaseStack[j].rt][chaseStack[j].ft];
1817 boards[i+1][chaseStack[j].rt][chaseStack[j].ft] = boards[i+1][chaseStack[j].rf][chaseStack[j].ff];
1818 boards[i+1][chaseStack[j].rf][chaseStack[j].ff] = EmptySquare;
1819 // Then test if the opponent can recapture
1820 cl.recaptures = 0; // prepare closure to pass recapture square and count moves to it
1821 cl.rt = chaseStack[j].rt;
1822 cl.ft = chaseStack[j].ft;
1823 if(appData.debugMode) {
1824 fprintf(debugFP, "test if we can recapture %c%c\n", cl.ft+AAA, cl.rt+ONE);
1826 xqCheckers[EP_STATUS] = 2; // causes GenLegal to ignore the checks we delivered with the move, in real life evaded before we captured
1827 GenLegal(boards[i+1], PosFlags(i+1), ProtectedCallback, &cl, EmptySquare); // try all moves
1828 xqCheckers[EP_STATUS] = 0; // disable quasi-legal moves again
1829 // unmake the capture
1830 boards[i+1][chaseStack[j].rf][chaseStack[j].ff] = boards[i+1][chaseStack[j].rt][chaseStack[j].ft];
1831 boards[i+1][chaseStack[j].rt][chaseStack[j].ft] = captured;
1832 // if a recapture was found, piece is protected, and we are not chasing it.
1833 if(cl.recaptures) { // attacked piece was defended by true protector, no chase
1834 chaseStack[j] = chaseStack[--chaseStackPointer]; // so delete from chaseStack
1838 // chaseStack now contains all moves that chased
1839 if(appData.debugMode) { int n;
1840 for(n=0; n<chaseStackPointer; n++)
1841 fprintf(debugFP, "%c%c%c%c ", chaseStack[n].ff+AAA, chaseStack[n].rf+ONE,
1842 chaseStack[n].ft+AAA, chaseStack[n].rt+ONE);
1843 fprintf(debugFP, ": chases\n");
1845 if(i == first) { // copy all people chased by first move of repeat cycle to preyStack
1846 for(j=0; j<chaseStackPointer; j++) {
1847 preyStack[j].rank = chaseStack[j].rt;
1848 preyStack[j].file = chaseStack[j].ft;
1850 preyStackPointer = chaseStackPointer;
1853 for(j=0; j<chaseStackPointer; j++) {
1854 for(k=0; k<preyStackPointer; k++) {
1855 // search the victim of each chase move on the preyStack (first occurrence)
1856 if(chaseStack[j].ft == preyStack[k].file && chaseStack[j].rt == preyStack[k].rank ) {
1857 if(k < tail) break; // piece was already identified as still being chased
1858 preyStack[preyStackPointer] = preyStack[tail]; // move chased piece to bottom part of preyStack
1859 preyStack[tail] = preyStack[k]; // by swapping
1860 preyStack[k] = preyStack[preyStackPointer];
1866 preyStackPointer = tail; // keep bottom part of preyStack, popping pieces unchased on move i.
1867 if(appData.debugMode) { int n;
1868 for(n=0; n<preyStackPointer; n++)
1869 fprintf(debugFP, "%c%c ", preyStack[n].file+AAA, preyStack[n].rank+ONE);
1870 fprintf(debugFP, "always chased upto ply %d\n", i);
1872 // now adjust the location of the chased pieces according to opponent move
1873 for(j=0; j<preyStackPointer; j++) {
1874 if(preyStack[j].rank == moveList[i+1][1]-ONE &&
1875 preyStack[j].file == moveList[i+1][0]-AAA+BOARD_LEFT) {
1876 preyStack[j].rank = moveList[i+1][3]-ONE;
1877 preyStack[j].file = moveList[i+1][2]-AAA+BOARD_LEFT;
1882 return preyStackPointer ? 256*(preyStack[preyStackPointer].file - BOARD_LEFT + AAA) + (preyStack[preyStackPointer].rank + ONE)
1883 : 0; // if any piece was left on preyStack, it has been perpetually chased,and we return the