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 && gameInfo.variant != VariantBughouse) // in bughouse we don't check for availability, because ICS doesn't always tell us
1058 return ImpossibleMove; // piece not available
1059 if(gameInfo.variant == VariantShogi) { // in Shogi lots of drops are forbidden!
1060 if((piece == WhitePawn || piece == WhiteQueen) && rt == BOARD_HEIGHT-1 ||
1061 (piece == BlackPawn || piece == BlackQueen) && rt == 0 ||
1062 piece == WhiteKnight && rt > BOARD_HEIGHT-3 ||
1063 piece == BlackKnight && rt < 2 ) return IllegalMove; // e.g. where dropped piece has no moves
1064 if(piece == WhitePawn || piece == BlackPawn) {
1066 for(r=1; r<BOARD_HEIGHT-1; r++)
1067 if(board[r][ft] == piece) return IllegalMove; // or there already is a Pawn in file
1068 // should still test if we mate with this Pawn
1070 } else if(gameInfo.variant == VariantSChess) { // only back-rank drops
1071 if (rt != (piece < BlackPawn ? 0 : BOARD_HEIGHT-1)) return IllegalMove;
1073 if( (piece == WhitePawn || piece == BlackPawn) &&
1074 (rt == 0 || rt == BOARD_HEIGHT -1 ) )
1075 return IllegalMove; /* no pawn drops on 1st/8th */
1077 if(appData.debugMode) fprintf(debugFP, "LegalDrop: %d @ %d,%d)\n", piece, ft, rt);
1078 if (!(flags & F_IGNORE_CHECK) &&
1079 CheckTest(board, flags, DROP_RANK, piece, rt, ft, FALSE) ) return IllegalMove;
1080 return flags & F_WHITE_ON_MOVE ? WhiteDrop : BlackDrop;
1083 extern void LegalityTestCallback P((Board board, int flags, ChessMove kind,
1084 int rf, int ff, int rt, int ft,
1088 LegalityTestCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1090 register LegalityTestClosure *cl = (LegalityTestClosure *) closure;
1092 if(board[rt][ft] != EmptySquare || kind==WhiteCapturesEnPassant || kind==BlackCapturesEnPassant)
1093 cl->captures++; // [HGM] losers: count legal captures
1094 if (rf == cl->rf && ff == cl->ff && rt == cl->rt && ft == cl->ft)
1099 LegalityTest (Board board, int flags, int rf, int ff, int rt, int ft, int promoChar)
1101 LegalityTestClosure cl; ChessSquare piece, filterPiece;
1103 if(quickFlag) flags = flags & ~1 | quickFlag & 1; // [HGM] speed: in quick mode quickFlag specifies side-to-move.
1104 if(rf == DROP_RANK) return LegalDrop(board, flags, ff, rt, ft);
1105 piece = filterPiece = board[rf][ff];
1106 if(PieceToChar(piece) == '~') filterPiece = DEMOTED piece;
1108 /* [HGM] Cobra and Falcon are wildcard pieces; consider all their moves legal */
1109 /* (perhaps we should disallow moves that obviously leave us in check?) */
1110 if(piece == WhiteFalcon || piece == BlackFalcon ||
1111 piece == WhiteCobra || piece == BlackCobra)
1112 return CheckTest(board, flags, rf, ff, rt, ft, FALSE) ? IllegalMove : NormalMove;
1116 cl.rt = rFilter = rt; // [HGM] speed: filter on to-square
1117 cl.ft = fFilter = ft;
1118 cl.kind = IllegalMove;
1119 cl.captures = 0; // [HGM] losers: prepare to count legal captures.
1120 if(flags & F_MANDATORY_CAPTURE) filterPiece = EmptySquare; // [HGM] speed: do not filter in suicide, to find all captures
1121 GenLegal(board, flags, LegalityTestCallback, (VOIDSTAR) &cl, filterPiece);
1122 if((flags & F_MANDATORY_CAPTURE) && cl.captures && board[rt][ft] == EmptySquare
1123 && cl.kind != WhiteCapturesEnPassant && cl.kind != BlackCapturesEnPassant)
1124 return(IllegalMove); // [HGM] losers: if there are legal captures, non-capts are illegal
1126 if(promoChar == 'x') promoChar = NULLCHAR; // [HGM] is this ever the case?
1127 if(gameInfo.variant == VariantSChess && promoChar && promoChar != '=' && board[rf][ff] != WhitePawn && board[rf][ff] != BlackPawn) {
1128 if(board[rf][ff] < BlackPawn) { // white
1129 if(rf != 0) return IllegalMove; // must be on back rank
1130 if(board[PieceToNumber(CharToPiece(ToUpper(promoChar)))][BOARD_WIDTH-2] == 0) return ImpossibleMove;// must be in stock
1132 if(rf != BOARD_HEIGHT-1) return IllegalMove;
1133 if(board[BOARD_HEIGHT-1-PieceToNumber(CharToPiece(ToLower(promoChar)))][1] == 0) return ImpossibleMove;
1136 if(gameInfo.variant == VariantShogi) {
1137 /* [HGM] Shogi promotions. '=' means defer */
1138 if(rf != DROP_RANK && cl.kind == NormalMove) {
1139 ChessSquare piece = board[rf][ff];
1141 if(promoChar == PieceToChar(BlackQueen)) promoChar = NULLCHAR; /* [HGM] Kludge */
1142 if(promoChar == 'd' && (piece == WhiteRook || piece == BlackRook) ||
1143 promoChar == 'h' && (piece == WhiteBishop || piece == BlackBishop) ||
1144 promoChar == 'g' && (piece <= WhiteFerz || piece <= BlackFerz && piece >= BlackPawn) )
1145 promoChar = '+'; // allowed ICS notations
1146 if(appData.debugMode)fprintf(debugFP,"SHOGI promoChar = %c\n", promoChar ? promoChar : '-');
1147 if(promoChar != NULLCHAR && promoChar != '+' && promoChar != '=')
1148 return CharToPiece(promoChar) == EmptySquare ? ImpossibleMove : IllegalMove;
1149 else if(flags & F_WHITE_ON_MOVE) {
1150 if( (int) piece < (int) WhiteWazir &&
1151 (rf >= BOARD_HEIGHT*2/3 || rt >= BOARD_HEIGHT*2/3) ) {
1152 if( (piece == WhitePawn || piece == WhiteQueen) && rt > BOARD_HEIGHT-2 ||
1153 piece == WhiteKnight && rt > BOARD_HEIGHT-3) /* promotion mandatory */
1154 cl.kind = promoChar == '=' ? IllegalMove : WhitePromotion;
1155 else /* promotion optional, default is defer */
1156 cl.kind = promoChar == '+' ? WhitePromotion : WhiteNonPromotion;
1157 } else cl.kind = promoChar == '+' ? IllegalMove : NormalMove;
1159 if( (int) piece < (int) BlackWazir && (rf < BOARD_HEIGHT/3 || rt < BOARD_HEIGHT/3) ) {
1160 if( (piece == BlackPawn || piece == BlackQueen) && rt < 1 ||
1161 piece == BlackKnight && rt < 2 ) /* promotion obligatory */
1162 cl.kind = promoChar == '=' ? IllegalMove : BlackPromotion;
1163 else /* promotion optional, default is defer */
1164 cl.kind = promoChar == '+' ? BlackPromotion : BlackNonPromotion;
1165 } else cl.kind = promoChar == '+' ? IllegalMove : NormalMove;
1169 if (promoChar != NULLCHAR) {
1170 if(promoChar == '=') cl.kind = IllegalMove; else // [HGM] shogi: no deferred promotion outside Shogi
1171 if (cl.kind == WhitePromotion || cl.kind == BlackPromotion) {
1172 ChessSquare piece = CharToPiece(flags & F_WHITE_ON_MOVE ? ToUpper(promoChar) : ToLower(promoChar));
1173 if(piece == EmptySquare)
1174 cl.kind = ImpossibleMove; // non-existing piece
1175 if(gameInfo.variant == VariantSpartan && cl.kind == BlackPromotion ) {
1176 if(promoChar != PieceToChar(BlackKing)) {
1177 if(CheckTest(board, flags, rf, ff, rt, ft, FALSE)) cl.kind = IllegalMove; // [HGM] spartan: only promotion to King was possible
1178 if(piece == BlackLance) cl.kind = ImpossibleMove;
1179 } else { // promotion to King allowed only if we do not haave two yet
1180 int r, f, kings = 0;
1181 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) kings += (board[r][f] == BlackKing);
1182 if(kings == 2) cl.kind = IllegalMove;
1184 } else if(piece == WhitePawn && rt == BOARD_HEIGHT-1 ||
1185 piece == BlackPawn && rt == 0) cl.kind = IllegalMove; // cannot stay Pawn on last rank in any variant
1186 else if((piece == WhiteUnicorn || piece == BlackUnicorn) && gameInfo.variant == VariantKnightmate)
1187 cl.kind = IllegalMove; // promotion to Royal Knight not allowed
1188 else if((piece == WhiteKing || piece == BlackKing) && gameInfo.variant != VariantSuicide && gameInfo.variant != VariantGiveaway)
1189 cl.kind = IllegalMove; // promotion to King usually not allowed
1191 cl.kind = IllegalMove;
1201 extern void MateTestCallback P((Board board, int flags, ChessMove kind,
1202 int rf, int ff, int rt, int ft,
1206 MateTestCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1208 register MateTestClosure *cl = (MateTestClosure *) closure;
1213 /* Return MT_NONE, MT_CHECK, MT_CHECKMATE, or MT_STALEMATE */
1215 MateTest (Board board, int flags)
1218 int inCheck, r, f, myPieces=0, hisPieces=0, nrKing=0;
1219 ChessSquare king = flags & F_WHITE_ON_MOVE ? WhiteKing : BlackKing;
1221 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
1222 // [HGM] losers: Count pieces and kings, to detect other unorthodox winning conditions
1223 nrKing += (board[r][f] == king); // stm has king
1224 if( board[r][f] != EmptySquare ) {
1225 if((int)board[r][f] <= (int)king && (int)board[r][f] >= (int)king - (int)WhiteKing + (int)WhitePawn)
1230 switch(gameInfo.variant) { // [HGM] losers: extinction wins
1231 case VariantShatranj:
1232 if(hisPieces == 1) return myPieces > 1 ? MT_BARE : MT_DRAW;
1236 if(nrKing == 0) return MT_NOKING;
1239 if(myPieces == 1) return MT_BARE;
1242 inCheck = GenLegal(board, flags, MateTestCallback, (VOIDSTAR) &cl, EmptySquare);
1243 // [HGM] 3check: yet to do!
1245 return inCheck ? MT_CHECK : MT_NONE;
1247 if(gameInfo.holdingsWidth && gameInfo.variant != VariantSuper && gameInfo.variant != VariantGreat
1248 && gameInfo.variant != VariantSChess && gameInfo.variant != VariantGrand) { // drop game
1249 int r, f, n, holdings = flags & F_WHITE_ON_MOVE ? BOARD_WIDTH-1 : 0;
1250 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) if(board[r][f] == EmptySquare) // all empty squares
1251 for(n=0; n<BOARD_HEIGHT; n++) // all pieces in hand
1252 if(board[n][holdings] != EmptySquare) {
1253 int moveType = LegalDrop(board, flags, board[n][holdings], r, f);
1254 if(moveType == WhiteDrop || moveType == BlackDrop) return (inCheck ? MT_CHECK : MT_NONE); // we have legal drop
1257 if(gameInfo.variant == VariantSuicide) // [HGM] losers: always stalemate, since no check, but result varies
1258 return myPieces == hisPieces ? MT_STALEMATE :
1259 myPieces > hisPieces ? MT_STAINMATE : MT_STEALMATE;
1260 else if(gameInfo.variant == VariantLosers) return inCheck ? MT_TRICKMATE : MT_STEALMATE;
1261 else if(gameInfo.variant == VariantGiveaway) return MT_STEALMATE; // no check exists, stalemated = win
1263 return inCheck ? MT_CHECKMATE
1264 : (gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShatranj) ?
1265 MT_STAINMATE : MT_STALEMATE;
1270 extern void DisambiguateCallback P((Board board, int flags, ChessMove kind,
1271 int rf, int ff, int rt, int ft,
1275 DisambiguateCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1277 register DisambiguateClosure *cl = (DisambiguateClosure *) closure;
1278 int wildCard = FALSE; ChessSquare piece = board[rf][ff];
1280 // [HGM] wild: for wild-card pieces rt and rf are dummies
1281 if(piece == WhiteFalcon || piece == BlackFalcon ||
1282 piece == WhiteCobra || piece == BlackCobra)
1285 if ((cl->pieceIn == EmptySquare || cl->pieceIn == board[rf][ff]
1286 || PieceToChar(board[rf][ff]) == '~'
1287 && cl->pieceIn == (ChessSquare)(DEMOTED board[rf][ff])
1289 (cl->rfIn == -1 || cl->rfIn == rf) &&
1290 (cl->ffIn == -1 || cl->ffIn == ff) &&
1291 (cl->rtIn == -1 || cl->rtIn == rt || wildCard) &&
1292 (cl->ftIn == -1 || cl->ftIn == ft || wildCard)) {
1295 if(cl->count == 1 || board[rt][ft] != EmptySquare) {
1296 // [HGM] oneclick: if multiple moves, be sure we remember capture
1297 cl->piece = board[rf][ff];
1300 cl->rt = wildCard ? cl->rtIn : rt;
1301 cl->ft = wildCard ? cl->ftIn : ft;
1304 cl->captures += (board[rt][ft] != EmptySquare); // [HGM] oneclick: count captures
1309 Disambiguate (Board board, int flags, DisambiguateClosure *closure)
1311 int illegal = 0; char c = closure->promoCharIn;
1313 if(quickFlag) flags = flags & ~1 | quickFlag & 1; // [HGM] speed: in quick mode quickFlag specifies side-to-move.
1314 closure->count = closure->captures = 0;
1315 closure->rf = closure->ff = closure->rt = closure->ft = 0;
1316 closure->kind = ImpossibleMove;
1317 rFilter = closure->rtIn; // [HGM] speed: only consider moves to given to-square
1318 fFilter = closure->ftIn;
1319 if(quickFlag) { // [HGM] speed: try without check test first, because if that is not ambiguous, we are happy
1320 GenLegal(board, flags|F_IGNORE_CHECK, DisambiguateCallback, (VOIDSTAR) closure, closure->pieceIn);
1321 if(closure->count > 1) { // gamble did not pay off. retry with check test to resolve ambiguity
1322 closure->count = closure->captures = 0;
1323 closure->rf = closure->ff = closure->rt = closure->ft = 0;
1324 closure->kind = ImpossibleMove;
1325 GenLegal(board, flags, DisambiguateCallback, (VOIDSTAR) closure, closure->pieceIn); // [HGM] speed: only pieces of requested type
1328 GenLegal(board, flags, DisambiguateCallback, (VOIDSTAR) closure, closure->pieceIn); // [HGM] speed: only pieces of requested type
1329 if (closure->count == 0) {
1330 /* See if it's an illegal move due to check */
1332 GenLegal(board, flags|F_IGNORE_CHECK, DisambiguateCallback, (VOIDSTAR) closure, closure->pieceIn);
1333 if (closure->count == 0) {
1334 /* No, it's not even that */
1335 if(!appData.testLegality && closure->pieceIn != EmptySquare) {
1336 int f, r; // if there is only a single piece of the requested type on the board, use that
1337 closure->rt = closure->rtIn, closure->ft = closure->ftIn;
1338 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
1339 if(board[r][f] == closure->pieceIn) closure->count++, closure->rf = r, closure->ff = f;
1340 if(closure->count > 1) illegal = 0; // ambiguous
1342 if(closure->count == 0) {
1343 if (appData.debugMode) { int i, j;
1344 for(i=BOARD_HEIGHT-1; i>=0; i--) {
1345 for(j=0; j<BOARD_WIDTH; j++)
1346 fprintf(debugFP, "%3d", (int) board[i][j]);
1347 fprintf(debugFP, "\n");
1355 if (c == 'x') c = NULLCHAR; // get rid of any 'x' (which should never happen?)
1356 if(gameInfo.variant == VariantSChess && c && c != '=' && closure->piece != WhitePawn && closure->piece != BlackPawn) {
1357 if(closure->piece < BlackPawn) { // white
1358 if(closure->rf != 0) closure->kind = IllegalMove; // must be on back rank
1359 if(board[PieceToNumber(CharToPiece(ToUpper(c)))][BOARD_WIDTH-2] == 0) closure->kind = ImpossibleMove;// must be in stock
1361 if(closure->rf != BOARD_HEIGHT-1) closure->kind = IllegalMove;
1362 if(board[BOARD_HEIGHT-1-PieceToNumber(CharToPiece(ToLower(c)))][1] == 0) closure->kind = ImpossibleMove;
1365 if(gameInfo.variant == VariantShogi) {
1366 /* [HGM] Shogi promotions. On input, '=' means defer, '+' promote. Afterwards, c is set to '+' for promotions, NULL other */
1367 if(closure->rfIn != DROP_RANK && closure->kind == NormalMove) {
1368 ChessSquare piece = closure->piece;
1369 if (c == 'd' && (piece == WhiteRook || piece == BlackRook) ||
1370 c == 'h' && (piece == WhiteBishop || piece == BlackBishop) ||
1371 c == 'g' && (piece <= WhiteFerz || piece <= BlackFerz && piece >= BlackPawn) )
1372 c = '+'; // allowed ICS notations
1373 if(c != NULLCHAR && c != '+' && c != '=') closure->kind = IllegalMove; // otherwise specifying a piece is illegal
1374 else if(flags & F_WHITE_ON_MOVE) {
1375 if( (int) piece < (int) WhiteWazir &&
1376 (closure->rf >= BOARD_HEIGHT-(BOARD_HEIGHT/3) || closure->rt >= BOARD_HEIGHT-(BOARD_HEIGHT/3)) ) {
1377 if( (piece == WhitePawn || piece == WhiteQueen) && closure->rt > BOARD_HEIGHT-2 ||
1378 piece == WhiteKnight && closure->rt > BOARD_HEIGHT-3) /* promotion mandatory */
1379 closure->kind = c == '=' ? IllegalMove : WhitePromotion;
1380 else /* promotion optional, default is defer */
1381 closure->kind = c == '+' ? WhitePromotion : WhiteNonPromotion;
1382 } else closure->kind = c == '+' ? IllegalMove : NormalMove;
1384 if( (int) piece < (int) BlackWazir && (closure->rf < BOARD_HEIGHT/3 || closure->rt < BOARD_HEIGHT/3) ) {
1385 if( (piece == BlackPawn || piece == BlackQueen) && closure->rt < 1 ||
1386 piece == BlackKnight && closure->rt < 2 ) /* promotion obligatory */
1387 closure->kind = c == '=' ? IllegalMove : BlackPromotion;
1388 else /* promotion optional, default is defer */
1389 closure->kind = c == '+' ? BlackPromotion : BlackNonPromotion;
1390 } else closure->kind = c == '+' ? IllegalMove : NormalMove;
1393 if(closure->kind == WhitePromotion || closure->kind == BlackPromotion) c = '+'; else
1394 if(closure->kind == WhiteNonPromotion || closure->kind == BlackNonPromotion) c = '=';
1396 if (closure->kind == WhitePromotion || closure->kind == BlackPromotion) {
1397 if(c == NULLCHAR) { // missing promoChar on mandatory promotion; use default for variant
1398 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
1399 c = PieceToChar(BlackFerz);
1400 else if(gameInfo.variant == VariantGreat)
1401 c = PieceToChar(BlackMan);
1402 else if(gameInfo.variant == VariantGrand)
1403 closure->kind = closure->rt != 0 && closure->rt != BOARD_HEIGHT-1 ? NormalMove : AmbiguousMove; // no default in Grand Chess
1405 c = PieceToChar(BlackQueen);
1406 } else if(c == '=') closure->kind = IllegalMove; // no deferral outside Shogi
1407 } else if (c != NULLCHAR) closure->kind = IllegalMove;
1409 closure->promoChar = ToLower(c); // this can be NULLCHAR! Note we keep original promoChar even if illegal.
1410 if(c != '+' && c != '=' && c != NULLCHAR && CharToPiece(flags & F_WHITE_ON_MOVE ? ToUpper(c) : ToLower(c)) == EmptySquare)
1411 closure->kind = ImpossibleMove; // but we cannot handle non-existing piece types!
1412 if (closure->count > 1) {
1413 closure->kind = AmbiguousMove;
1416 /* Note: If more than one illegal move matches, but no legal
1417 moves, we return IllegalMove, not AmbiguousMove. Caller
1418 can look at closure->count to detect this.
1420 closure->kind = IllegalMove;
1434 } CoordsToAlgebraicClosure;
1436 extern void CoordsToAlgebraicCallback P((Board board, int flags,
1437 ChessMove kind, int rf, int ff,
1438 int rt, int ft, VOIDSTAR closure));
1441 CoordsToAlgebraicCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1443 register CoordsToAlgebraicClosure *cl =
1444 (CoordsToAlgebraicClosure *) closure;
1446 if ((rt == cl->rt && ft == cl->ft || rt == rf && ft == ff) && // [HGM] null move matches any toSquare
1447 (board[rf][ff] == cl->piece
1448 || PieceToChar(board[rf][ff]) == '~' &&
1449 (ChessSquare) (DEMOTED board[rf][ff]) == cl->piece)
1453 cl->kind = kind; /* this is the move we want */
1455 cl->file++; /* need file to rule out this move */
1459 cl->rank++; /* need rank to rule out this move */
1461 cl->either++; /* rank or file will rule out this move */
1467 /* Convert coordinates to normal algebraic notation.
1468 promoChar must be NULLCHAR or 'x' if not a promotion.
1471 CoordsToAlgebraic (Board board, int flags, int rf, int ff, int rt, int ft, int promoChar, char out[MOVE_LEN])
1475 char *outp = out, c;
1476 CoordsToAlgebraicClosure cl;
1478 if (rf == DROP_RANK) {
1479 if(ff == EmptySquare) { strncpy(outp, "--",3); return NormalMove; } // [HGM] pass
1480 /* Bughouse piece drop */
1481 *outp++ = ToUpper(PieceToChar((ChessSquare) ff));
1486 else { *outp++ = (rt+ONE-'0')/10 + '0';*outp++ = (rt+ONE-'0')%10 + '0'; }
1488 return (flags & F_WHITE_ON_MOVE) ? WhiteDrop : BlackDrop;
1491 if (promoChar == 'x') promoChar = NULLCHAR;
1492 piece = board[rf][ff];
1493 if(PieceToChar(piece)=='~') piece = (ChessSquare)(DEMOTED piece);
1498 kind = LegalityTest(board, flags, rf, ff, rt, ft, promoChar);
1499 if (kind == IllegalMove && !(flags&F_IGNORE_CHECK)) {
1500 /* Keep short notation if move is illegal only because it
1501 leaves the player in check, but still return IllegalMove */
1502 kind = LegalityTest(board, flags|F_IGNORE_CHECK, rf, ff, rt, ft, promoChar);
1503 if (kind == IllegalMove) break;
1508 if (ff == ft && board[rt][ft] == EmptySquare) { /* [HGM] Xiangqi has straight noncapts! */
1509 /* Non-capture; use style "e5" */
1512 else { *outp++ = (rt+ONE-'0')/10 + '0';*outp++ = (rt+ONE-'0')%10 + '0'; }
1514 /* Capture; use style "exd5" */
1515 if(gameInfo.variant != VariantXiangqi || board[rt][ft] != EmptySquare )
1516 *outp++ = 'x'; /* [HGM] Xiangqi has sideway noncaptures across river! */
1520 else { *outp++ = (rt+ONE-'0')/10 + '0';*outp++ = (rt+ONE-'0')%10 + '0'; }
1522 /* Use promotion suffix style "=Q" */
1524 if (promoChar != NULLCHAR) {
1525 if(gameInfo.variant == VariantShogi) {
1526 /* [HGM] ... but not in Shogi! */
1527 *outp++ = promoChar == '=' ? '=' : '+';
1530 *outp++ = ToUpper(promoChar);
1539 /* Fabien moved code: FRC castling first (if KxR), wild castling second */
1540 /* Code added by Tord: FRC castling. */
1541 if((piece == WhiteKing && board[rt][ft] == WhiteRook) ||
1542 (piece == BlackKing && board[rt][ft] == BlackRook)) {
1544 safeStrCpy(out, "O-O", MOVE_LEN);
1546 safeStrCpy(out, "O-O-O", MOVE_LEN);
1547 return LegalityTest(board, flags, rf, ff, rt, ft, promoChar);
1549 /* End of code added by Tord */
1550 /* Test for castling or ICS wild castling */
1551 /* Use style "O-O" (oh-oh) for PGN compatibility */
1552 else if (rf == rt &&
1553 rf == ((piece == WhiteKing) ? 0 : BOARD_HEIGHT-1) &&
1554 (ft - ff > 1 || ff - ft > 1) && // No castling if legal King move (on narrow boards!)
1555 ((ff == BOARD_WIDTH>>1 && (ft == BOARD_LEFT+2 || ft == BOARD_RGHT-2)) ||
1556 (ff == (BOARD_WIDTH-1)>>1 && (ft == BOARD_LEFT+1 || ft == BOARD_RGHT-3)))) {
1557 if(ft==BOARD_LEFT+1 || ft==BOARD_RGHT-2)
1558 snprintf(out, MOVE_LEN, "O-O%c%c", promoChar ? '/' : 0, ToUpper(promoChar));
1560 snprintf(out, MOVE_LEN, "O-O-O%c%c", promoChar ? '/' : 0, ToUpper(promoChar));
1562 /* This notation is always unambiguous, unless there are
1563 kings on both the d and e files, with "wild castling"
1564 possible for the king on the d file and normal castling
1565 possible for the other. ICS rules for wild 9
1566 effectively make castling illegal for either king in
1567 this situation. So I am not going to worry about it;
1568 I'll just generate an ambiguous O-O in this case.
1570 return LegalityTest(board, flags, rf, ff, rt, ft, promoChar);
1573 /* else fall through */
1578 cl.rt = rFilter = rt; // [HGM] speed: filter on to-square
1579 cl.ft = fFilter = ft;
1581 cl.kind = IllegalMove;
1582 cl.rank = cl.file = cl.either = 0;
1583 c = PieceToChar(piece) ;
1584 GenLegal(board, flags, CoordsToAlgebraicCallback, (VOIDSTAR) &cl, c!='~' ? piece : (DEMOTED piece)); // [HGM] speed
1586 if (cl.kind == IllegalMove && !(flags&F_IGNORE_CHECK)) {
1587 /* Generate pretty moves for moving into check, but
1588 still return IllegalMove.
1590 GenLegal(board, flags|F_IGNORE_CHECK, CoordsToAlgebraicCallback, (VOIDSTAR) &cl, c!='~' ? piece : (DEMOTED piece));
1591 if (cl.kind == IllegalMove) break;
1592 cl.kind = IllegalMove;
1595 /* Style is "Nf3" or "Nxf7" if this is unambiguous,
1596 else "Ngf3" or "Ngxf7",
1597 else "N1f3" or "N5xf7",
1598 else "Ng1f3" or "Ng5xf7".
1600 if( c == '~' || c == '+') {
1601 /* [HGM] print nonexistent piece as its demoted version */
1602 piece = (ChessSquare) (DEMOTED piece);
1604 if(c=='+') *outp++ = c;
1605 *outp++ = ToUpper(PieceToChar(piece));
1607 if (cl.file || (cl.either && !cl.rank)) {
1613 else { *outp++ = (rf+ONE-'0')/10 + '0';*outp++ = (rf+ONE-'0')%10 + '0'; }
1616 if(board[rt][ft] != EmptySquare)
1622 else { *outp++ = (rt+ONE-'0')/10 + '0';*outp++ = (rt+ONE-'0')%10 + '0'; }
1623 if (gameInfo.variant == VariantShogi) {
1624 /* [HGM] in Shogi non-pawns can promote */
1625 *outp++ = promoChar; // Don't bother to correct move type, return value is never used!
1627 else if (gameInfo.variant != VariantSuper && promoChar &&
1628 (piece == WhiteLance || piece == BlackLance) ) { // Lance sometimes represents Pawn
1630 *outp++ = ToUpper(promoChar);
1632 else if (gameInfo.variant == VariantSChess && promoChar) { // and in S-Chess we have gating
1634 *outp++ = ToUpper(promoChar);
1640 /* Moving a nonexistent piece */
1644 /* Not a legal move, even ignoring check.
1645 If there was a piece on the from square,
1646 use style "Ng1g3" or "Ng1xe8";
1647 if there was a pawn or nothing (!),
1648 use style "g1g3" or "g1xe8". Use "x"
1649 if a piece was on the to square, even
1650 a piece of the same color.
1654 if (piece != EmptySquare && piece != WhitePawn && piece != BlackPawn) {
1656 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<=BOARD_RGHT; f++)
1657 c += (board[r][f] == piece); // count on-board pieces of given type
1658 *outp++ = ToUpper(PieceToChar(piece));
1660 if(c != 1) { // [HGM] but if there is only one piece of the mentioned type, no from-square, thank you!
1664 else { *outp++ = (rf+ONE-'0')/10 + '0';*outp++ = (rf+ONE-'0')%10 + '0'; }
1666 if (board[rt][ft] != EmptySquare) *outp++ = 'x';
1670 else { *outp++ = (rt+ONE-'0')/10 + '0';*outp++ = (rt+ONE-'0')%10 + '0'; }
1671 /* Use promotion suffix style "=Q" */
1672 if (promoChar != NULLCHAR && promoChar != 'x') {
1674 *outp++ = ToUpper(promoChar);
1681 // [HGM] XQ: the following code serves to detect perpetual chasing (Asian rules)
1690 // I guess the following variables logically belong in the closure too, but I was too lazy and used globals
1692 int preyStackPointer, chaseStackPointer;
1695 unsigned char rf, ff, rt, ft;
1699 unsigned char rank, file;
1705 // there are three new callbacks for use with GenLegal: for adding captures, deleting them, and finding a recapture
1707 extern void AtacksCallback P((Board board, int flags, ChessMove kind,
1708 int rf, int ff, int rt, int ft,
1712 AttacksCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1713 { // For adding captures that can lead to chase indictment to the chaseStack
1714 if(board[rt][ft] == EmptySquare) return; // non-capture
1715 if(board[rt][ft] == WhitePawn && rt < BOARD_HEIGHT/2) return; // Pawn before river can be chased
1716 if(board[rt][ft] == BlackPawn && rt >= BOARD_HEIGHT/2) return; // Pawn before river can be chased
1717 if(board[rf][ff] == WhitePawn || board[rf][ff] == BlackPawn) return; // Pawns are allowed to chase
1718 if(board[rf][ff] == WhiteWazir || board[rf][ff] == BlackWazir) return; // King is allowed to chase
1719 // move cannot be excluded from being a chase trivially (based on attacker and victim); save it on chaseStack
1720 chaseStack[chaseStackPointer].rf = rf;
1721 chaseStack[chaseStackPointer].ff = ff;
1722 chaseStack[chaseStackPointer].rt = rt;
1723 chaseStack[chaseStackPointer].ft = ft;
1724 chaseStackPointer++;
1727 extern void ExistingAtacksCallback P((Board board, int flags, ChessMove kind,
1728 int rf, int ff, int rt, int ft,
1732 ExistingAttacksCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1733 { // for removing pre-exsting captures from the chaseStack, to be left with newly created ones
1735 register ChaseClosure *cl = (ChaseClosure *) closure; //closure tells us the move played in the repeat loop
1737 if(board[rt][ft] == EmptySquare) return; // no capture
1738 if(rf == cl->rf && ff == cl->ff) { // attacks with same piece from new position are not considered new
1739 rf = cl->rt; ff = cl->ft; // doctor their fromSquare so they will be recognized in chaseStack
1741 // search move in chaseStack, and delete it if it occurred there (as we know now it is not a new capture)
1742 for(i=0; i<chaseStackPointer; i++) {
1743 if(chaseStack[i].rf == rf && chaseStack[i].ff == ff &&
1744 chaseStack[i].rt == rt && chaseStack[i].ft == ft ) {
1745 // move found on chaseStack, delete it by overwriting with move popped from top of chaseStack
1746 chaseStack[i] = chaseStack[--chaseStackPointer];
1752 extern void ProtectedCallback P((Board board, int flags, ChessMove kind,
1753 int rf, int ff, int rt, int ft,
1757 ProtectedCallback (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
1758 { // for determining if a piece (given through the closure) is protected
1759 register ChaseClosure *cl = (ChaseClosure *) closure; // closure tells us where to recapture
1761 if(rt == cl->rt && ft == cl->ft) cl->recaptures++; // count legal recaptures to this square
1762 if(appData.debugMode && board[rt][ft] != EmptySquare)
1763 fprintf(debugFP, "try %c%c%c%c=%d\n", ff+AAA, rf+ONE,ft+AAA, rt+ONE, cl->recaptures);
1766 extern char moveList[MAX_MOVES][MOVE_LEN];
1769 PerpetualChase (int first, int last)
1770 { // this routine detects if the side to move in the 'first' position is perpetually chasing (when not checking)
1773 ChessSquare captured;
1775 preyStackPointer = 0; // clear stack of chased pieces
1776 for(i=first; i<last; i+=2) { // for all positions with same side to move
1777 if(appData.debugMode) fprintf(debugFP, "judge position %i\n", i);
1778 chaseStackPointer = 0; // clear stack that is going to hold possible chases
1779 // determine all captures possible after the move, and put them on chaseStack
1780 GenLegal(boards[i+1], PosFlags(i), AttacksCallback, &cl, EmptySquare);
1781 if(appData.debugMode) { int n;
1782 for(n=0; n<chaseStackPointer; n++)
1783 fprintf(debugFP, "%c%c%c%c ", chaseStack[n].ff+AAA, chaseStack[n].rf+ONE,
1784 chaseStack[n].ft+AAA, chaseStack[n].rt+ONE);
1785 fprintf(debugFP, ": all capts\n");
1787 // determine all captures possible before the move, and delete them from chaseStack
1788 cl.rf = moveList[i][1]-ONE; // prepare closure to pass move that led from i to i+1
1789 cl.ff = moveList[i][0]-AAA+BOARD_LEFT;
1790 cl.rt = moveList[i][3]-ONE;
1791 cl.ft = moveList[i][2]-AAA+BOARD_LEFT;
1792 CopyBoard(xqCheckers, nullBoard); xqCheckers[EP_STATUS] = 1; // giant kludge to make GenLegal ignore pre-existing checks
1793 GenLegal(boards[i], PosFlags(i), ExistingAttacksCallback, &cl, EmptySquare);
1794 xqCheckers[EP_STATUS] = 0; // disable the generation of quasi-legal moves again
1795 if(appData.debugMode) { int n;
1796 for(n=0; n<chaseStackPointer; n++)
1797 fprintf(debugFP, "%c%c%c%c ", chaseStack[n].ff+AAA, chaseStack[n].rf+ONE,
1798 chaseStack[n].ft+AAA, chaseStack[n].rt+ONE);
1799 fprintf(debugFP, ": new capts after %c%c%c%c\n", cl.ff+AAA, cl.rf+ONE, cl.ft+AAA, cl.rt+ONE);
1801 // chaseSack now contains all captures made possible by the move
1802 for(j=0; j<chaseStackPointer; j++) { // run through chaseStack to identify true chases
1803 int attacker = (int)boards[i+1][chaseStack[j].rf][chaseStack[j].ff];
1804 int victim = (int)boards[i+1][chaseStack[j].rt][chaseStack[j].ft];
1806 if(attacker >= (int) BlackPawn) attacker = BLACK_TO_WHITE attacker; // convert to white, as piecee type
1807 if(victim >= (int) BlackPawn) victim = BLACK_TO_WHITE victim;
1809 if((attacker == WhiteKnight || attacker == WhiteCannon) && victim == WhiteRook)
1810 continue; // C or H attack on R is always chase; leave on chaseStack
1812 if(attacker == victim) {
1813 if(LegalityTest(boards[i+1], PosFlags(i+1), chaseStack[j].rt,
1814 chaseStack[j].ft, chaseStack[j].rf, chaseStack[j].ff, NULLCHAR) == NormalMove) {
1815 // we can capture back with equal piece, so this is no chase but a sacrifice
1816 chaseStack[j] = chaseStack[--chaseStackPointer]; // delete the capture from the chaseStack
1817 j--; /* ! */ continue;
1822 // the attack is on a lower piece, or on a pinned or blocked equal one
1823 CopyBoard(xqCheckers, nullBoard); xqCheckers[EP_STATUS] = 1;
1824 CheckTest(boards[i+1], PosFlags(i+1), -1, -1, -1, -1, FALSE); // if we deliver check with our move, the checkers get marked
1825 // test if the victim is protected by a true protector. First make the capture.
1826 captured = boards[i+1][chaseStack[j].rt][chaseStack[j].ft];
1827 boards[i+1][chaseStack[j].rt][chaseStack[j].ft] = boards[i+1][chaseStack[j].rf][chaseStack[j].ff];
1828 boards[i+1][chaseStack[j].rf][chaseStack[j].ff] = EmptySquare;
1829 // Then test if the opponent can recapture
1830 cl.recaptures = 0; // prepare closure to pass recapture square and count moves to it
1831 cl.rt = chaseStack[j].rt;
1832 cl.ft = chaseStack[j].ft;
1833 if(appData.debugMode) {
1834 fprintf(debugFP, "test if we can recapture %c%c\n", cl.ft+AAA, cl.rt+ONE);
1836 xqCheckers[EP_STATUS] = 2; // causes GenLegal to ignore the checks we delivered with the move, in real life evaded before we captured
1837 GenLegal(boards[i+1], PosFlags(i+1), ProtectedCallback, &cl, EmptySquare); // try all moves
1838 xqCheckers[EP_STATUS] = 0; // disable quasi-legal moves again
1839 // unmake the capture
1840 boards[i+1][chaseStack[j].rf][chaseStack[j].ff] = boards[i+1][chaseStack[j].rt][chaseStack[j].ft];
1841 boards[i+1][chaseStack[j].rt][chaseStack[j].ft] = captured;
1842 // if a recapture was found, piece is protected, and we are not chasing it.
1843 if(cl.recaptures) { // attacked piece was defended by true protector, no chase
1844 chaseStack[j] = chaseStack[--chaseStackPointer]; // so delete from chaseStack
1848 // chaseStack now contains all moves that chased
1849 if(appData.debugMode) { int n;
1850 for(n=0; n<chaseStackPointer; n++)
1851 fprintf(debugFP, "%c%c%c%c ", chaseStack[n].ff+AAA, chaseStack[n].rf+ONE,
1852 chaseStack[n].ft+AAA, chaseStack[n].rt+ONE);
1853 fprintf(debugFP, ": chases\n");
1855 if(i == first) { // copy all people chased by first move of repeat cycle to preyStack
1856 for(j=0; j<chaseStackPointer; j++) {
1857 preyStack[j].rank = chaseStack[j].rt;
1858 preyStack[j].file = chaseStack[j].ft;
1860 preyStackPointer = chaseStackPointer;
1863 for(j=0; j<chaseStackPointer; j++) {
1864 for(k=0; k<preyStackPointer; k++) {
1865 // search the victim of each chase move on the preyStack (first occurrence)
1866 if(chaseStack[j].ft == preyStack[k].file && chaseStack[j].rt == preyStack[k].rank ) {
1867 if(k < tail) break; // piece was already identified as still being chased
1868 preyStack[preyStackPointer] = preyStack[tail]; // move chased piece to bottom part of preyStack
1869 preyStack[tail] = preyStack[k]; // by swapping
1870 preyStack[k] = preyStack[preyStackPointer];
1876 preyStackPointer = tail; // keep bottom part of preyStack, popping pieces unchased on move i.
1877 if(appData.debugMode) { int n;
1878 for(n=0; n<preyStackPointer; n++)
1879 fprintf(debugFP, "%c%c ", preyStack[n].file+AAA, preyStack[n].rank+ONE);
1880 fprintf(debugFP, "always chased upto ply %d\n", i);
1882 // now adjust the location of the chased pieces according to opponent move
1883 for(j=0; j<preyStackPointer; j++) {
1884 if(preyStack[j].rank == moveList[i+1][1]-ONE &&
1885 preyStack[j].file == moveList[i+1][0]-AAA+BOARD_LEFT) {
1886 preyStack[j].rank = moveList[i+1][3]-ONE;
1887 preyStack[j].file = moveList[i+1][2]-AAA+BOARD_LEFT;
1892 return preyStackPointer ? 256*(preyStack[preyStackPointer].file - BOARD_LEFT + AAA) + (preyStack[preyStackPointer].rank + ONE)
1893 : 0; // if any piece was left on preyStack, it has been perpetually chased,and we return the