2 * backend.c -- Common back end for X and Windows NT versions of
4 * Copyright 1991 by Digital Equipment Corporation, Maynard,
7 * Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006,
8 * 2007, 2008, 2009 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. */
54 /* [AS] Also useful here for debugging */
58 #define DoSleep( n ) if( (n) != 0 ) Sleep( (n) );
62 #define DoSleep( n ) if( (n) >= 0) sleep(n)
72 #include <sys/types.h>
80 #else /* not STDC_HEADERS */
83 # else /* not HAVE_STRING_H */
85 # endif /* not HAVE_STRING_H */
86 #endif /* not STDC_HEADERS */
89 # include <sys/fcntl.h>
90 #else /* not HAVE_SYS_FCNTL_H */
93 # endif /* HAVE_FCNTL_H */
94 #endif /* not HAVE_SYS_FCNTL_H */
96 #if TIME_WITH_SYS_TIME
97 # include <sys/time.h>
101 # include <sys/time.h>
107 #if defined(_amigados) && !defined(__GNUC__)
112 extern int gettimeofday(struct timeval *, struct timezone *);
120 #include "frontend.h"
127 #include "backendz.h"
131 # define _(s) gettext (s)
132 # define N_(s) gettext_noop (s)
139 /* A point in time */
141 long sec; /* Assuming this is >= 32 bits */
142 int ms; /* Assuming this is >= 16 bits */
145 int establish P((void));
146 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
147 char *buf, int count, int error));
148 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
149 char *buf, int count, int error));
150 void SendToICS P((char *s));
151 void SendToICSDelayed P((char *s, long msdelay));
152 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY,
154 void InitPosition P((int redraw));
155 void HandleMachineMove P((char *message, ChessProgramState *cps));
156 int AutoPlayOneMove P((void));
157 int LoadGameOneMove P((ChessMove readAhead));
158 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
159 int LoadPositionFromFile P((char *filename, int n, char *title));
160 int SavePositionToFile P((char *filename));
161 void ApplyMove P((int fromX, int fromY, int toX, int toY, int promoChar,
162 Board board, char *castle, char *ep));
163 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
164 void ShowMove P((int fromX, int fromY, int toX, int toY));
165 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
166 /*char*/int promoChar));
167 void BackwardInner P((int target));
168 void ForwardInner P((int target));
169 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
170 void EditPositionDone P((void));
171 void PrintOpponents P((FILE *fp));
172 void PrintPosition P((FILE *fp, int move));
173 void StartChessProgram P((ChessProgramState *cps));
174 void SendToProgram P((char *message, ChessProgramState *cps));
175 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
176 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
177 char *buf, int count, int error));
178 void SendTimeControl P((ChessProgramState *cps,
179 int mps, long tc, int inc, int sd, int st));
180 char *TimeControlTagValue P((void));
181 void Attention P((ChessProgramState *cps));
182 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
183 void ResurrectChessProgram P((void));
184 void DisplayComment P((int moveNumber, char *text));
185 void DisplayMove P((int moveNumber));
186 void DisplayAnalysis P((void));
188 void ParseGameHistory P((char *game));
189 void ParseBoard12 P((char *string));
190 void StartClocks P((void));
191 void SwitchClocks P((void));
192 void StopClocks P((void));
193 void ResetClocks P((void));
194 char *PGNDate P((void));
195 void SetGameInfo P((void));
196 Boolean ParseFEN P((Board board, int *blackPlaysFirst, char *fen));
197 int RegisterMove P((void));
198 void MakeRegisteredMove P((void));
199 void TruncateGame P((void));
200 int looking_at P((char *, int *, char *));
201 void CopyPlayerNameIntoFileName P((char **, char *));
202 char *SavePart P((char *));
203 int SaveGameOldStyle P((FILE *));
204 int SaveGamePGN P((FILE *));
205 void GetTimeMark P((TimeMark *));
206 long SubtractTimeMarks P((TimeMark *, TimeMark *));
207 int CheckFlags P((void));
208 long NextTickLength P((long));
209 void CheckTimeControl P((void));
210 void show_bytes P((FILE *, char *, int));
211 int string_to_rating P((char *str));
212 void ParseFeatures P((char* args, ChessProgramState *cps));
213 void InitBackEnd3 P((void));
214 void FeatureDone P((ChessProgramState* cps, int val));
215 void InitChessProgram P((ChessProgramState *cps, int setup));
216 void OutputKibitz(int window, char *text);
217 int PerpetualChase(int first, int last);
218 int EngineOutputIsUp();
219 void InitDrawingSizes(int x, int y);
222 extern void ConsoleCreate();
225 ChessProgramState *WhitePlayer();
226 void InsertIntoMemo P((int which, char *text)); // [HGM] kibitz: in engineo.c
227 int VerifyDisplayMode P(());
229 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
230 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
231 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
232 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
233 extern char installDir[MSG_SIZ];
235 extern int tinyLayout, smallLayout;
236 ChessProgramStats programStats;
237 static int exiting = 0; /* [HGM] moved to top */
238 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
239 int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
240 char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
241 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
242 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
243 int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
244 int opponentKibitzes;
245 int lastSavedGame; /* [HGM] save: ID of game */
247 /* States for ics_getting_history */
249 #define H_REQUESTED 1
250 #define H_GOT_REQ_HEADER 2
251 #define H_GOT_UNREQ_HEADER 3
252 #define H_GETTING_MOVES 4
253 #define H_GOT_UNWANTED_HEADER 5
255 /* whosays values for GameEnds */
264 /* Maximum number of games in a cmail message */
265 #define CMAIL_MAX_GAMES 20
267 /* Different types of move when calling RegisterMove */
269 #define CMAIL_RESIGN 1
271 #define CMAIL_ACCEPT 3
273 /* Different types of result to remember for each game */
274 #define CMAIL_NOT_RESULT 0
275 #define CMAIL_OLD_RESULT 1
276 #define CMAIL_NEW_RESULT 2
278 /* Telnet protocol constants */
289 static char * safeStrCpy( char * dst, const char * src, size_t count )
291 assert( dst != NULL );
292 assert( src != NULL );
295 strncpy( dst, src, count );
296 dst[ count-1 ] = '\0';
301 //[HGM] for future use? Conditioned out for now to suppress warning.
302 static char * safeStrCat( char * dst, const char * src, size_t count )
306 assert( dst != NULL );
307 assert( src != NULL );
310 dst_len = strlen(dst);
312 assert( count > dst_len ); /* Buffer size must be greater than current length */
314 safeStrCpy( dst + dst_len, src, count - dst_len );
320 /* Some compiler can't cast u64 to double
321 * This function do the job for us:
323 * We use the highest bit for cast, this only
324 * works if the highest bit is not
325 * in use (This should not happen)
327 * We used this for all compiler
330 u64ToDouble(u64 value)
333 u64 tmp = value & u64Const(0x7fffffffffffffff);
334 r = (double)(s64)tmp;
335 if (value & u64Const(0x8000000000000000))
336 r += 9.2233720368547758080e18; /* 2^63 */
340 /* Fake up flags for now, as we aren't keeping track of castling
341 availability yet. [HGM] Change of logic: the flag now only
342 indicates the type of castlings allowed by the rule of the game.
343 The actual rights themselves are maintained in the array
344 castlingRights, as part of the game history, and are not probed
350 int flags = F_ALL_CASTLE_OK;
351 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
352 switch (gameInfo.variant) {
354 flags &= ~F_ALL_CASTLE_OK;
355 case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
356 flags |= F_IGNORE_CHECK;
358 flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
361 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
363 case VariantKriegspiel:
364 flags |= F_KRIEGSPIEL_CAPTURE;
366 case VariantCapaRandom:
367 case VariantFischeRandom:
368 flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
369 case VariantNoCastle:
370 case VariantShatranj:
372 flags &= ~F_ALL_CASTLE_OK;
380 FILE *gameFileFP, *debugFP;
383 [AS] Note: sometimes, the sscanf() function is used to parse the input
384 into a fixed-size buffer. Because of this, we must be prepared to
385 receive strings as long as the size of the input buffer, which is currently
386 set to 4K for Windows and 8K for the rest.
387 So, we must either allocate sufficiently large buffers here, or
388 reduce the size of the input buffer in the input reading part.
391 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
392 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
393 char thinkOutput1[MSG_SIZ*10];
395 ChessProgramState first, second;
397 /* premove variables */
400 int premoveFromX = 0;
401 int premoveFromY = 0;
402 int premovePromoChar = 0;
404 Boolean alarmSounded;
405 /* end premove variables */
407 char *ics_prefix = "$";
408 int ics_type = ICS_GENERIC;
410 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
411 int pauseExamForwardMostMove = 0;
412 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
413 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
414 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
415 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
416 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
417 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
418 int whiteFlag = FALSE, blackFlag = FALSE;
419 int userOfferedDraw = FALSE;
420 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
421 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
422 int cmailMoveType[CMAIL_MAX_GAMES];
423 long ics_clock_paused = 0;
424 ProcRef icsPR = NoProc, cmailPR = NoProc;
425 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
426 GameMode gameMode = BeginningOfGame;
427 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
428 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
429 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
430 int hiddenThinkOutputState = 0; /* [AS] */
431 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
432 int adjudicateLossPlies = 6;
433 char white_holding[64], black_holding[64];
434 TimeMark lastNodeCountTime;
435 long lastNodeCount=0;
436 int have_sent_ICS_logon = 0;
438 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement;
439 long timeControl_2; /* [AS] Allow separate time controls */
440 char *fullTimeControlString = NULL; /* [HGM] secondary TC: merge of MPS, TC and inc */
441 long timeRemaining[2][MAX_MOVES];
443 TimeMark programStartTime;
444 char ics_handle[MSG_SIZ];
445 int have_set_title = 0;
447 /* animateTraining preserves the state of appData.animate
448 * when Training mode is activated. This allows the
449 * response to be animated when appData.animate == TRUE and
450 * appData.animateDragging == TRUE.
452 Boolean animateTraining;
458 Board boards[MAX_MOVES];
459 /* [HGM] Following 7 needed for accurate legality tests: */
460 char epStatus[MAX_MOVES];
461 char castlingRights[MAX_MOVES][BOARD_SIZE]; // stores files for pieces with castling rights or -1
462 char castlingRank[BOARD_SIZE]; // and corresponding ranks
463 char initialRights[BOARD_SIZE], FENcastlingRights[BOARD_SIZE], fileRights[BOARD_SIZE];
464 int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
465 int initialRulePlies, FENrulePlies;
467 FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
471 ChessSquare FIDEArray[2][BOARD_SIZE] = {
472 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
473 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
474 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
475 BlackKing, BlackBishop, BlackKnight, BlackRook }
478 ChessSquare twoKingsArray[2][BOARD_SIZE] = {
479 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
480 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
481 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
482 BlackKing, BlackKing, BlackKnight, BlackRook }
485 ChessSquare KnightmateArray[2][BOARD_SIZE] = {
486 { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
487 WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
488 { BlackRook, BlackMan, BlackBishop, BlackQueen,
489 BlackUnicorn, BlackBishop, BlackMan, BlackRook }
492 ChessSquare fairyArray[2][BOARD_SIZE] = { /* [HGM] Queen side differs from King side */
493 { WhiteCannon, WhiteNightrider, WhiteAlfil, WhiteQueen,
494 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
495 { BlackCannon, BlackNightrider, BlackAlfil, BlackQueen,
496 BlackKing, BlackBishop, BlackKnight, BlackRook }
499 ChessSquare ShatranjArray[2][BOARD_SIZE] = { /* [HGM] (movGen knows about Shatranj Q and P) */
500 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
501 WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
502 { BlackRook, BlackKnight, BlackAlfil, BlackKing,
503 BlackFerz, BlackAlfil, BlackKnight, BlackRook }
508 ChessSquare ShogiArray[2][BOARD_SIZE] = {
509 { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
510 WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
511 { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
512 BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
515 ChessSquare XiangqiArray[2][BOARD_SIZE] = {
516 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
517 WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
518 { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
519 BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
522 ChessSquare CapablancaArray[2][BOARD_SIZE] = {
523 { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
524 WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
525 { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
526 BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
529 ChessSquare GreatArray[2][BOARD_SIZE] = {
530 { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
531 WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
532 { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
533 BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
536 ChessSquare JanusArray[2][BOARD_SIZE] = {
537 { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
538 WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
539 { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
540 BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
544 ChessSquare GothicArray[2][BOARD_SIZE] = {
545 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
546 WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
547 { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
548 BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
551 #define GothicArray CapablancaArray
555 ChessSquare FalconArray[2][BOARD_SIZE] = {
556 { WhiteRook, WhiteKnight, WhiteBishop, WhiteLance, WhiteQueen,
557 WhiteKing, WhiteLance, WhiteBishop, WhiteKnight, WhiteRook },
558 { BlackRook, BlackKnight, BlackBishop, BlackLance, BlackQueen,
559 BlackKing, BlackLance, BlackBishop, BlackKnight, BlackRook }
562 #define FalconArray CapablancaArray
565 #else // !(BOARD_SIZE>=10)
566 #define XiangqiPosition FIDEArray
567 #define CapablancaArray FIDEArray
568 #define GothicArray FIDEArray
569 #define GreatArray FIDEArray
570 #endif // !(BOARD_SIZE>=10)
573 ChessSquare CourierArray[2][BOARD_SIZE] = {
574 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
575 WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
576 { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
577 BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
579 #else // !(BOARD_SIZE>=12)
580 #define CourierArray CapablancaArray
581 #endif // !(BOARD_SIZE>=12)
584 Board initialPosition;
587 /* Convert str to a rating. Checks for special cases of "----",
589 "++++", etc. Also strips ()'s */
591 string_to_rating(str)
594 while(*str && !isdigit(*str)) ++str;
596 return 0; /* One of the special "no rating" cases */
604 /* Init programStats */
605 programStats.movelist[0] = 0;
606 programStats.depth = 0;
607 programStats.nr_moves = 0;
608 programStats.moves_left = 0;
609 programStats.nodes = 0;
610 programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
611 programStats.score = 0;
612 programStats.got_only_move = 0;
613 programStats.got_fail = 0;
614 programStats.line_is_book = 0;
620 int matched, min, sec;
622 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
624 GetTimeMark(&programStartTime);
625 srand(programStartTime.ms); // [HGM] book: makes sure random is unpredictabe to msec level
628 programStats.ok_to_send = 1;
629 programStats.seen_stat = 0;
632 * Initialize game list
638 * Internet chess server status
640 if (appData.icsActive) {
641 appData.matchMode = FALSE;
642 appData.matchGames = 0;
644 appData.noChessProgram = !appData.zippyPlay;
646 appData.zippyPlay = FALSE;
647 appData.zippyTalk = FALSE;
648 appData.noChessProgram = TRUE;
650 if (*appData.icsHelper != NULLCHAR) {
651 appData.useTelnet = TRUE;
652 appData.telnetProgram = appData.icsHelper;
655 appData.zippyTalk = appData.zippyPlay = FALSE;
658 /* [AS] Initialize pv info list [HGM] and game state */
662 for( i=0; i<MAX_MOVES; i++ ) {
663 pvInfoList[i].depth = -1;
665 for( j=0; j<BOARD_SIZE; j++ ) castlingRights[i][j] = -1;
670 * Parse timeControl resource
672 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
673 appData.movesPerSession)) {
675 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
676 DisplayFatalError(buf, 0, 2);
680 * Parse searchTime resource
682 if (*appData.searchTime != NULLCHAR) {
683 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
685 searchTime = min * 60;
686 } else if (matched == 2) {
687 searchTime = min * 60 + sec;
690 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
691 DisplayFatalError(buf, 0, 2);
695 /* [AS] Adjudication threshold */
696 adjudicateLossThreshold = appData.adjudicateLossThreshold;
698 first.which = "first";
699 second.which = "second";
700 first.maybeThinking = second.maybeThinking = FALSE;
701 first.pr = second.pr = NoProc;
702 first.isr = second.isr = NULL;
703 first.sendTime = second.sendTime = 2;
704 first.sendDrawOffers = 1;
705 if (appData.firstPlaysBlack) {
706 first.twoMachinesColor = "black\n";
707 second.twoMachinesColor = "white\n";
709 first.twoMachinesColor = "white\n";
710 second.twoMachinesColor = "black\n";
712 first.program = appData.firstChessProgram;
713 second.program = appData.secondChessProgram;
714 first.host = appData.firstHost;
715 second.host = appData.secondHost;
716 first.dir = appData.firstDirectory;
717 second.dir = appData.secondDirectory;
718 first.other = &second;
719 second.other = &first;
720 first.initString = appData.initString;
721 second.initString = appData.secondInitString;
722 first.computerString = appData.firstComputerString;
723 second.computerString = appData.secondComputerString;
724 first.useSigint = second.useSigint = TRUE;
725 first.useSigterm = second.useSigterm = TRUE;
726 first.reuse = appData.reuseFirst;
727 second.reuse = appData.reuseSecond;
728 first.nps = appData.firstNPS; // [HGM] nps: copy nodes per second
729 second.nps = appData.secondNPS;
730 first.useSetboard = second.useSetboard = FALSE;
731 first.useSAN = second.useSAN = FALSE;
732 first.usePing = second.usePing = FALSE;
733 first.lastPing = second.lastPing = 0;
734 first.lastPong = second.lastPong = 0;
735 first.usePlayother = second.usePlayother = FALSE;
736 first.useColors = second.useColors = TRUE;
737 first.useUsermove = second.useUsermove = FALSE;
738 first.sendICS = second.sendICS = FALSE;
739 first.sendName = second.sendName = appData.icsActive;
740 first.sdKludge = second.sdKludge = FALSE;
741 first.stKludge = second.stKludge = FALSE;
742 TidyProgramName(first.program, first.host, first.tidy);
743 TidyProgramName(second.program, second.host, second.tidy);
744 first.matchWins = second.matchWins = 0;
745 strcpy(first.variants, appData.variant);
746 strcpy(second.variants, appData.variant);
747 first.analysisSupport = second.analysisSupport = 2; /* detect */
748 first.analyzing = second.analyzing = FALSE;
749 first.initDone = second.initDone = FALSE;
751 /* New features added by Tord: */
752 first.useFEN960 = FALSE; second.useFEN960 = FALSE;
753 first.useOOCastle = TRUE; second.useOOCastle = TRUE;
754 /* End of new features added by Tord. */
755 first.fenOverride = appData.fenOverride1;
756 second.fenOverride = appData.fenOverride2;
758 /* [HGM] time odds: set factor for each machine */
759 first.timeOdds = appData.firstTimeOdds;
760 second.timeOdds = appData.secondTimeOdds;
762 if(appData.timeOddsMode) {
763 norm = first.timeOdds;
764 if(norm > second.timeOdds) norm = second.timeOdds;
766 first.timeOdds /= norm;
767 second.timeOdds /= norm;
770 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
771 first.accumulateTC = appData.firstAccumulateTC;
772 second.accumulateTC = appData.secondAccumulateTC;
773 first.maxNrOfSessions = second.maxNrOfSessions = 1;
776 first.debug = second.debug = FALSE;
777 first.supportsNPS = second.supportsNPS = UNKNOWN;
780 first.optionSettings = appData.firstOptions;
781 second.optionSettings = appData.secondOptions;
783 first.scoreIsAbsolute = appData.firstScoreIsAbsolute; /* [AS] */
784 second.scoreIsAbsolute = appData.secondScoreIsAbsolute; /* [AS] */
785 first.isUCI = appData.firstIsUCI; /* [AS] */
786 second.isUCI = appData.secondIsUCI; /* [AS] */
787 first.hasOwnBookUCI = appData.firstHasOwnBookUCI; /* [AS] */
788 second.hasOwnBookUCI = appData.secondHasOwnBookUCI; /* [AS] */
790 if (appData.firstProtocolVersion > PROTOVER ||
791 appData.firstProtocolVersion < 1) {
793 sprintf(buf, _("protocol version %d not supported"),
794 appData.firstProtocolVersion);
795 DisplayFatalError(buf, 0, 2);
797 first.protocolVersion = appData.firstProtocolVersion;
800 if (appData.secondProtocolVersion > PROTOVER ||
801 appData.secondProtocolVersion < 1) {
803 sprintf(buf, _("protocol version %d not supported"),
804 appData.secondProtocolVersion);
805 DisplayFatalError(buf, 0, 2);
807 second.protocolVersion = appData.secondProtocolVersion;
810 if (appData.icsActive) {
811 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
812 } else if (*appData.searchTime != NULLCHAR || appData.noChessProgram) {
813 appData.clockMode = FALSE;
814 first.sendTime = second.sendTime = 0;
818 /* Override some settings from environment variables, for backward
819 compatibility. Unfortunately it's not feasible to have the env
820 vars just set defaults, at least in xboard. Ugh.
822 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
827 if (appData.noChessProgram) {
828 programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
829 sprintf(programVersion, "%s", PACKAGE_STRING);
834 while (*q != ' ' && *q != NULLCHAR) q++;
836 while (p > first.program && *(p-1) != '/' && *(p-1) != '\\') p--; /* [HGM] backslash added */
837 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING + (q - p));
838 sprintf(programVersion, "%s + ", PACKAGE_STRING);
839 strncat(programVersion, p, q - p);
841 /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
842 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
843 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
847 if (!appData.icsActive) {
849 /* Check for variants that are supported only in ICS mode,
850 or not at all. Some that are accepted here nevertheless
851 have bugs; see comments below.
853 VariantClass variant = StringToVariant(appData.variant);
855 case VariantBughouse: /* need four players and two boards */
856 case VariantKriegspiel: /* need to hide pieces and move details */
857 /* case VariantFischeRandom: (Fabien: moved below) */
858 sprintf(buf, _("Variant %s supported only in ICS mode"), appData.variant);
859 DisplayFatalError(buf, 0, 2);
863 case VariantLoadable:
873 sprintf(buf, _("Unknown variant name %s"), appData.variant);
874 DisplayFatalError(buf, 0, 2);
877 case VariantXiangqi: /* [HGM] repetition rules not implemented */
878 case VariantFairy: /* [HGM] TestLegality definitely off! */
879 case VariantGothic: /* [HGM] should work */
880 case VariantCapablanca: /* [HGM] should work */
881 case VariantCourier: /* [HGM] initial forced moves not implemented */
882 case VariantShogi: /* [HGM] drops not tested for legality */
883 case VariantKnightmate: /* [HGM] should work */
884 case VariantCylinder: /* [HGM] untested */
885 case VariantFalcon: /* [HGM] untested */
886 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
887 offboard interposition not understood */
888 case VariantNormal: /* definitely works! */
889 case VariantWildCastle: /* pieces not automatically shuffled */
890 case VariantNoCastle: /* pieces not automatically shuffled */
891 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
892 case VariantLosers: /* should work except for win condition,
893 and doesn't know captures are mandatory */
894 case VariantSuicide: /* should work except for win condition,
895 and doesn't know captures are mandatory */
896 case VariantGiveaway: /* should work except for win condition,
897 and doesn't know captures are mandatory */
898 case VariantTwoKings: /* should work */
899 case VariantAtomic: /* should work except for win condition */
900 case Variant3Check: /* should work except for win condition */
901 case VariantShatranj: /* should work except for all win conditions */
902 case VariantBerolina: /* might work if TestLegality is off */
903 case VariantCapaRandom: /* should work */
904 case VariantJanus: /* should work */
905 case VariantSuper: /* experimental */
906 case VariantGreat: /* experimental, requires legality testing to be off */
911 InitEngineUCI( installDir, &first ); // [HGM] moved here from winboard.c, to make available in xboard
912 InitEngineUCI( installDir, &second );
915 int NextIntegerFromString( char ** str, long * value )
920 while( *s == ' ' || *s == '\t' ) {
926 if( *s >= '0' && *s <= '9' ) {
927 while( *s >= '0' && *s <= '9' ) {
928 *value = *value * 10 + (*s - '0');
940 int NextTimeControlFromString( char ** str, long * value )
943 int result = NextIntegerFromString( str, &temp );
946 *value = temp * 60; /* Minutes */
949 result = NextIntegerFromString( str, &temp );
950 *value += temp; /* Seconds */
957 int NextSessionFromString( char ** str, int *moves, long * tc, long *inc)
958 { /* [HGM] routine added to read '+moves/time' for secondary time control */
959 int result = -1; long temp, temp2;
961 if(**str != '+') return -1; // old params remain in force!
963 if( NextTimeControlFromString( str, &temp ) ) return -1;
966 /* time only: incremental or sudden-death time control */
967 if(**str == '+') { /* increment follows; read it */
969 if(result = NextIntegerFromString( str, &temp2)) return -1;
972 *moves = 0; *tc = temp * 1000;
974 } else if(temp % 60 != 0) return -1; /* moves was given as min:sec */
976 (*str)++; /* classical time control */
977 result = NextTimeControlFromString( str, &temp2);
986 int GetTimeQuota(int movenr)
987 { /* [HGM] get time to add from the multi-session time-control string */
988 int moves=1; /* kludge to force reading of first session */
989 long time, increment;
990 char *s = fullTimeControlString;
992 if(appData.debugMode) fprintf(debugFP, "TC string = '%s'\n", fullTimeControlString);
994 if(moves) NextSessionFromString(&s, &moves, &time, &increment);
995 if(appData.debugMode) fprintf(debugFP, "mps=%d tc=%d inc=%d\n", moves, (int) time, (int) increment);
996 if(movenr == -1) return time; /* last move before new session */
997 if(!moves) return increment; /* current session is incremental */
998 if(movenr >= 0) movenr -= moves; /* we already finished this session */
999 } while(movenr >= -1); /* try again for next session */
1001 return 0; // no new time quota on this move
1005 ParseTimeControl(tc, ti, mps)
1011 int matched, min, sec;
1013 matched = sscanf(tc, "%d:%d", &min, &sec);
1015 timeControl = min * 60 * 1000;
1016 } else if (matched == 2) {
1017 timeControl = (min * 60 + sec) * 1000;
1026 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1029 sprintf(buf, "+%d/%s+%d", mps, tc, ti);
1030 else sprintf(buf, "+%s+%d", tc, ti);
1033 sprintf(buf, "+%d/%s", mps, tc);
1034 else sprintf(buf, "+%s", tc);
1036 fullTimeControlString = StrSave(buf);
1038 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1043 /* Parse second time control */
1046 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1054 timeControl_2 = tc2 * 1000;
1064 timeControl = tc1 * 1000;
1068 timeIncrement = ti * 1000; /* convert to ms */
1069 movesPerSession = 0;
1072 movesPerSession = mps;
1080 if (appData.debugMode) {
1081 fprintf(debugFP, "%s\n", programVersion);
1084 if (appData.matchGames > 0) {
1085 appData.matchMode = TRUE;
1086 } else if (appData.matchMode) {
1087 appData.matchGames = 1;
1089 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1090 appData.matchGames = appData.sameColorGames;
1091 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1092 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1093 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1096 if (appData.noChessProgram || first.protocolVersion == 1) {
1099 /* kludge: allow timeout for initial "feature" commands */
1101 DisplayMessage("", _("Starting chess program"));
1102 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1107 InitBackEnd3 P((void))
1109 GameMode initialMode;
1113 InitChessProgram(&first, startedFromSetupPosition);
1116 if (appData.icsActive) {
1118 /* [DM] Make a console window if needed [HGM] merged ifs */
1123 if (*appData.icsCommPort != NULLCHAR) {
1124 sprintf(buf, _("Could not open comm port %s"),
1125 appData.icsCommPort);
1127 snprintf(buf, sizeof(buf), _("Could not connect to host %s, port %s"),
1128 appData.icsHost, appData.icsPort);
1130 DisplayFatalError(buf, err, 1);
1135 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1137 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1138 } else if (appData.noChessProgram) {
1144 if (*appData.cmailGameName != NULLCHAR) {
1146 OpenLoopback(&cmailPR);
1148 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1152 DisplayMessage("", "");
1153 if (StrCaseCmp(appData.initialMode, "") == 0) {
1154 initialMode = BeginningOfGame;
1155 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1156 initialMode = TwoMachinesPlay;
1157 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1158 initialMode = AnalyzeFile;
1159 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1160 initialMode = AnalyzeMode;
1161 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1162 initialMode = MachinePlaysWhite;
1163 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1164 initialMode = MachinePlaysBlack;
1165 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1166 initialMode = EditGame;
1167 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1168 initialMode = EditPosition;
1169 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1170 initialMode = Training;
1172 sprintf(buf, _("Unknown initialMode %s"), appData.initialMode);
1173 DisplayFatalError(buf, 0, 2);
1177 if (appData.matchMode) {
1178 /* Set up machine vs. machine match */
1179 if (appData.noChessProgram) {
1180 DisplayFatalError(_("Can't have a match with no chess programs"),
1186 if (*appData.loadGameFile != NULLCHAR) {
1187 int index = appData.loadGameIndex; // [HGM] autoinc
1188 if(index<0) lastIndex = index = 1;
1189 if (!LoadGameFromFile(appData.loadGameFile,
1191 appData.loadGameFile, FALSE)) {
1192 DisplayFatalError(_("Bad game file"), 0, 1);
1195 } else if (*appData.loadPositionFile != NULLCHAR) {
1196 int index = appData.loadPositionIndex; // [HGM] autoinc
1197 if(index<0) lastIndex = index = 1;
1198 if (!LoadPositionFromFile(appData.loadPositionFile,
1200 appData.loadPositionFile)) {
1201 DisplayFatalError(_("Bad position file"), 0, 1);
1206 } else if (*appData.cmailGameName != NULLCHAR) {
1207 /* Set up cmail mode */
1208 ReloadCmailMsgEvent(TRUE);
1210 /* Set up other modes */
1211 if (initialMode == AnalyzeFile) {
1212 if (*appData.loadGameFile == NULLCHAR) {
1213 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1217 if (*appData.loadGameFile != NULLCHAR) {
1218 (void) LoadGameFromFile(appData.loadGameFile,
1219 appData.loadGameIndex,
1220 appData.loadGameFile, TRUE);
1221 } else if (*appData.loadPositionFile != NULLCHAR) {
1222 (void) LoadPositionFromFile(appData.loadPositionFile,
1223 appData.loadPositionIndex,
1224 appData.loadPositionFile);
1225 /* [HGM] try to make self-starting even after FEN load */
1226 /* to allow automatic setup of fairy variants with wtm */
1227 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1228 gameMode = BeginningOfGame;
1229 setboardSpoiledMachineBlack = 1;
1231 /* [HGM] loadPos: make that every new game uses the setup */
1232 /* from file as long as we do not switch variant */
1233 if(!blackPlaysFirst) { int i;
1234 startedFromPositionFile = TRUE;
1235 CopyBoard(filePosition, boards[0]);
1236 for(i=0; i<BOARD_SIZE; i++) fileRights[i] = castlingRights[0][i];
1239 if (initialMode == AnalyzeMode) {
1240 if (appData.noChessProgram) {
1241 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1244 if (appData.icsActive) {
1245 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1249 } else if (initialMode == AnalyzeFile) {
1250 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1251 ShowThinkingEvent();
1253 AnalysisPeriodicEvent(1);
1254 } else if (initialMode == MachinePlaysWhite) {
1255 if (appData.noChessProgram) {
1256 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1260 if (appData.icsActive) {
1261 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1265 MachineWhiteEvent();
1266 } else if (initialMode == MachinePlaysBlack) {
1267 if (appData.noChessProgram) {
1268 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1272 if (appData.icsActive) {
1273 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1277 MachineBlackEvent();
1278 } else if (initialMode == TwoMachinesPlay) {
1279 if (appData.noChessProgram) {
1280 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1284 if (appData.icsActive) {
1285 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1290 } else if (initialMode == EditGame) {
1292 } else if (initialMode == EditPosition) {
1293 EditPositionEvent();
1294 } else if (initialMode == Training) {
1295 if (*appData.loadGameFile == NULLCHAR) {
1296 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1305 * Establish will establish a contact to a remote host.port.
1306 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1307 * used to talk to the host.
1308 * Returns 0 if okay, error code if not.
1315 if (*appData.icsCommPort != NULLCHAR) {
1316 /* Talk to the host through a serial comm port */
1317 return OpenCommPort(appData.icsCommPort, &icsPR);
1319 } else if (*appData.gateway != NULLCHAR) {
1320 if (*appData.remoteShell == NULLCHAR) {
1321 /* Use the rcmd protocol to run telnet program on a gateway host */
1322 snprintf(buf, sizeof(buf), "%s %s %s",
1323 appData.telnetProgram, appData.icsHost, appData.icsPort);
1324 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1327 /* Use the rsh program to run telnet program on a gateway host */
1328 if (*appData.remoteUser == NULLCHAR) {
1329 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1330 appData.gateway, appData.telnetProgram,
1331 appData.icsHost, appData.icsPort);
1333 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1334 appData.remoteShell, appData.gateway,
1335 appData.remoteUser, appData.telnetProgram,
1336 appData.icsHost, appData.icsPort);
1338 return StartChildProcess(buf, "", &icsPR);
1341 } else if (appData.useTelnet) {
1342 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1345 /* TCP socket interface differs somewhat between
1346 Unix and NT; handle details in the front end.
1348 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1353 show_bytes(fp, buf, count)
1359 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1360 fprintf(fp, "\\%03o", *buf & 0xff);
1369 /* Returns an errno value */
1371 OutputMaybeTelnet(pr, message, count, outError)
1377 char buf[8192], *p, *q, *buflim;
1378 int left, newcount, outcount;
1380 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1381 *appData.gateway != NULLCHAR) {
1382 if (appData.debugMode) {
1383 fprintf(debugFP, ">ICS: ");
1384 show_bytes(debugFP, message, count);
1385 fprintf(debugFP, "\n");
1387 return OutputToProcess(pr, message, count, outError);
1390 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1397 if (appData.debugMode) {
1398 fprintf(debugFP, ">ICS: ");
1399 show_bytes(debugFP, buf, newcount);
1400 fprintf(debugFP, "\n");
1402 outcount = OutputToProcess(pr, buf, newcount, outError);
1403 if (outcount < newcount) return -1; /* to be sure */
1410 } else if (((unsigned char) *p) == TN_IAC) {
1411 *q++ = (char) TN_IAC;
1418 if (appData.debugMode) {
1419 fprintf(debugFP, ">ICS: ");
1420 show_bytes(debugFP, buf, newcount);
1421 fprintf(debugFP, "\n");
1423 outcount = OutputToProcess(pr, buf, newcount, outError);
1424 if (outcount < newcount) return -1; /* to be sure */
1429 read_from_player(isr, closure, message, count, error)
1436 int outError, outCount;
1437 static int gotEof = 0;
1439 /* Pass data read from player on to ICS */
1442 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1443 if (outCount < count) {
1444 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1446 } else if (count < 0) {
1447 RemoveInputSource(isr);
1448 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1449 } else if (gotEof++ > 0) {
1450 RemoveInputSource(isr);
1451 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1459 int count, outCount, outError;
1461 if (icsPR == NULL) return;
1464 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1465 if (outCount < count) {
1466 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1470 /* This is used for sending logon scripts to the ICS. Sending
1471 without a delay causes problems when using timestamp on ICC
1472 (at least on my machine). */
1474 SendToICSDelayed(s,msdelay)
1478 int count, outCount, outError;
1480 if (icsPR == NULL) return;
1483 if (appData.debugMode) {
1484 fprintf(debugFP, ">ICS: ");
1485 show_bytes(debugFP, s, count);
1486 fprintf(debugFP, "\n");
1488 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1490 if (outCount < count) {
1491 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1496 /* Remove all highlighting escape sequences in s
1497 Also deletes any suffix starting with '('
1500 StripHighlightAndTitle(s)
1503 static char retbuf[MSG_SIZ];
1506 while (*s != NULLCHAR) {
1507 while (*s == '\033') {
1508 while (*s != NULLCHAR && !isalpha(*s)) s++;
1509 if (*s != NULLCHAR) s++;
1511 while (*s != NULLCHAR && *s != '\033') {
1512 if (*s == '(' || *s == '[') {
1523 /* Remove all highlighting escape sequences in s */
1528 static char retbuf[MSG_SIZ];
1531 while (*s != NULLCHAR) {
1532 while (*s == '\033') {
1533 while (*s != NULLCHAR && !isalpha(*s)) s++;
1534 if (*s != NULLCHAR) s++;
1536 while (*s != NULLCHAR && *s != '\033') {
1544 char *variantNames[] = VARIANT_NAMES;
1549 return variantNames[v];
1553 /* Identify a variant from the strings the chess servers use or the
1554 PGN Variant tag names we use. */
1561 VariantClass v = VariantNormal;
1562 int i, found = FALSE;
1567 /* [HGM] skip over optional board-size prefixes */
1568 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
1569 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
1570 while( *e++ != '_');
1573 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1574 if (StrCaseStr(e, variantNames[i])) {
1575 v = (VariantClass) i;
1582 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
1583 || StrCaseStr(e, "wild/fr")
1584 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
1585 v = VariantFischeRandom;
1586 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
1587 (i = 1, p = StrCaseStr(e, "w"))) {
1589 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
1596 case 0: /* FICS only, actually */
1598 /* Castling legal even if K starts on d-file */
1599 v = VariantWildCastle;
1604 /* Castling illegal even if K & R happen to start in
1605 normal positions. */
1606 v = VariantNoCastle;
1619 /* Castling legal iff K & R start in normal positions */
1625 /* Special wilds for position setup; unclear what to do here */
1626 v = VariantLoadable;
1629 /* Bizarre ICC game */
1630 v = VariantTwoKings;
1633 v = VariantKriegspiel;
1639 v = VariantFischeRandom;
1642 v = VariantCrazyhouse;
1645 v = VariantBughouse;
1651 /* Not quite the same as FICS suicide! */
1652 v = VariantGiveaway;
1658 v = VariantShatranj;
1661 /* Temporary names for future ICC types. The name *will* change in
1662 the next xboard/WinBoard release after ICC defines it. */
1700 v = VariantCapablanca;
1703 v = VariantKnightmate;
1709 v = VariantCylinder;
1715 v = VariantCapaRandom;
1718 v = VariantBerolina;
1730 /* Found "wild" or "w" in the string but no number;
1731 must assume it's normal chess. */
1735 sprintf(buf, _("Unknown wild type %d"), wnum);
1736 DisplayError(buf, 0);
1742 if (appData.debugMode) {
1743 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
1744 e, wnum, VariantName(v));
1749 static int leftover_start = 0, leftover_len = 0;
1750 char star_match[STAR_MATCH_N][MSG_SIZ];
1752 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
1753 advance *index beyond it, and set leftover_start to the new value of
1754 *index; else return FALSE. If pattern contains the character '*', it
1755 matches any sequence of characters not containing '\r', '\n', or the
1756 character following the '*' (if any), and the matched sequence(s) are
1757 copied into star_match.
1760 looking_at(buf, index, pattern)
1765 char *bufp = &buf[*index], *patternp = pattern;
1767 char *matchp = star_match[0];
1770 if (*patternp == NULLCHAR) {
1771 *index = leftover_start = bufp - buf;
1775 if (*bufp == NULLCHAR) return FALSE;
1776 if (*patternp == '*') {
1777 if (*bufp == *(patternp + 1)) {
1779 matchp = star_match[++star_count];
1783 } else if (*bufp == '\n' || *bufp == '\r') {
1785 if (*patternp == NULLCHAR)
1790 *matchp++ = *bufp++;
1794 if (*patternp != *bufp) return FALSE;
1801 SendToPlayer(data, length)
1805 int error, outCount;
1806 outCount = OutputToProcess(NoProc, data, length, &error);
1807 if (outCount < length) {
1808 DisplayFatalError(_("Error writing to display"), error, 1);
1813 PackHolding(packed, holding)
1825 switch (runlength) {
1836 sprintf(q, "%d", runlength);
1848 /* Telnet protocol requests from the front end */
1850 TelnetRequest(ddww, option)
1851 unsigned char ddww, option;
1853 unsigned char msg[3];
1854 int outCount, outError;
1856 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
1858 if (appData.debugMode) {
1859 char buf1[8], buf2[8], *ddwwStr, *optionStr;
1875 sprintf(buf1, "%d", ddww);
1884 sprintf(buf2, "%d", option);
1887 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
1892 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
1894 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1901 if (!appData.icsActive) return;
1902 TelnetRequest(TN_DO, TN_ECHO);
1908 if (!appData.icsActive) return;
1909 TelnetRequest(TN_DONT, TN_ECHO);
1913 CopyHoldings(Board board, char *holdings, ChessSquare lowestPiece)
1915 /* put the holdings sent to us by the server on the board holdings area */
1916 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
1920 if(gameInfo.holdingsWidth < 2) return;
1922 if( (int)lowestPiece >= BlackPawn ) {
1925 holdingsStartRow = BOARD_HEIGHT-1;
1928 holdingsColumn = BOARD_WIDTH-1;
1929 countsColumn = BOARD_WIDTH-2;
1930 holdingsStartRow = 0;
1934 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
1935 board[i][holdingsColumn] = EmptySquare;
1936 board[i][countsColumn] = (ChessSquare) 0;
1938 while( (p=*holdings++) != NULLCHAR ) {
1939 piece = CharToPiece( ToUpper(p) );
1940 if(piece == EmptySquare) continue;
1941 /*j = (int) piece - (int) WhitePawn;*/
1942 j = PieceToNumber(piece);
1943 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
1944 if(j < 0) continue; /* should not happen */
1945 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
1946 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
1947 board[holdingsStartRow+j*direction][countsColumn]++;
1954 VariantSwitch(Board board, VariantClass newVariant)
1956 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
1957 int oldCurrentMove = currentMove, oldForwardMostMove = forwardMostMove, oldBackwardMostMove = backwardMostMove;
1958 // Board tempBoard; int saveCastling[BOARD_SIZE], saveEP;
1960 startedFromPositionFile = FALSE;
1961 if(gameInfo.variant == newVariant) return;
1963 /* [HGM] This routine is called each time an assignment is made to
1964 * gameInfo.variant during a game, to make sure the board sizes
1965 * are set to match the new variant. If that means adding or deleting
1966 * holdings, we shift the playing board accordingly
1967 * This kludge is needed because in ICS observe mode, we get boards
1968 * of an ongoing game without knowing the variant, and learn about the
1969 * latter only later. This can be because of the move list we requested,
1970 * in which case the game history is refilled from the beginning anyway,
1971 * but also when receiving holdings of a crazyhouse game. In the latter
1972 * case we want to add those holdings to the already received position.
1976 if (appData.debugMode) {
1977 fprintf(debugFP, "Switch board from %s to %s\n",
1978 VariantName(gameInfo.variant), VariantName(newVariant));
1979 setbuf(debugFP, NULL);
1981 shuffleOpenings = 0; /* [HGM] shuffle */
1982 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
1983 switch(newVariant) {
1985 newWidth = 9; newHeight = 9;
1986 gameInfo.holdingsSize = 7;
1987 case VariantBughouse:
1988 case VariantCrazyhouse:
1989 newHoldingsWidth = 2; break;
1991 newHoldingsWidth = gameInfo.holdingsSize = 0;
1994 if(newWidth != gameInfo.boardWidth ||
1995 newHeight != gameInfo.boardHeight ||
1996 newHoldingsWidth != gameInfo.holdingsWidth ) {
1998 /* shift position to new playing area, if needed */
1999 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2000 for(i=0; i<BOARD_HEIGHT; i++)
2001 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2002 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2004 for(i=0; i<newHeight; i++) {
2005 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2006 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2008 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2009 for(i=0; i<BOARD_HEIGHT; i++)
2010 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2011 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2015 gameInfo.boardWidth = newWidth;
2016 gameInfo.boardHeight = newHeight;
2017 gameInfo.holdingsWidth = newHoldingsWidth;
2018 gameInfo.variant = newVariant;
2019 InitDrawingSizes(-2, 0);
2021 /* [HGM] The following should definitely be solved in a better way */
2023 CopyBoard(board, tempBoard); /* save position in case it is board[0] */
2024 for(i=0; i<BOARD_SIZE; i++) saveCastling[i] = castlingRights[0][i];
2025 saveEP = epStatus[0];
2027 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2029 epStatus[0] = saveEP;
2030 for(i=0; i<BOARD_SIZE; i++) castlingRights[0][i] = saveCastling[i];
2031 CopyBoard(tempBoard, board); /* restore position received from ICS */
2033 } else { gameInfo.variant = newVariant; InitPosition(FALSE); }
2035 forwardMostMove = oldForwardMostMove;
2036 backwardMostMove = oldBackwardMostMove;
2037 currentMove = oldCurrentMove; /* InitPos reset these, but we need still to redraw the position */
2040 static int loggedOn = FALSE;
2042 /*-- Game start info cache: --*/
2044 char gs_kind[MSG_SIZ];
2045 static char player1Name[128] = "";
2046 static char player2Name[128] = "";
2047 static int player1Rating = -1;
2048 static int player2Rating = -1;
2049 /*----------------------------*/
2051 ColorClass curColor = ColorNormal;
2052 int suppressKibitz = 0;
2055 read_from_ics(isr, closure, data, count, error)
2062 #define BUF_SIZE 8192
2063 #define STARTED_NONE 0
2064 #define STARTED_MOVES 1
2065 #define STARTED_BOARD 2
2066 #define STARTED_OBSERVE 3
2067 #define STARTED_HOLDINGS 4
2068 #define STARTED_CHATTER 5
2069 #define STARTED_COMMENT 6
2070 #define STARTED_MOVES_NOHIDE 7
2072 static int started = STARTED_NONE;
2073 static char parse[20000];
2074 static int parse_pos = 0;
2075 static char buf[BUF_SIZE + 1];
2076 static int firstTime = TRUE, intfSet = FALSE;
2077 static ColorClass prevColor = ColorNormal;
2078 static int savingComment = FALSE;
2084 int backup; /* [DM] For zippy color lines */
2087 if (appData.debugMode) {
2089 fprintf(debugFP, "<ICS: ");
2090 show_bytes(debugFP, data, count);
2091 fprintf(debugFP, "\n");
2095 if (appData.debugMode) { int f = forwardMostMove;
2096 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2097 castlingRights[f][0],castlingRights[f][1],castlingRights[f][2],castlingRights[f][3],castlingRights[f][4],castlingRights[f][5]);
2100 /* If last read ended with a partial line that we couldn't parse,
2101 prepend it to the new read and try again. */
2102 if (leftover_len > 0) {
2103 for (i=0; i<leftover_len; i++)
2104 buf[i] = buf[leftover_start + i];
2107 /* Copy in new characters, removing nulls and \r's */
2108 buf_len = leftover_len;
2109 for (i = 0; i < count; i++) {
2110 if (data[i] != NULLCHAR && data[i] != '\r')
2111 buf[buf_len++] = data[i];
2112 if(buf_len >= 5 && buf[buf_len-5]=='\n' && buf[buf_len-4]=='\\' &&
2113 buf[buf_len-3]==' ' && buf[buf_len-2]==' ' && buf[buf_len-1]==' ')
2114 buf_len -= 5; // [HGM] ICS: join continuation line of Lasker 2.2.3 server with previous
2115 buf[buf_len++] = ' '; // replace by space (assumes ICS does not break lines within word)
2118 buf[buf_len] = NULLCHAR;
2119 next_out = leftover_len;
2123 while (i < buf_len) {
2124 /* Deal with part of the TELNET option negotiation
2125 protocol. We refuse to do anything beyond the
2126 defaults, except that we allow the WILL ECHO option,
2127 which ICS uses to turn off password echoing when we are
2128 directly connected to it. We reject this option
2129 if localLineEditing mode is on (always on in xboard)
2130 and we are talking to port 23, which might be a real
2131 telnet server that will try to keep WILL ECHO on permanently.
2133 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2134 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2135 unsigned char option;
2137 switch ((unsigned char) buf[++i]) {
2139 if (appData.debugMode)
2140 fprintf(debugFP, "\n<WILL ");
2141 switch (option = (unsigned char) buf[++i]) {
2143 if (appData.debugMode)
2144 fprintf(debugFP, "ECHO ");
2145 /* Reply only if this is a change, according
2146 to the protocol rules. */
2147 if (remoteEchoOption) break;
2148 if (appData.localLineEditing &&
2149 atoi(appData.icsPort) == TN_PORT) {
2150 TelnetRequest(TN_DONT, TN_ECHO);
2153 TelnetRequest(TN_DO, TN_ECHO);
2154 remoteEchoOption = TRUE;
2158 if (appData.debugMode)
2159 fprintf(debugFP, "%d ", option);
2160 /* Whatever this is, we don't want it. */
2161 TelnetRequest(TN_DONT, option);
2166 if (appData.debugMode)
2167 fprintf(debugFP, "\n<WONT ");
2168 switch (option = (unsigned char) buf[++i]) {
2170 if (appData.debugMode)
2171 fprintf(debugFP, "ECHO ");
2172 /* Reply only if this is a change, according
2173 to the protocol rules. */
2174 if (!remoteEchoOption) break;
2176 TelnetRequest(TN_DONT, TN_ECHO);
2177 remoteEchoOption = FALSE;
2180 if (appData.debugMode)
2181 fprintf(debugFP, "%d ", (unsigned char) option);
2182 /* Whatever this is, it must already be turned
2183 off, because we never agree to turn on
2184 anything non-default, so according to the
2185 protocol rules, we don't reply. */
2190 if (appData.debugMode)
2191 fprintf(debugFP, "\n<DO ");
2192 switch (option = (unsigned char) buf[++i]) {
2194 /* Whatever this is, we refuse to do it. */
2195 if (appData.debugMode)
2196 fprintf(debugFP, "%d ", option);
2197 TelnetRequest(TN_WONT, option);
2202 if (appData.debugMode)
2203 fprintf(debugFP, "\n<DONT ");
2204 switch (option = (unsigned char) buf[++i]) {
2206 if (appData.debugMode)
2207 fprintf(debugFP, "%d ", option);
2208 /* Whatever this is, we are already not doing
2209 it, because we never agree to do anything
2210 non-default, so according to the protocol
2211 rules, we don't reply. */
2216 if (appData.debugMode)
2217 fprintf(debugFP, "\n<IAC ");
2218 /* Doubled IAC; pass it through */
2222 if (appData.debugMode)
2223 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2224 /* Drop all other telnet commands on the floor */
2227 if (oldi > next_out)
2228 SendToPlayer(&buf[next_out], oldi - next_out);
2234 /* OK, this at least will *usually* work */
2235 if (!loggedOn && looking_at(buf, &i, "ics%")) {
2239 if (loggedOn && !intfSet) {
2240 if (ics_type == ICS_ICC) {
2242 "/set-quietly interface %s\n/set-quietly style 12\n",
2245 } else if (ics_type == ICS_CHESSNET) {
2246 sprintf(str, "/style 12\n");
2248 strcpy(str, "alias $ @\n$set interface ");
2249 strcat(str, programVersion);
2250 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2252 strcat(str, "$iset nohighlight 1\n");
2254 strcat(str, "$iset lock 1\n$style 12\n");
2260 if (started == STARTED_COMMENT) {
2261 /* Accumulate characters in comment */
2262 parse[parse_pos++] = buf[i];
2263 if (buf[i] == '\n') {
2264 parse[parse_pos] = NULLCHAR;
2265 if(!suppressKibitz) // [HGM] kibitz
2266 AppendComment(forwardMostMove, StripHighlight(parse));
2267 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2268 int nrDigit = 0, nrAlph = 0, i;
2269 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2270 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2271 parse[parse_pos] = NULLCHAR;
2272 // try to be smart: if it does not look like search info, it should go to
2273 // ICS interaction window after all, not to engine-output window.
2274 for(i=0; i<parse_pos; i++) { // count letters and digits
2275 nrDigit += (parse[i] >= '0' && parse[i] <= '9');
2276 nrAlph += (parse[i] >= 'a' && parse[i] <= 'z');
2277 nrAlph += (parse[i] >= 'A' && parse[i] <= 'Z');
2279 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
2280 int depth=0; float score;
2281 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
2282 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
2283 pvInfoList[forwardMostMove-1].depth = depth;
2284 pvInfoList[forwardMostMove-1].score = 100*score;
2286 OutputKibitz(suppressKibitz, parse);
2289 sprintf(tmp, _("your opponent kibitzes: %s"), parse);
2290 SendToPlayer(tmp, strlen(tmp));
2293 started = STARTED_NONE;
2295 /* Don't match patterns against characters in chatter */
2300 if (started == STARTED_CHATTER) {
2301 if (buf[i] != '\n') {
2302 /* Don't match patterns against characters in chatter */
2306 started = STARTED_NONE;
2309 /* Kludge to deal with rcmd protocol */
2310 if (firstTime && looking_at(buf, &i, "\001*")) {
2311 DisplayFatalError(&buf[1], 0, 1);
2317 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
2320 if (appData.debugMode)
2321 fprintf(debugFP, "ics_type %d\n", ics_type);
2324 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
2325 ics_type = ICS_FICS;
2327 if (appData.debugMode)
2328 fprintf(debugFP, "ics_type %d\n", ics_type);
2331 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
2332 ics_type = ICS_CHESSNET;
2334 if (appData.debugMode)
2335 fprintf(debugFP, "ics_type %d\n", ics_type);
2340 (looking_at(buf, &i, "\"*\" is *a registered name") ||
2341 looking_at(buf, &i, "Logging you in as \"*\"") ||
2342 looking_at(buf, &i, "will be \"*\""))) {
2343 strcpy(ics_handle, star_match[0]);
2347 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
2349 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
2350 DisplayIcsInteractionTitle(buf);
2351 have_set_title = TRUE;
2354 /* skip finger notes */
2355 if (started == STARTED_NONE &&
2356 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
2357 (buf[i] == '1' && buf[i+1] == '0')) &&
2358 buf[i+2] == ':' && buf[i+3] == ' ') {
2359 started = STARTED_CHATTER;
2364 /* skip formula vars */
2365 if (started == STARTED_NONE &&
2366 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
2367 started = STARTED_CHATTER;
2373 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
2374 if (appData.autoKibitz && started == STARTED_NONE &&
2375 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
2376 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
2377 if(looking_at(buf, &i, "* kibitzes: ") &&
2378 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
2379 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
2380 suppressKibitz = TRUE;
2381 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
2382 && (gameMode == IcsPlayingWhite)) ||
2383 (StrStr(star_match[0], gameInfo.black) == star_match[0]
2384 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
2385 started = STARTED_CHATTER; // own kibitz we simply discard
2387 started = STARTED_COMMENT; // make sure it will be collected in parse[]
2388 parse_pos = 0; parse[0] = NULLCHAR;
2389 savingComment = TRUE;
2390 suppressKibitz = gameMode != IcsObserving ? 2 :
2391 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
2395 if(looking_at(buf, &i, "kibitzed to")) { // suppress the acknowledgements of our own autoKibitz
2396 started = STARTED_CHATTER;
2397 suppressKibitz = TRUE;
2399 } // [HGM] kibitz: end of patch
2401 if (appData.zippyTalk || appData.zippyPlay) {
2402 /* [DM] Backup address for color zippy lines */
2406 if (loggedOn == TRUE)
2407 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
2408 (appData.zippyPlay && ZippyMatch(buf, &backup)));
2410 if (ZippyControl(buf, &i) ||
2411 ZippyConverse(buf, &i) ||
2412 (appData.zippyPlay && ZippyMatch(buf, &i))) {
2414 if (!appData.colorize) continue;
2418 } // [DM] 'else { ' deleted
2419 if (/* Don't color "message" or "messages" output */
2420 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
2421 looking_at(buf, &i, "*. * at *:*: ") ||
2422 looking_at(buf, &i, "--* (*:*): ") ||
2423 /* Regular tells and says */
2424 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
2425 looking_at(buf, &i, "* (your partner) tells you: ") ||
2426 looking_at(buf, &i, "* says: ") ||
2427 /* Message notifications (same color as tells) */
2428 looking_at(buf, &i, "* has left a message ") ||
2429 looking_at(buf, &i, "* just sent you a message:\n") ||
2430 /* Whispers and kibitzes */
2431 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
2432 looking_at(buf, &i, "* kibitzes: ") ||
2434 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
2436 if (tkind == 1 && strchr(star_match[0], ':')) {
2437 /* Avoid "tells you:" spoofs in channels */
2440 if (star_match[0][0] == NULLCHAR ||
2441 strchr(star_match[0], ' ') ||
2442 (tkind == 3 && strchr(star_match[1], ' '))) {
2443 /* Reject bogus matches */
2446 if (appData.colorize) {
2447 if (oldi > next_out) {
2448 SendToPlayer(&buf[next_out], oldi - next_out);
2453 Colorize(ColorTell, FALSE);
2454 curColor = ColorTell;
2457 Colorize(ColorKibitz, FALSE);
2458 curColor = ColorKibitz;
2461 p = strrchr(star_match[1], '(');
2468 Colorize(ColorChannel1, FALSE);
2469 curColor = ColorChannel1;
2471 Colorize(ColorChannel, FALSE);
2472 curColor = ColorChannel;
2476 curColor = ColorNormal;
2480 if (started == STARTED_NONE && appData.autoComment &&
2481 (gameMode == IcsObserving ||
2482 gameMode == IcsPlayingWhite ||
2483 gameMode == IcsPlayingBlack)) {
2484 parse_pos = i - oldi;
2485 memcpy(parse, &buf[oldi], parse_pos);
2486 parse[parse_pos] = NULLCHAR;
2487 started = STARTED_COMMENT;
2488 savingComment = TRUE;
2490 started = STARTED_CHATTER;
2491 savingComment = FALSE;
2498 if (looking_at(buf, &i, "* s-shouts: ") ||
2499 looking_at(buf, &i, "* c-shouts: ")) {
2500 if (appData.colorize) {
2501 if (oldi > next_out) {
2502 SendToPlayer(&buf[next_out], oldi - next_out);
2505 Colorize(ColorSShout, FALSE);
2506 curColor = ColorSShout;
2509 started = STARTED_CHATTER;
2513 if (looking_at(buf, &i, "--->")) {
2518 if (looking_at(buf, &i, "* shouts: ") ||
2519 looking_at(buf, &i, "--> ")) {
2520 if (appData.colorize) {
2521 if (oldi > next_out) {
2522 SendToPlayer(&buf[next_out], oldi - next_out);
2525 Colorize(ColorShout, FALSE);
2526 curColor = ColorShout;
2529 started = STARTED_CHATTER;
2533 if (looking_at( buf, &i, "Challenge:")) {
2534 if (appData.colorize) {
2535 if (oldi > next_out) {
2536 SendToPlayer(&buf[next_out], oldi - next_out);
2539 Colorize(ColorChallenge, FALSE);
2540 curColor = ColorChallenge;
2546 if (looking_at(buf, &i, "* offers you") ||
2547 looking_at(buf, &i, "* offers to be") ||
2548 looking_at(buf, &i, "* would like to") ||
2549 looking_at(buf, &i, "* requests to") ||
2550 looking_at(buf, &i, "Your opponent offers") ||
2551 looking_at(buf, &i, "Your opponent requests")) {
2553 if (appData.colorize) {
2554 if (oldi > next_out) {
2555 SendToPlayer(&buf[next_out], oldi - next_out);
2558 Colorize(ColorRequest, FALSE);
2559 curColor = ColorRequest;
2564 if (looking_at(buf, &i, "* (*) seeking")) {
2565 if (appData.colorize) {
2566 if (oldi > next_out) {
2567 SendToPlayer(&buf[next_out], oldi - next_out);
2570 Colorize(ColorSeek, FALSE);
2571 curColor = ColorSeek;
2576 if (looking_at(buf, &i, "\\ ")) {
2577 if (prevColor != ColorNormal) {
2578 if (oldi > next_out) {
2579 SendToPlayer(&buf[next_out], oldi - next_out);
2582 Colorize(prevColor, TRUE);
2583 curColor = prevColor;
2585 if (savingComment) {
2586 parse_pos = i - oldi;
2587 memcpy(parse, &buf[oldi], parse_pos);
2588 parse[parse_pos] = NULLCHAR;
2589 started = STARTED_COMMENT;
2591 started = STARTED_CHATTER;
2596 if (looking_at(buf, &i, "Black Strength :") ||
2597 looking_at(buf, &i, "<<< style 10 board >>>") ||
2598 looking_at(buf, &i, "<10>") ||
2599 looking_at(buf, &i, "#@#")) {
2600 /* Wrong board style */
2602 SendToICS(ics_prefix);
2603 SendToICS("set style 12\n");
2604 SendToICS(ics_prefix);
2605 SendToICS("refresh\n");
2609 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
2611 have_sent_ICS_logon = 1;
2615 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
2616 (looking_at(buf, &i, "\n<12> ") ||
2617 looking_at(buf, &i, "<12> "))) {
2619 if (oldi > next_out) {
2620 SendToPlayer(&buf[next_out], oldi - next_out);
2623 started = STARTED_BOARD;
2628 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
2629 looking_at(buf, &i, "<b1> ")) {
2630 if (oldi > next_out) {
2631 SendToPlayer(&buf[next_out], oldi - next_out);
2634 started = STARTED_HOLDINGS;
2639 if (looking_at(buf, &i, "* *vs. * *--- *")) {
2641 /* Header for a move list -- first line */
2643 switch (ics_getting_history) {
2647 case BeginningOfGame:
2648 /* User typed "moves" or "oldmoves" while we
2649 were idle. Pretend we asked for these
2650 moves and soak them up so user can step
2651 through them and/or save them.
2654 gameMode = IcsObserving;
2657 ics_getting_history = H_GOT_UNREQ_HEADER;
2659 case EditGame: /*?*/
2660 case EditPosition: /*?*/
2661 /* Should above feature work in these modes too? */
2662 /* For now it doesn't */
2663 ics_getting_history = H_GOT_UNWANTED_HEADER;
2666 ics_getting_history = H_GOT_UNWANTED_HEADER;
2671 /* Is this the right one? */
2672 if (gameInfo.white && gameInfo.black &&
2673 strcmp(gameInfo.white, star_match[0]) == 0 &&
2674 strcmp(gameInfo.black, star_match[2]) == 0) {
2676 ics_getting_history = H_GOT_REQ_HEADER;
2679 case H_GOT_REQ_HEADER:
2680 case H_GOT_UNREQ_HEADER:
2681 case H_GOT_UNWANTED_HEADER:
2682 case H_GETTING_MOVES:
2683 /* Should not happen */
2684 DisplayError(_("Error gathering move list: two headers"), 0);
2685 ics_getting_history = H_FALSE;
2689 /* Save player ratings into gameInfo if needed */
2690 if ((ics_getting_history == H_GOT_REQ_HEADER ||
2691 ics_getting_history == H_GOT_UNREQ_HEADER) &&
2692 (gameInfo.whiteRating == -1 ||
2693 gameInfo.blackRating == -1)) {
2695 gameInfo.whiteRating = string_to_rating(star_match[1]);
2696 gameInfo.blackRating = string_to_rating(star_match[3]);
2697 if (appData.debugMode)
2698 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
2699 gameInfo.whiteRating, gameInfo.blackRating);
2704 if (looking_at(buf, &i,
2705 "* * match, initial time: * minute*, increment: * second")) {
2706 /* Header for a move list -- second line */
2707 /* Initial board will follow if this is a wild game */
2708 if (gameInfo.event != NULL) free(gameInfo.event);
2709 sprintf(str, "ICS %s %s match", star_match[0], star_match[1]);
2710 gameInfo.event = StrSave(str);
2711 /* [HGM] we switched variant. Translate boards if needed. */
2712 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
2716 if (looking_at(buf, &i, "Move ")) {
2717 /* Beginning of a move list */
2718 switch (ics_getting_history) {
2720 /* Normally should not happen */
2721 /* Maybe user hit reset while we were parsing */
2724 /* Happens if we are ignoring a move list that is not
2725 * the one we just requested. Common if the user
2726 * tries to observe two games without turning off
2729 case H_GETTING_MOVES:
2730 /* Should not happen */
2731 DisplayError(_("Error gathering move list: nested"), 0);
2732 ics_getting_history = H_FALSE;
2734 case H_GOT_REQ_HEADER:
2735 ics_getting_history = H_GETTING_MOVES;
2736 started = STARTED_MOVES;
2738 if (oldi > next_out) {
2739 SendToPlayer(&buf[next_out], oldi - next_out);
2742 case H_GOT_UNREQ_HEADER:
2743 ics_getting_history = H_GETTING_MOVES;
2744 started = STARTED_MOVES_NOHIDE;
2747 case H_GOT_UNWANTED_HEADER:
2748 ics_getting_history = H_FALSE;
2754 if (looking_at(buf, &i, "% ") ||
2755 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
2756 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
2757 savingComment = FALSE;
2760 case STARTED_MOVES_NOHIDE:
2761 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
2762 parse[parse_pos + i - oldi] = NULLCHAR;
2763 ParseGameHistory(parse);
2765 if (appData.zippyPlay && first.initDone) {
2766 FeedMovesToProgram(&first, forwardMostMove);
2767 if (gameMode == IcsPlayingWhite) {
2768 if (WhiteOnMove(forwardMostMove)) {
2769 if (first.sendTime) {
2770 if (first.useColors) {
2771 SendToProgram("black\n", &first);
2773 SendTimeRemaining(&first, TRUE);
2776 if (first.useColors) {
2777 SendToProgram("white\ngo\n", &first);
2779 SendToProgram("go\n", &first);
2782 if (first.useColors) {
2783 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
2785 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
2787 first.maybeThinking = TRUE;
2789 if (first.usePlayother) {
2790 if (first.sendTime) {
2791 SendTimeRemaining(&first, TRUE);
2793 SendToProgram("playother\n", &first);
2799 } else if (gameMode == IcsPlayingBlack) {
2800 if (!WhiteOnMove(forwardMostMove)) {
2801 if (first.sendTime) {
2802 if (first.useColors) {
2803 SendToProgram("white\n", &first);
2805 SendTimeRemaining(&first, FALSE);
2808 if (first.useColors) {
2809 SendToProgram("black\ngo\n", &first);
2811 SendToProgram("go\n", &first);
2814 if (first.useColors) {
2815 SendToProgram("black\n", &first);
2817 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
2819 first.maybeThinking = TRUE;
2821 if (first.usePlayother) {
2822 if (first.sendTime) {
2823 SendTimeRemaining(&first, FALSE);
2825 SendToProgram("playother\n", &first);
2834 if (gameMode == IcsObserving && ics_gamenum == -1) {
2835 /* Moves came from oldmoves or moves command
2836 while we weren't doing anything else.
2838 currentMove = forwardMostMove;
2839 ClearHighlights();/*!!could figure this out*/
2840 flipView = appData.flipView;
2841 DrawPosition(FALSE, boards[currentMove]);
2842 DisplayBothClocks();
2843 sprintf(str, "%s vs. %s",
2844 gameInfo.white, gameInfo.black);
2848 /* Moves were history of an active game */
2849 if (gameInfo.resultDetails != NULL) {
2850 free(gameInfo.resultDetails);
2851 gameInfo.resultDetails = NULL;
2854 HistorySet(parseList, backwardMostMove,
2855 forwardMostMove, currentMove-1);
2856 DisplayMove(currentMove - 1);
2857 if (started == STARTED_MOVES) next_out = i;
2858 started = STARTED_NONE;
2859 ics_getting_history = H_FALSE;
2862 case STARTED_OBSERVE:
2863 started = STARTED_NONE;
2864 SendToICS(ics_prefix);
2865 SendToICS("refresh\n");
2871 if(bookHit) { // [HGM] book: simulate book reply
2872 static char bookMove[MSG_SIZ]; // a bit generous?
2874 programStats.nodes = programStats.depth = programStats.time =
2875 programStats.score = programStats.got_only_move = 0;
2876 sprintf(programStats.movelist, "%s (xbook)", bookHit);
2878 strcpy(bookMove, "move ");
2879 strcat(bookMove, bookHit);
2880 HandleMachineMove(bookMove, &first);
2885 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
2886 started == STARTED_HOLDINGS ||
2887 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
2888 /* Accumulate characters in move list or board */
2889 parse[parse_pos++] = buf[i];
2892 /* Start of game messages. Mostly we detect start of game
2893 when the first board image arrives. On some versions
2894 of the ICS, though, we need to do a "refresh" after starting
2895 to observe in order to get the current board right away. */
2896 if (looking_at(buf, &i, "Adding game * to observation list")) {
2897 started = STARTED_OBSERVE;
2901 /* Handle auto-observe */
2902 if (appData.autoObserve &&
2903 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
2904 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
2906 /* Choose the player that was highlighted, if any. */
2907 if (star_match[0][0] == '\033' ||
2908 star_match[1][0] != '\033') {
2909 player = star_match[0];
2911 player = star_match[2];
2913 sprintf(str, "%sobserve %s\n",
2914 ics_prefix, StripHighlightAndTitle(player));
2917 /* Save ratings from notify string */
2918 strcpy(player1Name, star_match[0]);
2919 player1Rating = string_to_rating(star_match[1]);
2920 strcpy(player2Name, star_match[2]);
2921 player2Rating = string_to_rating(star_match[3]);
2923 if (appData.debugMode)
2925 "Ratings from 'Game notification:' %s %d, %s %d\n",
2926 player1Name, player1Rating,
2927 player2Name, player2Rating);
2932 /* Deal with automatic examine mode after a game,
2933 and with IcsObserving -> IcsExamining transition */
2934 if (looking_at(buf, &i, "Entering examine mode for game *") ||
2935 looking_at(buf, &i, "has made you an examiner of game *")) {
2937 int gamenum = atoi(star_match[0]);
2938 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
2939 gamenum == ics_gamenum) {
2940 /* We were already playing or observing this game;
2941 no need to refetch history */
2942 gameMode = IcsExamining;
2944 pauseExamForwardMostMove = forwardMostMove;
2945 } else if (currentMove < forwardMostMove) {
2946 ForwardInner(forwardMostMove);
2949 /* I don't think this case really can happen */
2950 SendToICS(ics_prefix);
2951 SendToICS("refresh\n");
2956 /* Error messages */
2957 // if (ics_user_moved) {
2958 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
2959 if (looking_at(buf, &i, "Illegal move") ||
2960 looking_at(buf, &i, "Not a legal move") ||
2961 looking_at(buf, &i, "Your king is in check") ||
2962 looking_at(buf, &i, "It isn't your turn") ||
2963 looking_at(buf, &i, "It is not your move")) {
2965 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
2966 currentMove = --forwardMostMove;
2967 DisplayMove(currentMove - 1); /* before DMError */
2968 DrawPosition(FALSE, boards[currentMove]);
2970 DisplayBothClocks();
2972 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
2978 if (looking_at(buf, &i, "still have time") ||
2979 looking_at(buf, &i, "not out of time") ||
2980 looking_at(buf, &i, "either player is out of time") ||
2981 looking_at(buf, &i, "has timeseal; checking")) {
2982 /* We must have called his flag a little too soon */
2983 whiteFlag = blackFlag = FALSE;
2987 if (looking_at(buf, &i, "added * seconds to") ||
2988 looking_at(buf, &i, "seconds were added to")) {
2989 /* Update the clocks */
2990 SendToICS(ics_prefix);
2991 SendToICS("refresh\n");
2995 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
2996 ics_clock_paused = TRUE;
3001 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3002 ics_clock_paused = FALSE;
3007 /* Grab player ratings from the Creating: message.
3008 Note we have to check for the special case when
3009 the ICS inserts things like [white] or [black]. */
3010 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3011 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3013 0 player 1 name (not necessarily white)
3015 2 empty, white, or black (IGNORED)
3016 3 player 2 name (not necessarily black)
3019 The names/ratings are sorted out when the game
3020 actually starts (below).
3022 strcpy(player1Name, StripHighlightAndTitle(star_match[0]));
3023 player1Rating = string_to_rating(star_match[1]);
3024 strcpy(player2Name, StripHighlightAndTitle(star_match[3]));
3025 player2Rating = string_to_rating(star_match[4]);
3027 if (appData.debugMode)
3029 "Ratings from 'Creating:' %s %d, %s %d\n",
3030 player1Name, player1Rating,
3031 player2Name, player2Rating);
3036 /* Improved generic start/end-of-game messages */
3037 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3038 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3039 /* If tkind == 0: */
3040 /* star_match[0] is the game number */
3041 /* [1] is the white player's name */
3042 /* [2] is the black player's name */
3043 /* For end-of-game: */
3044 /* [3] is the reason for the game end */
3045 /* [4] is a PGN end game-token, preceded by " " */
3046 /* For start-of-game: */
3047 /* [3] begins with "Creating" or "Continuing" */
3048 /* [4] is " *" or empty (don't care). */
3049 int gamenum = atoi(star_match[0]);
3050 char *whitename, *blackname, *why, *endtoken;
3051 ChessMove endtype = (ChessMove) 0;
3054 whitename = star_match[1];
3055 blackname = star_match[2];
3056 why = star_match[3];
3057 endtoken = star_match[4];
3059 whitename = star_match[1];
3060 blackname = star_match[3];
3061 why = star_match[5];
3062 endtoken = star_match[6];
3065 /* Game start messages */
3066 if (strncmp(why, "Creating ", 9) == 0 ||
3067 strncmp(why, "Continuing ", 11) == 0) {
3068 gs_gamenum = gamenum;
3069 strcpy(gs_kind, strchr(why, ' ') + 1);
3071 if (appData.zippyPlay) {
3072 ZippyGameStart(whitename, blackname);
3078 /* Game end messages */
3079 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3080 ics_gamenum != gamenum) {
3083 while (endtoken[0] == ' ') endtoken++;
3084 switch (endtoken[0]) {
3087 endtype = GameUnfinished;
3090 endtype = BlackWins;
3093 if (endtoken[1] == '/')
3094 endtype = GameIsDrawn;
3096 endtype = WhiteWins;
3099 GameEnds(endtype, why, GE_ICS);
3101 if (appData.zippyPlay && first.initDone) {
3102 ZippyGameEnd(endtype, why);
3103 if (first.pr == NULL) {
3104 /* Start the next process early so that we'll
3105 be ready for the next challenge */
3106 StartChessProgram(&first);
3108 /* Send "new" early, in case this command takes
3109 a long time to finish, so that we'll be ready
3110 for the next challenge. */
3111 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3118 if (looking_at(buf, &i, "Removing game * from observation") ||
3119 looking_at(buf, &i, "no longer observing game *") ||
3120 looking_at(buf, &i, "Game * (*) has no examiners")) {
3121 if (gameMode == IcsObserving &&
3122 atoi(star_match[0]) == ics_gamenum)
3124 /* icsEngineAnalyze */
3125 if (appData.icsEngineAnalyze) {
3132 ics_user_moved = FALSE;
3137 if (looking_at(buf, &i, "no longer examining game *")) {
3138 if (gameMode == IcsExamining &&
3139 atoi(star_match[0]) == ics_gamenum)
3143 ics_user_moved = FALSE;
3148 /* Advance leftover_start past any newlines we find,
3149 so only partial lines can get reparsed */
3150 if (looking_at(buf, &i, "\n")) {
3151 prevColor = curColor;
3152 if (curColor != ColorNormal) {
3153 if (oldi > next_out) {
3154 SendToPlayer(&buf[next_out], oldi - next_out);
3157 Colorize(ColorNormal, FALSE);
3158 curColor = ColorNormal;
3160 if (started == STARTED_BOARD) {
3161 started = STARTED_NONE;
3162 parse[parse_pos] = NULLCHAR;
3163 ParseBoard12(parse);
3166 /* Send premove here */
3167 if (appData.premove) {
3169 if (currentMove == 0 &&
3170 gameMode == IcsPlayingWhite &&
3171 appData.premoveWhite) {
3172 sprintf(str, "%s%s\n", ics_prefix,
3173 appData.premoveWhiteText);
3174 if (appData.debugMode)
3175 fprintf(debugFP, "Sending premove:\n");
3177 } else if (currentMove == 1 &&
3178 gameMode == IcsPlayingBlack &&
3179 appData.premoveBlack) {
3180 sprintf(str, "%s%s\n", ics_prefix,
3181 appData.premoveBlackText);
3182 if (appData.debugMode)
3183 fprintf(debugFP, "Sending premove:\n");
3185 } else if (gotPremove) {
3187 ClearPremoveHighlights();
3188 if (appData.debugMode)
3189 fprintf(debugFP, "Sending premove:\n");
3190 UserMoveEvent(premoveFromX, premoveFromY,
3191 premoveToX, premoveToY,
3196 /* Usually suppress following prompt */
3197 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
3198 if (looking_at(buf, &i, "*% ")) {
3199 savingComment = FALSE;
3203 } else if (started == STARTED_HOLDINGS) {
3205 char new_piece[MSG_SIZ];
3206 started = STARTED_NONE;
3207 parse[parse_pos] = NULLCHAR;
3208 if (appData.debugMode)
3209 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
3210 parse, currentMove);
3211 if (sscanf(parse, " game %d", &gamenum) == 1 &&
3212 gamenum == ics_gamenum) {
3213 if (gameInfo.variant == VariantNormal) {
3214 /* [HGM] We seem to switch variant during a game!
3215 * Presumably no holdings were displayed, so we have
3216 * to move the position two files to the right to
3217 * create room for them!
3219 VariantSwitch(boards[currentMove], VariantCrazyhouse); /* temp guess */
3220 /* Get a move list just to see the header, which
3221 will tell us whether this is really bug or zh */
3222 if (ics_getting_history == H_FALSE) {
3223 ics_getting_history = H_REQUESTED;
3224 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
3228 new_piece[0] = NULLCHAR;
3229 sscanf(parse, "game %d white [%s black [%s <- %s",
3230 &gamenum, white_holding, black_holding,
3232 white_holding[strlen(white_holding)-1] = NULLCHAR;
3233 black_holding[strlen(black_holding)-1] = NULLCHAR;
3234 /* [HGM] copy holdings to board holdings area */
3235 CopyHoldings(boards[currentMove], white_holding, WhitePawn);
3236 CopyHoldings(boards[currentMove], black_holding, BlackPawn);
3238 if (appData.zippyPlay && first.initDone) {
3239 ZippyHoldings(white_holding, black_holding,
3243 if (tinyLayout || smallLayout) {
3244 char wh[16], bh[16];
3245 PackHolding(wh, white_holding);
3246 PackHolding(bh, black_holding);
3247 sprintf(str, "[%s-%s] %s-%s", wh, bh,
3248 gameInfo.white, gameInfo.black);
3250 sprintf(str, "%s [%s] vs. %s [%s]",
3251 gameInfo.white, white_holding,
3252 gameInfo.black, black_holding);
3255 DrawPosition(FALSE, boards[currentMove]);
3258 /* Suppress following prompt */
3259 if (looking_at(buf, &i, "*% ")) {
3260 savingComment = FALSE;
3267 i++; /* skip unparsed character and loop back */
3270 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz suppress printing in ICS interaction window
3271 started != STARTED_HOLDINGS && i > next_out) {
3272 SendToPlayer(&buf[next_out], i - next_out);
3275 suppressKibitz = FALSE; // [HGM] kibitz: has done its duty in if-statement above
3277 leftover_len = buf_len - leftover_start;
3278 /* if buffer ends with something we couldn't parse,
3279 reparse it after appending the next read */
3281 } else if (count == 0) {
3282 RemoveInputSource(isr);
3283 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
3285 DisplayFatalError(_("Error reading from ICS"), error, 1);
3290 /* Board style 12 looks like this:
3292 <12> r-b---k- pp----pp ---bP--- ---p---- q------- ------P- P--Q--BP -----R-K W -1 0 0 0 0 0 0 paf MaxII 0 2 12 21 25 234 174 24 Q/d7-a4 (0:06) Qxa4 0 0
3294 * The "<12> " is stripped before it gets to this routine. The two
3295 * trailing 0's (flip state and clock ticking) are later addition, and
3296 * some chess servers may not have them, or may have only the first.
3297 * Additional trailing fields may be added in the future.
3300 #define PATTERN "%c%d%d%d%d%d%d%d%s%s%d%d%d%d%d%d%d%d%s%s%s%d%d"
3302 #define RELATION_OBSERVING_PLAYED 0
3303 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
3304 #define RELATION_PLAYING_MYMOVE 1
3305 #define RELATION_PLAYING_NOTMYMOVE -1
3306 #define RELATION_EXAMINING 2
3307 #define RELATION_ISOLATED_BOARD -3
3308 #define RELATION_STARTING_POSITION -4 /* FICS only */
3311 ParseBoard12(string)
3314 GameMode newGameMode;
3315 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0, i;
3316 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time, takeback;
3317 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
3318 char to_play, board_chars[200];
3319 char move_str[500], str[500], elapsed_time[500];
3320 char black[32], white[32];
3322 int prevMove = currentMove;
3325 int fromX, fromY, toX, toY;
3327 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
3328 char *bookHit = NULL; // [HGM] book
3330 fromX = fromY = toX = toY = -1;
3334 if (appData.debugMode)
3335 fprintf(debugFP, _("Parsing board: %s\n"), string);
3337 move_str[0] = NULLCHAR;
3338 elapsed_time[0] = NULLCHAR;
3339 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
3341 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
3342 if(string[i] == ' ') { ranks++; files = 0; }
3346 for(j = 0; j <i; j++) board_chars[j] = string[j];
3347 board_chars[i] = '\0';
3350 n = sscanf(string, PATTERN, &to_play, &double_push,
3351 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
3352 &gamenum, white, black, &relation, &basetime, &increment,
3353 &white_stren, &black_stren, &white_time, &black_time,
3354 &moveNum, str, elapsed_time, move_str, &ics_flip,
3358 snprintf(str, sizeof(str), _("Failed to parse board string:\n\"%s\""), string);
3359 DisplayError(str, 0);
3363 /* Convert the move number to internal form */
3364 moveNum = (moveNum - 1) * 2;
3365 if (to_play == 'B') moveNum++;
3366 if (moveNum >= MAX_MOVES) {
3367 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
3373 case RELATION_OBSERVING_PLAYED:
3374 case RELATION_OBSERVING_STATIC:
3375 if (gamenum == -1) {
3376 /* Old ICC buglet */
3377 relation = RELATION_OBSERVING_STATIC;
3379 newGameMode = IcsObserving;
3381 case RELATION_PLAYING_MYMOVE:
3382 case RELATION_PLAYING_NOTMYMOVE:
3384 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
3385 IcsPlayingWhite : IcsPlayingBlack;
3387 case RELATION_EXAMINING:
3388 newGameMode = IcsExamining;
3390 case RELATION_ISOLATED_BOARD:
3392 /* Just display this board. If user was doing something else,
3393 we will forget about it until the next board comes. */
3394 newGameMode = IcsIdle;
3396 case RELATION_STARTING_POSITION:
3397 newGameMode = gameMode;
3401 /* Modify behavior for initial board display on move listing
3404 switch (ics_getting_history) {
3408 case H_GOT_REQ_HEADER:
3409 case H_GOT_UNREQ_HEADER:
3410 /* This is the initial position of the current game */
3411 gamenum = ics_gamenum;
3412 moveNum = 0; /* old ICS bug workaround */
3413 if (to_play == 'B') {
3414 startedFromSetupPosition = TRUE;
3415 blackPlaysFirst = TRUE;
3417 if (forwardMostMove == 0) forwardMostMove = 1;
3418 if (backwardMostMove == 0) backwardMostMove = 1;
3419 if (currentMove == 0) currentMove = 1;
3421 newGameMode = gameMode;
3422 relation = RELATION_STARTING_POSITION; /* ICC needs this */
3424 case H_GOT_UNWANTED_HEADER:
3425 /* This is an initial board that we don't want */
3427 case H_GETTING_MOVES:
3428 /* Should not happen */
3429 DisplayError(_("Error gathering move list: extra board"), 0);
3430 ics_getting_history = H_FALSE;
3434 /* Take action if this is the first board of a new game, or of a
3435 different game than is currently being displayed. */
3436 if (gamenum != ics_gamenum || newGameMode != gameMode ||
3437 relation == RELATION_ISOLATED_BOARD) {
3439 /* Forget the old game and get the history (if any) of the new one */
3440 if (gameMode != BeginningOfGame) {
3444 if (appData.autoRaiseBoard) BoardToTop();
3446 if (gamenum == -1) {
3447 newGameMode = IcsIdle;
3448 } else if (moveNum > 0 && newGameMode != IcsIdle &&
3449 appData.getMoveList) {
3450 /* Need to get game history */
3451 ics_getting_history = H_REQUESTED;
3452 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
3456 /* Initially flip the board to have black on the bottom if playing
3457 black or if the ICS flip flag is set, but let the user change
3458 it with the Flip View button. */
3459 flipView = appData.autoFlipView ?
3460 (newGameMode == IcsPlayingBlack) || ics_flip :
3463 /* Done with values from previous mode; copy in new ones */
3464 gameMode = newGameMode;
3466 ics_gamenum = gamenum;
3467 if (gamenum == gs_gamenum) {
3468 int klen = strlen(gs_kind);
3469 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
3470 sprintf(str, "ICS %s", gs_kind);
3471 gameInfo.event = StrSave(str);
3473 gameInfo.event = StrSave("ICS game");
3475 gameInfo.site = StrSave(appData.icsHost);
3476 gameInfo.date = PGNDate();
3477 gameInfo.round = StrSave("-");
3478 gameInfo.white = StrSave(white);
3479 gameInfo.black = StrSave(black);
3480 timeControl = basetime * 60 * 1000;
3482 timeIncrement = increment * 1000;
3483 movesPerSession = 0;
3484 gameInfo.timeControl = TimeControlTagValue();
3485 VariantSwitch(board, StringToVariant(gameInfo.event) );
3486 if (appData.debugMode) {
3487 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
3488 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
3489 setbuf(debugFP, NULL);
3492 gameInfo.outOfBook = NULL;
3494 /* Do we have the ratings? */
3495 if (strcmp(player1Name, white) == 0 &&
3496 strcmp(player2Name, black) == 0) {
3497 if (appData.debugMode)
3498 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
3499 player1Rating, player2Rating);
3500 gameInfo.whiteRating = player1Rating;
3501 gameInfo.blackRating = player2Rating;
3502 } else if (strcmp(player2Name, white) == 0 &&
3503 strcmp(player1Name, black) == 0) {
3504 if (appData.debugMode)
3505 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
3506 player2Rating, player1Rating);
3507 gameInfo.whiteRating = player2Rating;
3508 gameInfo.blackRating = player1Rating;
3510 player1Name[0] = player2Name[0] = NULLCHAR;
3512 /* Silence shouts if requested */
3513 if (appData.quietPlay &&
3514 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
3515 SendToICS(ics_prefix);
3516 SendToICS("set shout 0\n");
3520 /* Deal with midgame name changes */
3522 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
3523 if (gameInfo.white) free(gameInfo.white);
3524 gameInfo.white = StrSave(white);
3526 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
3527 if (gameInfo.black) free(gameInfo.black);
3528 gameInfo.black = StrSave(black);
3532 /* Throw away game result if anything actually changes in examine mode */
3533 if (gameMode == IcsExamining && !newGame) {
3534 gameInfo.result = GameUnfinished;
3535 if (gameInfo.resultDetails != NULL) {
3536 free(gameInfo.resultDetails);
3537 gameInfo.resultDetails = NULL;
3541 /* In pausing && IcsExamining mode, we ignore boards coming
3542 in if they are in a different variation than we are. */
3543 if (pauseExamInvalid) return;
3544 if (pausing && gameMode == IcsExamining) {
3545 if (moveNum <= pauseExamForwardMostMove) {
3546 pauseExamInvalid = TRUE;
3547 forwardMostMove = pauseExamForwardMostMove;
3552 if (appData.debugMode) {
3553 fprintf(debugFP, "load %dx%d board\n", files, ranks);
3555 /* Parse the board */
3556 for (k = 0; k < ranks; k++) {
3557 for (j = 0; j < files; j++)
3558 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
3559 if(gameInfo.holdingsWidth > 1) {
3560 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
3561 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
3564 CopyBoard(boards[moveNum], board);
3566 startedFromSetupPosition =
3567 !CompareBoards(board, initialPosition);
3568 if(startedFromSetupPosition)
3569 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
3572 /* [HGM] Set castling rights. Take the outermost Rooks,
3573 to make it also work for FRC opening positions. Note that board12
3574 is really defective for later FRC positions, as it has no way to
3575 indicate which Rook can castle if they are on the same side of King.
3576 For the initial position we grant rights to the outermost Rooks,
3577 and remember thos rights, and we then copy them on positions
3578 later in an FRC game. This means WB might not recognize castlings with
3579 Rooks that have moved back to their original position as illegal,
3580 but in ICS mode that is not its job anyway.
3582 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
3583 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
3585 for(i=BOARD_LEFT, j= -1; i<BOARD_RGHT; i++)
3586 if(board[0][i] == WhiteRook) j = i;
3587 initialRights[0] = castlingRights[moveNum][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? -1 : j);
3588 for(i=BOARD_RGHT-1, j= -1; i>=BOARD_LEFT; i--)
3589 if(board[0][i] == WhiteRook) j = i;
3590 initialRights[1] = castlingRights[moveNum][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? -1 : j);
3591 for(i=BOARD_LEFT, j= -1; i<BOARD_RGHT; i++)
3592 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
3593 initialRights[3] = castlingRights[moveNum][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? -1 : j);
3594 for(i=BOARD_RGHT-1, j= -1; i>=BOARD_LEFT; i--)
3595 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
3596 initialRights[4] = castlingRights[moveNum][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? -1 : j);
3598 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
3599 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
3600 if(board[0][k] == wKing) initialRights[2] = castlingRights[moveNum][2] = k;
3601 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
3602 if(board[BOARD_HEIGHT-1][k] == bKing)
3603 initialRights[5] = castlingRights[moveNum][5] = k;
3605 r = castlingRights[moveNum][0] = initialRights[0];
3606 if(board[0][r] != WhiteRook) castlingRights[moveNum][0] = -1;
3607 r = castlingRights[moveNum][1] = initialRights[1];
3608 if(board[0][r] != WhiteRook) castlingRights[moveNum][1] = -1;
3609 r = castlingRights[moveNum][3] = initialRights[3];
3610 if(board[BOARD_HEIGHT-1][r] != BlackRook) castlingRights[moveNum][3] = -1;
3611 r = castlingRights[moveNum][4] = initialRights[4];
3612 if(board[BOARD_HEIGHT-1][r] != BlackRook) castlingRights[moveNum][4] = -1;
3613 /* wildcastle kludge: always assume King has rights */
3614 r = castlingRights[moveNum][2] = initialRights[2];
3615 r = castlingRights[moveNum][5] = initialRights[5];
3617 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
3618 epStatus[moveNum] = double_push == -1 ? EP_NONE : double_push + BOARD_LEFT;
3621 if (ics_getting_history == H_GOT_REQ_HEADER ||
3622 ics_getting_history == H_GOT_UNREQ_HEADER) {
3623 /* This was an initial position from a move list, not
3624 the current position */
3628 /* Update currentMove and known move number limits */
3629 newMove = newGame || moveNum > forwardMostMove;
3631 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
3632 if (!newGame && appData.icsEngineAnalyze && moveNum < forwardMostMove) {
3633 takeback = forwardMostMove - moveNum;
3634 for (i = 0; i < takeback; i++) {
3635 if (appData.debugMode) fprintf(debugFP, "take back move\n");
3636 SendToProgram("undo\n", &first);
3641 forwardMostMove = backwardMostMove = currentMove = moveNum;
3642 if (gameMode == IcsExamining && moveNum == 0) {
3643 /* Workaround for ICS limitation: we are not told the wild
3644 type when starting to examine a game. But if we ask for
3645 the move list, the move list header will tell us */
3646 ics_getting_history = H_REQUESTED;
3647 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
3650 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
3651 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
3652 forwardMostMove = moveNum;
3653 if (!pausing || currentMove > forwardMostMove)
3654 currentMove = forwardMostMove;
3656 /* New part of history that is not contiguous with old part */
3657 if (pausing && gameMode == IcsExamining) {
3658 pauseExamInvalid = TRUE;
3659 forwardMostMove = pauseExamForwardMostMove;
3662 forwardMostMove = backwardMostMove = currentMove = moveNum;
3663 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
3664 ics_getting_history = H_REQUESTED;
3665 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
3670 /* Update the clocks */
3671 if (strchr(elapsed_time, '.')) {
3673 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
3674 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
3676 /* Time is in seconds */
3677 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
3678 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
3683 if (appData.zippyPlay && newGame &&
3684 gameMode != IcsObserving && gameMode != IcsIdle &&
3685 gameMode != IcsExamining)
3686 ZippyFirstBoard(moveNum, basetime, increment);
3689 /* Put the move on the move list, first converting
3690 to canonical algebraic form. */
3692 if (appData.debugMode) {
3693 if (appData.debugMode) { int f = forwardMostMove;
3694 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
3695 castlingRights[f][0],castlingRights[f][1],castlingRights[f][2],castlingRights[f][3],castlingRights[f][4],castlingRights[f][5]);
3697 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
3698 fprintf(debugFP, "moveNum = %d\n", moveNum);
3699 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
3700 setbuf(debugFP, NULL);
3702 if (moveNum <= backwardMostMove) {
3703 /* We don't know what the board looked like before
3705 strcpy(parseList[moveNum - 1], move_str);
3706 strcat(parseList[moveNum - 1], " ");
3707 strcat(parseList[moveNum - 1], elapsed_time);
3708 moveList[moveNum - 1][0] = NULLCHAR;
3709 } else if (strcmp(move_str, "none") == 0) {
3710 // [HGM] long SAN: swapped order; test for 'none' before parsing move
3711 /* Again, we don't know what the board looked like;
3712 this is really the start of the game. */
3713 parseList[moveNum - 1][0] = NULLCHAR;
3714 moveList[moveNum - 1][0] = NULLCHAR;
3715 backwardMostMove = moveNum;
3716 startedFromSetupPosition = TRUE;
3717 fromX = fromY = toX = toY = -1;
3719 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
3720 // So we parse the long-algebraic move string in stead of the SAN move
3721 int valid; char buf[MSG_SIZ], *prom;
3723 // str looks something like "Q/a1-a2"; kill the slash
3725 sprintf(buf, "%c%s", str[0], str+2);
3726 else strcpy(buf, str); // might be castling
3727 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
3728 strcat(buf, prom); // long move lacks promo specification!
3729 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
3730 if(appData.debugMode)
3731 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
3732 strcpy(move_str, buf);
3734 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
3735 &fromX, &fromY, &toX, &toY, &promoChar)
3736 || ParseOneMove(buf, moveNum - 1, &moveType,
3737 &fromX, &fromY, &toX, &toY, &promoChar);
3738 // end of long SAN patch
3740 (void) CoordsToAlgebraic(boards[moveNum - 1],
3741 PosFlags(moveNum - 1), EP_UNKNOWN,
3742 fromY, fromX, toY, toX, promoChar,
3743 parseList[moveNum-1]);
3744 switch (MateTest(boards[moveNum], PosFlags(moveNum), EP_UNKNOWN,
3745 castlingRights[moveNum]) ) {
3751 if(gameInfo.variant != VariantShogi)
3752 strcat(parseList[moveNum - 1], "+");
3755 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
3756 strcat(parseList[moveNum - 1], "#");
3759 strcat(parseList[moveNum - 1], " ");
3760 strcat(parseList[moveNum - 1], elapsed_time);
3761 /* currentMoveString is set as a side-effect of ParseOneMove */
3762 strcpy(moveList[moveNum - 1], currentMoveString);
3763 strcat(moveList[moveNum - 1], "\n");
3765 /* Move from ICS was illegal!? Punt. */
3766 if (appData.debugMode) {
3767 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
3768 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
3771 if (appData.testLegality && appData.debugMode) {
3772 sprintf(str, "Illegal move \"%s\" from ICS", move_str);
3773 DisplayError(str, 0);
3776 strcpy(parseList[moveNum - 1], move_str);
3777 strcat(parseList[moveNum - 1], " ");
3778 strcat(parseList[moveNum - 1], elapsed_time);
3779 moveList[moveNum - 1][0] = NULLCHAR;
3780 fromX = fromY = toX = toY = -1;
3783 if (appData.debugMode) {
3784 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
3785 setbuf(debugFP, NULL);
3789 /* Send move to chess program (BEFORE animating it). */
3790 if (appData.zippyPlay && !newGame && newMove &&
3791 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
3793 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
3794 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
3795 if (moveList[moveNum - 1][0] == NULLCHAR) {
3796 sprintf(str, _("Couldn't parse move \"%s\" from ICS"),
3798 DisplayError(str, 0);
3800 if (first.sendTime) {
3801 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
3803 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
3804 if (firstMove && !bookHit) {
3806 if (first.useColors) {
3807 SendToProgram(gameMode == IcsPlayingWhite ?
3809 "black\ngo\n", &first);
3811 SendToProgram("go\n", &first);
3813 first.maybeThinking = TRUE;
3816 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
3817 if (moveList[moveNum - 1][0] == NULLCHAR) {
3818 sprintf(str, _("Couldn't parse move \"%s\" from ICS"), move_str);
3819 DisplayError(str, 0);
3821 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
3822 SendMoveToProgram(moveNum - 1, &first);
3829 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
3830 /* If move comes from a remote source, animate it. If it
3831 isn't remote, it will have already been animated. */
3832 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
3833 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
3835 if (!pausing && appData.highlightLastMove) {
3836 SetHighlights(fromX, fromY, toX, toY);
3840 /* Start the clocks */
3841 whiteFlag = blackFlag = FALSE;
3842 appData.clockMode = !(basetime == 0 && increment == 0);
3844 ics_clock_paused = TRUE;
3846 } else if (ticking == 1) {
3847 ics_clock_paused = FALSE;
3849 if (gameMode == IcsIdle ||
3850 relation == RELATION_OBSERVING_STATIC ||
3851 relation == RELATION_EXAMINING ||
3853 DisplayBothClocks();
3857 /* Display opponents and material strengths */
3858 if (gameInfo.variant != VariantBughouse &&
3859 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
3860 if (tinyLayout || smallLayout) {
3861 if(gameInfo.variant == VariantNormal)
3862 sprintf(str, "%s(%d) %s(%d) {%d %d}",
3863 gameInfo.white, white_stren, gameInfo.black, black_stren,
3864 basetime, increment);
3866 sprintf(str, "%s(%d) %s(%d) {%d %d w%d}",
3867 gameInfo.white, white_stren, gameInfo.black, black_stren,
3868 basetime, increment, (int) gameInfo.variant);
3870 if(gameInfo.variant == VariantNormal)
3871 sprintf(str, "%s (%d) vs. %s (%d) {%d %d}",
3872 gameInfo.white, white_stren, gameInfo.black, black_stren,
3873 basetime, increment);
3875 sprintf(str, "%s (%d) vs. %s (%d) {%d %d %s}",
3876 gameInfo.white, white_stren, gameInfo.black, black_stren,
3877 basetime, increment, VariantName(gameInfo.variant));
3880 if (appData.debugMode) {
3881 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
3886 /* Display the board */
3887 if (!pausing && !appData.noGUI) {
3889 if (appData.premove)
3891 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
3892 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
3893 ClearPremoveHighlights();
3895 DrawPosition(FALSE, boards[currentMove]);
3896 DisplayMove(moveNum - 1);
3897 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
3898 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
3899 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
3900 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
3904 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
3906 if(bookHit) { // [HGM] book: simulate book reply
3907 static char bookMove[MSG_SIZ]; // a bit generous?
3909 programStats.nodes = programStats.depth = programStats.time =
3910 programStats.score = programStats.got_only_move = 0;
3911 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3913 strcpy(bookMove, "move ");
3914 strcat(bookMove, bookHit);
3915 HandleMachineMove(bookMove, &first);
3924 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
3925 ics_getting_history = H_REQUESTED;
3926 sprintf(buf, "%smoves %d\n", ics_prefix, ics_gamenum);
3932 AnalysisPeriodicEvent(force)
3935 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
3936 && !force) || !appData.periodicUpdates)
3939 /* Send . command to Crafty to collect stats */
3940 SendToProgram(".\n", &first);
3942 /* Don't send another until we get a response (this makes
3943 us stop sending to old Crafty's which don't understand
3944 the "." command (sending illegal cmds resets node count & time,
3945 which looks bad)) */
3946 programStats.ok_to_send = 0;
3950 SendMoveToProgram(moveNum, cps)
3952 ChessProgramState *cps;
3956 if (cps->useUsermove) {
3957 SendToProgram("usermove ", cps);
3961 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
3962 int len = space - parseList[moveNum];
3963 memcpy(buf, parseList[moveNum], len);
3965 buf[len] = NULLCHAR;
3967 sprintf(buf, "%s\n", parseList[moveNum]);
3969 SendToProgram(buf, cps);
3971 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
3972 AlphaRank(moveList[moveNum], 4);
3973 SendToProgram(moveList[moveNum], cps);
3974 AlphaRank(moveList[moveNum], 4); // and back
3976 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
3977 * the engine. It would be nice to have a better way to identify castle
3979 if((gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom)
3980 && cps->useOOCastle) {
3981 int fromX = moveList[moveNum][0] - AAA;
3982 int fromY = moveList[moveNum][1] - ONE;
3983 int toX = moveList[moveNum][2] - AAA;
3984 int toY = moveList[moveNum][3] - ONE;
3985 if((boards[moveNum][fromY][fromX] == WhiteKing
3986 && boards[moveNum][toY][toX] == WhiteRook)
3987 || (boards[moveNum][fromY][fromX] == BlackKing
3988 && boards[moveNum][toY][toX] == BlackRook)) {
3989 if(toX > fromX) SendToProgram("O-O\n", cps);
3990 else SendToProgram("O-O-O\n", cps);
3992 else SendToProgram(moveList[moveNum], cps);
3994 else SendToProgram(moveList[moveNum], cps);
3995 /* End of additions by Tord */
3998 /* [HGM] setting up the opening has brought engine in force mode! */
3999 /* Send 'go' if we are in a mode where machine should play. */
4000 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
4001 (gameMode == TwoMachinesPlay ||
4003 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
4005 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
4006 SendToProgram("go\n", cps);
4007 if (appData.debugMode) {
4008 fprintf(debugFP, "(extra)\n");
4011 setboardSpoiledMachineBlack = 0;
4015 SendMoveToICS(moveType, fromX, fromY, toX, toY)
4017 int fromX, fromY, toX, toY;
4019 char user_move[MSG_SIZ];
4023 sprintf(user_move, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
4024 (int)moveType, fromX, fromY, toX, toY);
4025 DisplayError(user_move + strlen("say "), 0);
4027 case WhiteKingSideCastle:
4028 case BlackKingSideCastle:
4029 case WhiteQueenSideCastleWild:
4030 case BlackQueenSideCastleWild:
4032 case WhiteHSideCastleFR:
4033 case BlackHSideCastleFR:
4035 sprintf(user_move, "o-o\n");
4037 case WhiteQueenSideCastle:
4038 case BlackQueenSideCastle:
4039 case WhiteKingSideCastleWild:
4040 case BlackKingSideCastleWild:
4042 case WhiteASideCastleFR:
4043 case BlackASideCastleFR:
4045 sprintf(user_move, "o-o-o\n");
4047 case WhitePromotionQueen:
4048 case BlackPromotionQueen:
4049 case WhitePromotionRook:
4050 case BlackPromotionRook:
4051 case WhitePromotionBishop:
4052 case BlackPromotionBishop:
4053 case WhitePromotionKnight:
4054 case BlackPromotionKnight:
4055 case WhitePromotionKing:
4056 case BlackPromotionKing:
4057 case WhitePromotionChancellor:
4058 case BlackPromotionChancellor:
4059 case WhitePromotionArchbishop:
4060 case BlackPromotionArchbishop:
4061 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier)
4062 sprintf(user_move, "%c%c%c%c=%c\n",
4063 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4064 PieceToChar(WhiteFerz));
4065 else if(gameInfo.variant == VariantGreat)
4066 sprintf(user_move, "%c%c%c%c=%c\n",
4067 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4068 PieceToChar(WhiteMan));
4070 sprintf(user_move, "%c%c%c%c=%c\n",
4071 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4072 PieceToChar(PromoPiece(moveType)));
4076 sprintf(user_move, "%c@%c%c\n",
4077 ToUpper(PieceToChar((ChessSquare) fromX)),
4078 AAA + toX, ONE + toY);
4081 case WhiteCapturesEnPassant:
4082 case BlackCapturesEnPassant:
4083 case IllegalMove: /* could be a variant we don't quite understand */
4084 sprintf(user_move, "%c%c%c%c\n",
4085 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4088 SendToICS(user_move);
4092 CoordsToComputerAlgebraic(rf, ff, rt, ft, promoChar, move)
4097 if (rf == DROP_RANK) {
4098 sprintf(move, "%c@%c%c\n",
4099 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
4101 if (promoChar == 'x' || promoChar == NULLCHAR) {
4102 sprintf(move, "%c%c%c%c\n",
4103 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
4105 sprintf(move, "%c%c%c%c%c\n",
4106 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
4112 ProcessICSInitScript(f)
4117 while (fgets(buf, MSG_SIZ, f)) {
4118 SendToICSDelayed(buf,(long)appData.msLoginDelay);
4125 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
4127 AlphaRank(char *move, int n)
4129 // char *p = move, c; int x, y;
4131 if (appData.debugMode) {
4132 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
4136 move[2]>='0' && move[2]<='9' &&
4137 move[3]>='a' && move[3]<='x' ) {
4139 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4140 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4142 if(move[0]>='0' && move[0]<='9' &&
4143 move[1]>='a' && move[1]<='x' &&
4144 move[2]>='0' && move[2]<='9' &&
4145 move[3]>='a' && move[3]<='x' ) {
4146 /* input move, Shogi -> normal */
4147 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
4148 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
4149 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4150 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4153 move[3]>='0' && move[3]<='9' &&
4154 move[2]>='a' && move[2]<='x' ) {
4156 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4157 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4160 move[0]>='a' && move[0]<='x' &&
4161 move[3]>='0' && move[3]<='9' &&
4162 move[2]>='a' && move[2]<='x' ) {
4163 /* output move, normal -> Shogi */
4164 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
4165 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
4166 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4167 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4168 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
4170 if (appData.debugMode) {
4171 fprintf(debugFP, " out = '%s'\n", move);
4175 /* Parser for moves from gnuchess, ICS, or user typein box */
4177 ParseOneMove(move, moveNum, moveType, fromX, fromY, toX, toY, promoChar)
4180 ChessMove *moveType;
4181 int *fromX, *fromY, *toX, *toY;
4184 if (appData.debugMode) {
4185 fprintf(debugFP, "move to parse: %s\n", move);
4187 *moveType = yylexstr(moveNum, move);
4189 switch (*moveType) {
4190 case WhitePromotionChancellor:
4191 case BlackPromotionChancellor:
4192 case WhitePromotionArchbishop:
4193 case BlackPromotionArchbishop:
4194 case WhitePromotionQueen:
4195 case BlackPromotionQueen:
4196 case WhitePromotionRook:
4197 case BlackPromotionRook:
4198 case WhitePromotionBishop:
4199 case BlackPromotionBishop:
4200 case WhitePromotionKnight:
4201 case BlackPromotionKnight:
4202 case WhitePromotionKing:
4203 case BlackPromotionKing:
4205 case WhiteCapturesEnPassant:
4206 case BlackCapturesEnPassant:
4207 case WhiteKingSideCastle:
4208 case WhiteQueenSideCastle:
4209 case BlackKingSideCastle:
4210 case BlackQueenSideCastle:
4211 case WhiteKingSideCastleWild:
4212 case WhiteQueenSideCastleWild:
4213 case BlackKingSideCastleWild:
4214 case BlackQueenSideCastleWild:
4215 /* Code added by Tord: */
4216 case WhiteHSideCastleFR:
4217 case WhiteASideCastleFR:
4218 case BlackHSideCastleFR:
4219 case BlackASideCastleFR:
4220 /* End of code added by Tord */
4221 case IllegalMove: /* bug or odd chess variant */
4222 *fromX = currentMoveString[0] - AAA;
4223 *fromY = currentMoveString[1] - ONE;
4224 *toX = currentMoveString[2] - AAA;
4225 *toY = currentMoveString[3] - ONE;
4226 *promoChar = currentMoveString[4];
4227 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
4228 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
4229 if (appData.debugMode) {
4230 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
4232 *fromX = *fromY = *toX = *toY = 0;
4235 if (appData.testLegality) {
4236 return (*moveType != IllegalMove);
4238 return !(fromX == fromY && toX == toY);
4243 *fromX = *moveType == WhiteDrop ?
4244 (int) CharToPiece(ToUpper(currentMoveString[0])) :
4245 (int) CharToPiece(ToLower(currentMoveString[0]));
4247 *toX = currentMoveString[2] - AAA;
4248 *toY = currentMoveString[3] - ONE;
4249 *promoChar = NULLCHAR;
4253 case ImpossibleMove:
4254 case (ChessMove) 0: /* end of file */
4263 if (appData.debugMode) {
4264 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
4267 *fromX = *fromY = *toX = *toY = 0;
4268 *promoChar = NULLCHAR;
4273 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
4274 // All positions will have equal probability, but the current method will not provide a unique
4275 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
4281 int piecesLeft[(int)BlackPawn];
4282 int seed, nrOfShuffles;
4284 void GetPositionNumber()
4285 { // sets global variable seed
4288 seed = appData.defaultFrcPosition;
4289 if(seed < 0) { // randomize based on time for negative FRC position numbers
4290 for(i=0; i<50; i++) seed += random();
4291 seed = random() ^ random() >> 8 ^ random() << 8;
4292 if(seed<0) seed = -seed;
4296 int put(Board board, int pieceType, int rank, int n, int shade)
4297 // put the piece on the (n-1)-th empty squares of the given shade
4301 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
4302 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
4303 board[rank][i] = (ChessSquare) pieceType;
4304 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
4306 piecesLeft[pieceType]--;
4314 void AddOnePiece(Board board, int pieceType, int rank, int shade)
4315 // calculate where the next piece goes, (any empty square), and put it there
4319 i = seed % squaresLeft[shade];
4320 nrOfShuffles *= squaresLeft[shade];
4321 seed /= squaresLeft[shade];
4322 put(board, pieceType, rank, i, shade);
4325 void AddTwoPieces(Board board, int pieceType, int rank)
4326 // calculate where the next 2 identical pieces go, (any empty square), and put it there
4328 int i, n=squaresLeft[ANY], j=n-1, k;
4330 k = n*(n-1)/2; // nr of possibilities, not counting permutations
4331 i = seed % k; // pick one
4334 while(i >= j) i -= j--;
4335 j = n - 1 - j; i += j;
4336 put(board, pieceType, rank, j, ANY);
4337 put(board, pieceType, rank, i, ANY);
4340 void SetUpShuffle(Board board, int number)
4344 GetPositionNumber(); nrOfShuffles = 1;
4346 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
4347 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
4348 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
4350 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
4352 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
4353 p = (int) board[0][i];
4354 if(p < (int) BlackPawn) piecesLeft[p] ++;
4355 board[0][i] = EmptySquare;
4358 if(PosFlags(0) & F_ALL_CASTLE_OK) {
4359 // shuffles restricted to allow normal castling put KRR first
4360 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
4361 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
4362 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
4363 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
4364 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
4365 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
4366 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
4367 put(board, WhiteRook, 0, 0, ANY);
4368 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
4371 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
4372 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
4373 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
4374 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
4375 while(piecesLeft[p] >= 2) {
4376 AddOnePiece(board, p, 0, LITE);
4377 AddOnePiece(board, p, 0, DARK);
4379 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
4382 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
4383 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
4384 // but we leave King and Rooks for last, to possibly obey FRC restriction
4385 if(p == (int)WhiteRook) continue;
4386 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
4387 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
4390 // now everything is placed, except perhaps King (Unicorn) and Rooks
4392 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
4393 // Last King gets castling rights
4394 while(piecesLeft[(int)WhiteUnicorn]) {
4395 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
4396 initialRights[2] = initialRights[5] = castlingRights[0][2] = castlingRights[0][5] = i;
4399 while(piecesLeft[(int)WhiteKing]) {
4400 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
4401 initialRights[2] = initialRights[5] = castlingRights[0][2] = castlingRights[0][5] = i;
4406 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
4407 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
4410 // Only Rooks can be left; simply place them all
4411 while(piecesLeft[(int)WhiteRook]) {
4412 i = put(board, WhiteRook, 0, 0, ANY);
4413 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
4416 initialRights[1] = initialRights[4] = castlingRights[0][1] = castlingRights[0][4] = i;
4418 initialRights[0] = initialRights[3] = castlingRights[0][0] = castlingRights[0][3] = i;
4421 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
4422 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
4425 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
4428 int SetCharTable( char *table, const char * map )
4429 /* [HGM] moved here from winboard.c because of its general usefulness */
4430 /* Basically a safe strcpy that uses the last character as King */
4432 int result = FALSE; int NrPieces;
4434 if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
4435 && NrPieces >= 12 && !(NrPieces&1)) {
4436 int i; /* [HGM] Accept even length from 12 to 34 */
4438 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
4439 for( i=0; i<NrPieces/2-1; i++ ) {
4441 table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
4443 table[(int) WhiteKing] = map[NrPieces/2-1];
4444 table[(int) BlackKing] = map[NrPieces-1];
4452 void Prelude(Board board)
4453 { // [HGM] superchess: random selection of exo-pieces
4454 int i, j, k; ChessSquare p;
4455 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
4457 GetPositionNumber(); // use FRC position number
4459 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
4460 SetCharTable(pieceToChar, appData.pieceToCharTable);
4461 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
4462 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
4465 j = seed%4; seed /= 4;
4466 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
4467 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
4468 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
4469 j = seed%3 + (seed%3 >= j); seed /= 3;
4470 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
4471 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
4472 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
4473 j = seed%3; seed /= 3;
4474 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
4475 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
4476 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
4477 j = seed%2 + (seed%2 >= j); seed /= 2;
4478 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
4479 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
4480 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
4481 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
4482 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
4483 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
4484 put(board, exoPieces[0], 0, 0, ANY);
4485 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
4489 InitPosition(redraw)
4492 ChessSquare (* pieces)[BOARD_SIZE];
4493 int i, j, pawnRow, overrule,
4494 oldx = gameInfo.boardWidth,
4495 oldy = gameInfo.boardHeight,
4496 oldh = gameInfo.holdingsWidth,
4497 oldv = gameInfo.variant;
4499 currentMove = forwardMostMove = backwardMostMove = 0;
4500 if(appData.icsActive) shuffleOpenings = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
4502 /* [AS] Initialize pv info list [HGM] and game status */
4504 for( i=0; i<MAX_MOVES; i++ ) {
4505 pvInfoList[i].depth = 0;
4506 epStatus[i]=EP_NONE;
4507 for( j=0; j<BOARD_SIZE; j++ ) castlingRights[i][j] = -1;
4510 initialRulePlies = 0; /* 50-move counter start */
4512 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
4513 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
4517 /* [HGM] logic here is completely changed. In stead of full positions */
4518 /* the initialized data only consist of the two backranks. The switch */
4519 /* selects which one we will use, which is than copied to the Board */
4520 /* initialPosition, which for the rest is initialized by Pawns and */
4521 /* empty squares. This initial position is then copied to boards[0], */
4522 /* possibly after shuffling, so that it remains available. */
4524 gameInfo.holdingsWidth = 0; /* default board sizes */
4525 gameInfo.boardWidth = 8;
4526 gameInfo.boardHeight = 8;
4527 gameInfo.holdingsSize = 0;
4528 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
4529 for(i=0; i<BOARD_SIZE; i++) initialRights[i] = -1; /* but no rights yet */
4530 SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
4532 switch (gameInfo.variant) {
4533 case VariantFischeRandom:
4534 shuffleOpenings = TRUE;
4538 case VariantShatranj:
4539 pieces = ShatranjArray;
4540 nrCastlingRights = 0;
4541 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
4543 case VariantTwoKings:
4544 pieces = twoKingsArray;
4546 case VariantCapaRandom:
4547 shuffleOpenings = TRUE;
4548 case VariantCapablanca:
4549 pieces = CapablancaArray;
4550 gameInfo.boardWidth = 10;
4551 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
4554 pieces = GothicArray;
4555 gameInfo.boardWidth = 10;
4556 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
4559 pieces = JanusArray;
4560 gameInfo.boardWidth = 10;
4561 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
4562 nrCastlingRights = 6;
4563 castlingRights[0][0] = initialRights[0] = BOARD_RGHT-1;
4564 castlingRights[0][1] = initialRights[1] = BOARD_LEFT;
4565 castlingRights[0][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
4566 castlingRights[0][3] = initialRights[3] = BOARD_RGHT-1;
4567 castlingRights[0][4] = initialRights[4] = BOARD_LEFT;
4568 castlingRights[0][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
4571 pieces = FalconArray;
4572 gameInfo.boardWidth = 10;
4573 SetCharTable(pieceToChar, "PNBRQ.............FKpnbrq.............fk");
4575 case VariantXiangqi:
4576 pieces = XiangqiArray;
4577 gameInfo.boardWidth = 9;
4578 gameInfo.boardHeight = 10;
4579 nrCastlingRights = 0;
4580 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
4583 pieces = ShogiArray;
4584 gameInfo.boardWidth = 9;
4585 gameInfo.boardHeight = 9;
4586 gameInfo.holdingsSize = 7;
4587 nrCastlingRights = 0;
4588 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
4590 case VariantCourier:
4591 pieces = CourierArray;
4592 gameInfo.boardWidth = 12;
4593 nrCastlingRights = 0;
4594 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
4595 for(i=0; i<BOARD_SIZE; i++) initialRights[i] = -1;
4597 case VariantKnightmate:
4598 pieces = KnightmateArray;
4599 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
4602 pieces = fairyArray;
4603 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVSLUKpnbrqfeacwmohijgdvsluk");
4606 pieces = GreatArray;
4607 gameInfo.boardWidth = 10;
4608 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
4609 gameInfo.holdingsSize = 8;
4613 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
4614 gameInfo.holdingsSize = 8;
4615 startedFromSetupPosition = TRUE;
4617 case VariantCrazyhouse:
4618 case VariantBughouse:
4620 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
4621 gameInfo.holdingsSize = 5;
4623 case VariantWildCastle:
4625 /* !!?shuffle with kings guaranteed to be on d or e file */
4626 shuffleOpenings = 1;
4628 case VariantNoCastle:
4630 nrCastlingRights = 0;
4631 for(i=0; i<BOARD_SIZE; i++) initialRights[i] = -1;
4632 /* !!?unconstrained back-rank shuffle */
4633 shuffleOpenings = 1;
4638 if(appData.NrFiles >= 0) {
4639 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
4640 gameInfo.boardWidth = appData.NrFiles;
4642 if(appData.NrRanks >= 0) {
4643 gameInfo.boardHeight = appData.NrRanks;
4645 if(appData.holdingsSize >= 0) {
4646 i = appData.holdingsSize;
4647 if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
4648 gameInfo.holdingsSize = i;
4650 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
4651 if(BOARD_HEIGHT > BOARD_SIZE || BOARD_WIDTH > BOARD_SIZE)
4652 DisplayFatalError(_("Recompile to support this BOARD_SIZE!"), 0, 2);
4654 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
4655 if(pawnRow < 1) pawnRow = 1;
4657 /* User pieceToChar list overrules defaults */
4658 if(appData.pieceToCharTable != NULL)
4659 SetCharTable(pieceToChar, appData.pieceToCharTable);
4661 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
4663 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
4664 s = (ChessSquare) 0; /* account holding counts in guard band */
4665 for( i=0; i<BOARD_HEIGHT; i++ )
4666 initialPosition[i][j] = s;
4668 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
4669 initialPosition[0][j] = pieces[0][j-gameInfo.holdingsWidth];
4670 initialPosition[pawnRow][j] = WhitePawn;
4671 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = BlackPawn;
4672 if(gameInfo.variant == VariantXiangqi) {
4674 initialPosition[pawnRow][j] =
4675 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
4676 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
4677 initialPosition[2][j] = WhiteCannon;
4678 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
4682 initialPosition[BOARD_HEIGHT-1][j] = pieces[1][j-gameInfo.holdingsWidth];
4684 if( (gameInfo.variant == VariantShogi) && !overrule ) {
4687 initialPosition[1][j] = WhiteBishop;
4688 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
4690 initialPosition[1][j] = WhiteRook;
4691 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
4694 if( nrCastlingRights == -1) {
4695 /* [HGM] Build normal castling rights (must be done after board sizing!) */
4696 /* This sets default castling rights from none to normal corners */
4697 /* Variants with other castling rights must set them themselves above */
4698 nrCastlingRights = 6;
4700 castlingRights[0][0] = initialRights[0] = BOARD_RGHT-1;
4701 castlingRights[0][1] = initialRights[1] = BOARD_LEFT;
4702 castlingRights[0][2] = initialRights[2] = BOARD_WIDTH>>1;
4703 castlingRights[0][3] = initialRights[3] = BOARD_RGHT-1;
4704 castlingRights[0][4] = initialRights[4] = BOARD_LEFT;
4705 castlingRights[0][5] = initialRights[5] = BOARD_WIDTH>>1;
4708 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
4709 if(gameInfo.variant == VariantGreat) { // promotion commoners
4710 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
4711 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
4712 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
4713 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
4716 if(gameInfo.variant == VariantFischeRandom) {
4717 if( appData.defaultFrcPosition < 0 ) {
4718 ShuffleFRC( initialPosition );
4721 SetupFRC( initialPosition, appData.defaultFrcPosition );
4723 startedFromSetupPosition = TRUE;
4726 if (appData.debugMode) {
4727 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
4729 if(shuffleOpenings) {
4730 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
4731 startedFromSetupPosition = TRUE;
4734 if(startedFromPositionFile) {
4735 /* [HGM] loadPos: use PositionFile for every new game */
4736 CopyBoard(initialPosition, filePosition);
4737 for(i=0; i<nrCastlingRights; i++)
4738 castlingRights[0][i] = initialRights[i] = fileRights[i];
4739 startedFromSetupPosition = TRUE;
4742 CopyBoard(boards[0], initialPosition);
4744 if(oldx != gameInfo.boardWidth ||
4745 oldy != gameInfo.boardHeight ||
4746 oldh != gameInfo.holdingsWidth
4748 || oldv == VariantGothic || // For licensing popups
4749 gameInfo.variant == VariantGothic
4752 || oldv == VariantFalcon ||
4753 gameInfo.variant == VariantFalcon
4756 InitDrawingSizes(-2 ,0);
4759 DrawPosition(TRUE, boards[currentMove]);
4763 SendBoard(cps, moveNum)
4764 ChessProgramState *cps;
4767 char message[MSG_SIZ];
4769 if (cps->useSetboard) {
4770 char* fen = PositionToFEN(moveNum, cps->fenOverride);
4771 sprintf(message, "setboard %s\n", fen);
4772 SendToProgram(message, cps);
4778 /* Kludge to set black to move, avoiding the troublesome and now
4779 * deprecated "black" command.
4781 if (!WhiteOnMove(moveNum)) SendToProgram("a2a3\n", cps);
4783 SendToProgram("edit\n", cps);
4784 SendToProgram("#\n", cps);
4785 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
4786 bp = &boards[moveNum][i][BOARD_LEFT];
4787 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
4788 if ((int) *bp < (int) BlackPawn) {
4789 sprintf(message, "%c%c%c\n", PieceToChar(*bp),
4791 if(message[0] == '+' || message[0] == '~') {
4792 sprintf(message, "%c%c%c+\n",
4793 PieceToChar((ChessSquare)(DEMOTED *bp)),
4796 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
4797 message[1] = BOARD_RGHT - 1 - j + '1';
4798 message[2] = BOARD_HEIGHT - 1 - i + 'a';
4800 SendToProgram(message, cps);
4805 SendToProgram("c\n", cps);
4806 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
4807 bp = &boards[moveNum][i][BOARD_LEFT];
4808 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
4809 if (((int) *bp != (int) EmptySquare)
4810 && ((int) *bp >= (int) BlackPawn)) {
4811 sprintf(message, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
4813 if(message[0] == '+' || message[0] == '~') {
4814 sprintf(message, "%c%c%c+\n",
4815 PieceToChar((ChessSquare)(DEMOTED *bp)),
4818 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
4819 message[1] = BOARD_RGHT - 1 - j + '1';
4820 message[2] = BOARD_HEIGHT - 1 - i + 'a';
4822 SendToProgram(message, cps);
4827 SendToProgram(".\n", cps);
4829 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
4833 IsPromotion(fromX, fromY, toX, toY)
4834 int fromX, fromY, toX, toY;
4836 /* [HGM] add Shogi promotions */
4837 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
4840 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi ||
4841 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) return FALSE;
4842 /* [HGM] Note to self: line above also weeds out drops */
4843 piece = boards[currentMove][fromY][fromX];
4844 if(gameInfo.variant == VariantShogi) {
4845 promotionZoneSize = 3;
4846 highestPromotingPiece = (int)WhiteKing;
4847 /* [HGM] Should be Silver = Ferz, really, but legality testing is off,
4848 and if in normal chess we then allow promotion to King, why not
4849 allow promotion of other piece in Shogi? */
4851 if((int)piece >= BlackPawn) {
4852 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
4854 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
4856 if( toY < BOARD_HEIGHT - promotionZoneSize &&
4857 fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
4859 return ( (int)piece <= highestPromotingPiece );
4863 InPalace(row, column)
4865 { /* [HGM] for Xiangqi */
4866 if( (row < 3 || row > BOARD_HEIGHT-4) &&
4867 column < (BOARD_WIDTH + 4)/2 &&
4868 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
4873 PieceForSquare (x, y)
4877 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
4880 return boards[currentMove][y][x];
4884 OKToStartUserMove(x, y)
4887 ChessSquare from_piece;
4890 if (matchMode) return FALSE;
4891 if (gameMode == EditPosition) return TRUE;
4893 if (x >= 0 && y >= 0)
4894 from_piece = boards[currentMove][y][x];
4896 from_piece = EmptySquare;
4898 if (from_piece == EmptySquare) return FALSE;
4900 white_piece = (int)from_piece >= (int)WhitePawn &&
4901 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
4904 case PlayFromGameFile:
4906 case TwoMachinesPlay:
4914 case MachinePlaysWhite:
4915 case IcsPlayingBlack:
4916 if (appData.zippyPlay) return FALSE;
4918 DisplayMoveError(_("You are playing Black"));
4923 case MachinePlaysBlack:
4924 case IcsPlayingWhite:
4925 if (appData.zippyPlay) return FALSE;
4927 DisplayMoveError(_("You are playing White"));
4933 if (!white_piece && WhiteOnMove(currentMove)) {
4934 DisplayMoveError(_("It is White's turn"));
4937 if (white_piece && !WhiteOnMove(currentMove)) {
4938 DisplayMoveError(_("It is Black's turn"));
4941 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
4942 /* Editing correspondence game history */
4943 /* Could disallow this or prompt for confirmation */
4946 if (currentMove < forwardMostMove) {
4947 /* Discarding moves */
4948 /* Could prompt for confirmation here,
4949 but I don't think that's such a good idea */
4950 forwardMostMove = currentMove;
4954 case BeginningOfGame:
4955 if (appData.icsActive) return FALSE;
4956 if (!appData.noChessProgram) {
4958 DisplayMoveError(_("You are playing White"));
4965 if (!white_piece && WhiteOnMove(currentMove)) {
4966 DisplayMoveError(_("It is White's turn"));
4969 if (white_piece && !WhiteOnMove(currentMove)) {
4970 DisplayMoveError(_("It is Black's turn"));
4979 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
4980 && gameMode != AnalyzeFile && gameMode != Training) {
4981 DisplayMoveError(_("Displayed position is not current"));
4987 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
4988 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
4989 int lastLoadGameUseList = FALSE;
4990 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
4991 ChessMove lastLoadGameStart = (ChessMove) 0;
4995 UserMoveTest(fromX, fromY, toX, toY, promoChar)
4996 int fromX, fromY, toX, toY;
5000 ChessSquare pdown, pup;
5002 if (fromX < 0 || fromY < 0) return ImpossibleMove;
5003 if ((fromX == toX) && (fromY == toY)) {
5004 return ImpossibleMove;
5007 /* [HGM] suppress all moves into holdings area and guard band */
5008 if( toX < BOARD_LEFT || toX >= BOARD_RGHT || toY < 0 )
5009 return ImpossibleMove;
5011 /* [HGM] <sameColor> moved to here from winboard.c */
5012 /* note: this code seems to exist for filtering out some obviously illegal premoves */
5013 pdown = boards[currentMove][fromY][fromX];
5014 pup = boards[currentMove][toY][toX];
5015 if ( gameMode != EditPosition &&
5016 (WhitePawn <= pdown && pdown < BlackPawn &&
5017 WhitePawn <= pup && pup < BlackPawn ||
5018 BlackPawn <= pdown && pdown < EmptySquare &&
5019 BlackPawn <= pup && pup < EmptySquare
5020 ) && !((gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) &&
5021 (pup == WhiteRook && pdown == WhiteKing && fromY == 0 && toY == 0||
5022 pup == BlackRook && pdown == BlackKing && fromY == BOARD_HEIGHT-1 && toY == BOARD_HEIGHT-1 )
5024 return ImpossibleMove;
5026 /* Check if the user is playing in turn. This is complicated because we
5027 let the user "pick up" a piece before it is his turn. So the piece he
5028 tried to pick up may have been captured by the time he puts it down!
5029 Therefore we use the color the user is supposed to be playing in this
5030 test, not the color of the piece that is currently on the starting
5031 square---except in EditGame mode, where the user is playing both
5032 sides; fortunately there the capture race can't happen. (It can
5033 now happen in IcsExamining mode, but that's just too bad. The user
5034 will get a somewhat confusing message in that case.)
5038 case PlayFromGameFile:
5040 case TwoMachinesPlay:
5044 /* We switched into a game mode where moves are not accepted,
5045 perhaps while the mouse button was down. */
5046 return ImpossibleMove;
5048 case MachinePlaysWhite:
5049 /* User is moving for Black */
5050 if (WhiteOnMove(currentMove)) {
5051 DisplayMoveError(_("It is White's turn"));
5052 return ImpossibleMove;
5056 case MachinePlaysBlack:
5057 /* User is moving for White */
5058 if (!WhiteOnMove(currentMove)) {
5059 DisplayMoveError(_("It is Black's turn"));
5060 return ImpossibleMove;
5066 case BeginningOfGame:
5069 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
5070 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
5071 /* User is moving for Black */
5072 if (WhiteOnMove(currentMove)) {
5073 DisplayMoveError(_("It is White's turn"));
5074 return ImpossibleMove;
5077 /* User is moving for White */
5078 if (!WhiteOnMove(currentMove)) {
5079 DisplayMoveError(_("It is Black's turn"));
5080 return ImpossibleMove;
5085 case IcsPlayingBlack:
5086 /* User is moving for Black */
5087 if (WhiteOnMove(currentMove)) {
5088 if (!appData.premove) {
5089 DisplayMoveError(_("It is White's turn"));
5090 } else if (toX >= 0 && toY >= 0) {
5093 premoveFromX = fromX;
5094 premoveFromY = fromY;
5095 premovePromoChar = promoChar;
5097 if (appData.debugMode)
5098 fprintf(debugFP, "Got premove: fromX %d,"
5099 "fromY %d, toX %d, toY %d\n",
5100 fromX, fromY, toX, toY);
5102 return ImpossibleMove;
5106 case IcsPlayingWhite:
5107 /* User is moving for White */
5108 if (!WhiteOnMove(currentMove)) {
5109 if (!appData.premove) {
5110 DisplayMoveError(_("It is Black's turn"));
5111 } else if (toX >= 0 && toY >= 0) {
5114 premoveFromX = fromX;
5115 premoveFromY = fromY;
5116 premovePromoChar = promoChar;
5118 if (appData.debugMode)
5119 fprintf(debugFP, "Got premove: fromX %d,"
5120 "fromY %d, toX %d, toY %d\n",
5121 fromX, fromY, toX, toY);
5123 return ImpossibleMove;
5131 /* EditPosition, empty square, or different color piece;
5132 click-click move is possible */
5133 if (toX == -2 || toY == -2) {
5134 boards[0][fromY][fromX] = EmptySquare;
5135 return AmbiguousMove;
5136 } else if (toX >= 0 && toY >= 0) {
5137 boards[0][toY][toX] = boards[0][fromY][fromX];
5138 boards[0][fromY][fromX] = EmptySquare;
5139 return AmbiguousMove;
5141 return ImpossibleMove;
5144 /* [HGM] If move started in holdings, it means a drop */
5145 if( fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) {
5146 if( pup != EmptySquare ) return ImpossibleMove;
5147 if(appData.testLegality) {
5148 /* it would be more logical if LegalityTest() also figured out
5149 * which drops are legal. For now we forbid pawns on back rank.
5150 * Shogi is on its own here...
5152 if( (pdown == WhitePawn || pdown == BlackPawn) &&
5153 (toY == 0 || toY == BOARD_HEIGHT -1 ) )
5154 return(ImpossibleMove); /* no pawn drops on 1st/8th */
5156 return WhiteDrop; /* Not needed to specify white or black yet */
5159 userOfferedDraw = FALSE;
5161 /* [HGM] always test for legality, to get promotion info */
5162 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
5163 epStatus[currentMove], castlingRights[currentMove],
5164 fromY, fromX, toY, toX, promoChar);
5166 /* [HGM] but possibly ignore an IllegalMove result */
5167 if (appData.testLegality) {
5168 if (moveType == IllegalMove || moveType == ImpossibleMove) {
5169 DisplayMoveError(_("Illegal move"));
5170 return ImpossibleMove;
5173 if(appData.debugMode) fprintf(debugFP, "moveType 3 = %d, promochar = %x\n", moveType, promoChar);
5175 /* [HGM] <popupFix> in stead of calling FinishMove directly, this
5176 function is made into one that returns an OK move type if FinishMove
5177 should be called. This to give the calling driver routine the
5178 opportunity to finish the userMove input with a promotion popup,
5179 without bothering the user with this for invalid or illegal moves */
5181 /* FinishMove(moveType, fromX, fromY, toX, toY, promoChar); */
5184 /* Common tail of UserMoveEvent and DropMenuEvent */
5186 FinishMove(moveType, fromX, fromY, toX, toY, promoChar)
5188 int fromX, fromY, toX, toY;
5189 /*char*/int promoChar;
5192 if(appData.debugMode) fprintf(debugFP, "moveType 5 = %d, promochar = %x\n", moveType, promoChar);
5193 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) && promoChar != NULLCHAR) {
5194 // [HGM] superchess: suppress promotions to non-available piece
5195 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
5196 if(WhiteOnMove(currentMove)) {
5197 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
5199 if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
5203 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
5204 move type in caller when we know the move is a legal promotion */
5205 if(moveType == NormalMove && promoChar)
5206 moveType = PromoCharToMoveType(WhiteOnMove(currentMove), promoChar);
5207 if(appData.debugMode) fprintf(debugFP, "moveType 1 = %d, promochar = %x\n", moveType, promoChar);
5208 /* [HGM] convert drag-and-drop piece drops to standard form */
5209 if( fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) {
5210 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
5211 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
5212 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
5213 // fromX = boards[currentMove][fromY][fromX];
5214 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
5215 if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
5216 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
5217 while(PieceToChar(fromX) == '.' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
5221 /* [HGM] <popupFix> The following if has been moved here from
5222 UserMoveEvent(). Because it seemed to belon here (why not allow
5223 piece drops in training games?), and because it can only be
5224 performed after it is known to what we promote. */
5225 if (gameMode == Training) {
5226 /* compare the move played on the board to the next move in the
5227 * game. If they match, display the move and the opponent's response.
5228 * If they don't match, display an error message.
5231 Board testBoard; char testRights[BOARD_SIZE]; char testStatus;
5232 CopyBoard(testBoard, boards[currentMove]);
5233 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard, testRights, &testStatus);
5235 if (CompareBoards(testBoard, boards[currentMove+1])) {
5236 ForwardInner(currentMove+1);
5238 /* Autoplay the opponent's response.
5239 * if appData.animate was TRUE when Training mode was entered,
5240 * the response will be animated.
5242 saveAnimate = appData.animate;
5243 appData.animate = animateTraining;
5244 ForwardInner(currentMove+1);
5245 appData.animate = saveAnimate;
5247 /* check for the end of the game */
5248 if (currentMove >= forwardMostMove) {
5249 gameMode = PlayFromGameFile;
5251 SetTrainingModeOff();
5252 DisplayInformation(_("End of game"));
5255 DisplayError(_("Incorrect move"), 0);
5260 /* Ok, now we know that the move is good, so we can kill
5261 the previous line in Analysis Mode */
5262 if (gameMode == AnalyzeMode && currentMove < forwardMostMove) {
5263 forwardMostMove = currentMove;
5266 /* If we need the chess program but it's dead, restart it */
5267 ResurrectChessProgram();
5269 /* A user move restarts a paused game*/
5273 thinkOutput[0] = NULLCHAR;
5275 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
5277 if (gameMode == BeginningOfGame) {
5278 if (appData.noChessProgram) {
5279 gameMode = EditGame;
5283 gameMode = MachinePlaysBlack;
5286 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
5288 if (first.sendName) {
5289 sprintf(buf, "name %s\n", gameInfo.white);
5290 SendToProgram(buf, &first);
5296 if(appData.debugMode) fprintf(debugFP, "moveType 2 = %d, promochar = %x\n", moveType, promoChar);
5297 /* Relay move to ICS or chess engine */
5298 if (appData.icsActive) {
5299 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
5300 gameMode == IcsExamining) {
5301 SendMoveToICS(moveType, fromX, fromY, toX, toY);
5305 if (first.sendTime && (gameMode == BeginningOfGame ||
5306 gameMode == MachinePlaysWhite ||
5307 gameMode == MachinePlaysBlack)) {
5308 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
5310 if (gameMode != EditGame && gameMode != PlayFromGameFile) {
5311 // [HGM] book: if program might be playing, let it use book
5312 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
5313 first.maybeThinking = TRUE;
5314 } else SendMoveToProgram(forwardMostMove-1, &first);
5315 if (currentMove == cmailOldMove + 1) {
5316 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
5320 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
5324 switch (MateTest(boards[currentMove], PosFlags(currentMove),
5325 EP_UNKNOWN, castlingRights[currentMove]) ) {
5331 if (WhiteOnMove(currentMove)) {
5332 GameEnds(BlackWins, "Black mates", GE_PLAYER);
5334 GameEnds(WhiteWins, "White mates", GE_PLAYER);
5338 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
5343 case MachinePlaysBlack:
5344 case MachinePlaysWhite:
5345 /* disable certain menu options while machine is thinking */
5346 SetMachineThinkingEnables();
5353 if(bookHit) { // [HGM] book: simulate book reply
5354 static char bookMove[MSG_SIZ]; // a bit generous?
5356 programStats.nodes = programStats.depth = programStats.time =
5357 programStats.score = programStats.got_only_move = 0;
5358 sprintf(programStats.movelist, "%s (xbook)", bookHit);
5360 strcpy(bookMove, "move ");
5361 strcat(bookMove, bookHit);
5362 HandleMachineMove(bookMove, &first);
5368 UserMoveEvent(fromX, fromY, toX, toY, promoChar)
5369 int fromX, fromY, toX, toY;
5372 /* [HGM] This routine was added to allow calling of its two logical
5373 parts from other modules in the old way. Before, UserMoveEvent()
5374 automatically called FinishMove() if the move was OK, and returned
5375 otherwise. I separated the two, in order to make it possible to
5376 slip a promotion popup in between. But that it always needs two
5377 calls, to the first part, (now called UserMoveTest() ), and to
5378 FinishMove if the first part succeeded. Calls that do not need
5379 to do anything in between, can call this routine the old way.
5381 ChessMove moveType = UserMoveTest(fromX, fromY, toX, toY, promoChar);
5382 if(appData.debugMode) fprintf(debugFP, "moveType 4 = %d, promochar = %x\n", moveType, promoChar);
5383 if(moveType != ImpossibleMove)
5384 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
5387 void SendProgramStatsToFrontend( ChessProgramState * cps, ChessProgramStats * cpstats )
5389 // char * hint = lastHint;
5390 FrontEndProgramStats stats;
5392 stats.which = cps == &first ? 0 : 1;
5393 stats.depth = cpstats->depth;
5394 stats.nodes = cpstats->nodes;
5395 stats.score = cpstats->score;
5396 stats.time = cpstats->time;
5397 stats.pv = cpstats->movelist;
5398 stats.hint = lastHint;
5399 stats.an_move_index = 0;
5400 stats.an_move_count = 0;
5402 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
5403 stats.hint = cpstats->move_name;
5404 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
5405 stats.an_move_count = cpstats->nr_moves;
5408 SetProgramStats( &stats );
5411 char *SendMoveToBookUser(int moveNr, ChessProgramState *cps, int initial)
5412 { // [HGM] book: this routine intercepts moves to simulate book replies
5413 char *bookHit = NULL;
5415 //first determine if the incoming move brings opponent into his book
5416 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
5417 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
5418 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
5419 if(bookHit != NULL && !cps->bookSuspend) {
5420 // make sure opponent is not going to reply after receiving move to book position
5421 SendToProgram("force\n", cps);
5422 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
5424 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
5425 // now arrange restart after book miss
5427 // after a book hit we never send 'go', and the code after the call to this routine
5428 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
5430 if (cps->useUsermove) sprintf(buf, "usermove "); // sorry, no SAN yet :(
5431 sprintf(buf, "%s\n", bookHit); // force book move into program supposed to play it
5432 SendToProgram(buf, cps);
5433 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
5434 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
5435 SendToProgram("go\n", cps);
5436 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
5437 } else { // 'go' might be sent based on 'firstMove' after this routine returns
5438 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
5439 SendToProgram("go\n", cps);
5440 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
5442 return bookHit; // notify caller of hit, so it can take action to send move to opponent
5446 ChessProgramState *savedState;
5447 void DeferredBookMove(void)
5449 if(savedState->lastPing != savedState->lastPong)
5450 ScheduleDelayedEvent(DeferredBookMove, 10);
5452 HandleMachineMove(savedMessage, savedState);
5456 HandleMachineMove(message, cps)
5458 ChessProgramState *cps;
5460 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
5461 char realname[MSG_SIZ];
5462 int fromX, fromY, toX, toY;
5469 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
5471 * Kludge to ignore BEL characters
5473 while (*message == '\007') message++;
5476 * [HGM] engine debug message: ignore lines starting with '#' character
5478 if(cps->debug && *message == '#') return;
5481 * Look for book output
5483 if (cps == &first && bookRequested) {
5484 if (message[0] == '\t' || message[0] == ' ') {
5485 /* Part of the book output is here; append it */
5486 strcat(bookOutput, message);
5487 strcat(bookOutput, " \n");
5489 } else if (bookOutput[0] != NULLCHAR) {
5490 /* All of book output has arrived; display it */
5491 char *p = bookOutput;
5492 while (*p != NULLCHAR) {
5493 if (*p == '\t') *p = ' ';
5496 DisplayInformation(bookOutput);
5497 bookRequested = FALSE;
5498 /* Fall through to parse the current output */
5503 * Look for machine move.
5505 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
5506 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
5508 /* This method is only useful on engines that support ping */
5509 if (cps->lastPing != cps->lastPong) {
5510 if (gameMode == BeginningOfGame) {
5511 /* Extra move from before last new; ignore */
5512 if (appData.debugMode) {
5513 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
5516 if (appData.debugMode) {
5517 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
5518 cps->which, gameMode);
5521 SendToProgram("undo\n", cps);
5527 case BeginningOfGame:
5528 /* Extra move from before last reset; ignore */
5529 if (appData.debugMode) {
5530 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
5537 /* Extra move after we tried to stop. The mode test is
5538 not a reliable way of detecting this problem, but it's
5539 the best we can do on engines that don't support ping.
5541 if (appData.debugMode) {
5542 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
5543 cps->which, gameMode);
5545 SendToProgram("undo\n", cps);
5548 case MachinePlaysWhite:
5549 case IcsPlayingWhite:
5550 machineWhite = TRUE;
5553 case MachinePlaysBlack:
5554 case IcsPlayingBlack:
5555 machineWhite = FALSE;
5558 case TwoMachinesPlay:
5559 machineWhite = (cps->twoMachinesColor[0] == 'w');
5562 if (WhiteOnMove(forwardMostMove) != machineWhite) {
5563 if (appData.debugMode) {
5565 "Ignoring move out of turn by %s, gameMode %d"
5566 ", forwardMost %d\n",
5567 cps->which, gameMode, forwardMostMove);
5572 if (appData.debugMode) { int f = forwardMostMove;
5573 fprintf(debugFP, "machine move %d, castling = %d %d %d %d %d %d\n", f,
5574 castlingRights[f][0],castlingRights[f][1],castlingRights[f][2],castlingRights[f][3],castlingRights[f][4],castlingRights[f][5]);
5576 if(cps->alphaRank) AlphaRank(machineMove, 4);
5577 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
5578 &fromX, &fromY, &toX, &toY, &promoChar)) {
5579 /* Machine move could not be parsed; ignore it. */
5580 sprintf(buf1, _("Illegal move \"%s\" from %s machine"),
5581 machineMove, cps->which);
5582 DisplayError(buf1, 0);
5583 sprintf(buf1, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
5584 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType);
5585 if (gameMode == TwoMachinesPlay) {
5586 GameEnds(machineWhite ? BlackWins : WhiteWins,
5592 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
5593 /* So we have to redo legality test with true e.p. status here, */
5594 /* to make sure an illegal e.p. capture does not slip through, */
5595 /* to cause a forfeit on a justified illegal-move complaint */
5596 /* of the opponent. */
5597 if( gameMode==TwoMachinesPlay && appData.testLegality
5598 && fromY != DROP_RANK /* [HGM] temporary; should still add legality test for drops */
5601 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
5602 epStatus[forwardMostMove], castlingRights[forwardMostMove],
5603 fromY, fromX, toY, toX, promoChar);
5604 if (appData.debugMode) {
5606 for(i=0; i< nrCastlingRights; i++) fprintf(debugFP, "(%d,%d) ",
5607 castlingRights[forwardMostMove][i], castlingRank[i]);
5608 fprintf(debugFP, "castling rights\n");
5610 if(moveType == IllegalMove) {
5611 sprintf(buf1, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
5612 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
5613 GameEnds(machineWhite ? BlackWins : WhiteWins,
5616 } else if(gameInfo.variant != VariantFischeRandom && gameInfo.variant != VariantCapaRandom)
5617 /* [HGM] Kludge to handle engines that send FRC-style castling
5618 when they shouldn't (like TSCP-Gothic) */
5620 case WhiteASideCastleFR:
5621 case BlackASideCastleFR:
5623 currentMoveString[2]++;
5625 case WhiteHSideCastleFR:
5626 case BlackHSideCastleFR:
5628 currentMoveString[2]--;
5630 default: ; // nothing to do, but suppresses warning of pedantic compilers
5633 hintRequested = FALSE;
5634 lastHint[0] = NULLCHAR;
5635 bookRequested = FALSE;
5636 /* Program may be pondering now */
5637 cps->maybeThinking = TRUE;
5638 if (cps->sendTime == 2) cps->sendTime = 1;
5639 if (cps->offeredDraw) cps->offeredDraw--;
5642 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
5644 SendMoveToICS(moveType, fromX, fromY, toX, toY);
5646 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
5647 char buf[3*MSG_SIZ];
5649 sprintf(buf, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %1.0f knps) PV=%s\n",
5650 programStats.score / 100.,
5652 programStats.time / 100.,
5653 (unsigned int)programStats.nodes,
5654 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
5655 programStats.movelist);
5660 /* currentMoveString is set as a side-effect of ParseOneMove */
5661 strcpy(machineMove, currentMoveString);
5662 strcat(machineMove, "\n");
5663 strcpy(moveList[forwardMostMove], machineMove);
5665 /* [AS] Save move info and clear stats for next move */
5666 pvInfoList[ forwardMostMove ].score = programStats.score;
5667 pvInfoList[ forwardMostMove ].depth = programStats.depth;
5668 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
5669 ClearProgramStats();
5670 thinkOutput[0] = NULLCHAR;
5671 hiddenThinkOutputState = 0;
5673 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
5675 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
5676 if( gameMode == TwoMachinesPlay && adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
5679 while( count < adjudicateLossPlies ) {
5680 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
5683 score = -score; /* Flip score for winning side */
5686 if( score > adjudicateLossThreshold ) {
5693 if( count >= adjudicateLossPlies ) {
5694 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
5696 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
5697 "Xboard adjudication",
5704 if( gameMode == TwoMachinesPlay ) {
5705 // [HGM] some adjudications useful with buggy engines
5706 int k, count = 0, epFile = epStatus[forwardMostMove]; static int bare = 1;
5707 if(gameInfo.holdingsSize == 0 || gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
5710 if( appData.testLegality )
5711 { /* [HGM] Some more adjudications for obstinate engines */
5712 int NrWN=0, NrBN=0, NrWB=0, NrBB=0, NrWR=0, NrBR=0,
5713 NrWQ=0, NrBQ=0, NrW=0, NrK=0, bishopsColor = 0,
5714 NrPieces=0, NrPawns=0, PawnAdvance=0, i, j;
5715 static int moveCount = 6;
5717 char *reason = NULL;
5719 /* Count what is on board. */
5720 for(i=0; i<BOARD_HEIGHT; i++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
5721 { ChessSquare p = boards[forwardMostMove][i][j];
5725 { /* count B,N,R and other of each side */
5728 NrK++; break; // [HGM] atomic: count Kings
5732 case WhiteFerz: // [HGM] shatranj: kludge to mke it work in shatranj
5733 bishopsColor |= 1 << ((i^j)&1);
5738 case BlackFerz: // [HGM] shatranj: kludge to mke it work in shatranj
5739 bishopsColor |= 1 << ((i^j)&1);
5754 PawnAdvance += m; NrPawns++;
5756 NrPieces += (p != EmptySquare);
5757 NrW += ((int)p < (int)BlackPawn);
5758 if(gameInfo.variant == VariantXiangqi &&
5759 (p == WhiteFerz || p == WhiteAlfil || p == BlackFerz || p == BlackAlfil)) {
5760 NrPieces--; // [HGM] XQ: do not count purely defensive pieces
5761 NrW -= ((int)p < (int)BlackPawn);
5765 /* Some material-based adjudications that have to be made before stalemate test */
5766 if(gameInfo.variant == VariantAtomic && NrK < 2) {
5767 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
5768 epStatus[forwardMostMove] = EP_CHECKMATE; // make claimable as if stm is checkmated
5769 if(appData.checkMates) {
5770 SendMoveToProgram(forwardMostMove-1, cps->other); // make sure opponent gets move
5771 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
5772 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
5773 "Xboard adjudication: King destroyed", GE_XBOARD );
5778 /* Bare King in Shatranj (loses) or Losers (wins) */
5779 if( NrW == 1 || NrPieces - NrW == 1) {
5780 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
5781 epStatus[forwardMostMove] = EP_WINS; // mark as win, so it becomes claimable
5782 if(appData.checkMates) {
5783 SendMoveToProgram(forwardMostMove-1, cps->other); // make sure opponent gets to see move
5784 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
5785 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
5786 "Xboard adjudication: Bare king", GE_XBOARD );
5790 if( gameInfo.variant == VariantShatranj && --bare < 0)
5792 epStatus[forwardMostMove] = EP_WINS; // make claimable as win for stm
5793 if(appData.checkMates) {
5794 /* but only adjudicate if adjudication enabled */
5795 SendMoveToProgram(forwardMostMove-1, cps->other); // make sure opponent gets move
5796 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
5797 GameEnds( NrW > 1 ? WhiteWins : NrPieces - NrW > 1 ? BlackWins : GameIsDrawn,
5798 "Xboard adjudication: Bare king", GE_XBOARD );
5805 // don't wait for engine to announce game end if we can judge ourselves
5806 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove), epFile,
5807 castlingRights[forwardMostMove]) ) {
5809 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
5810 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
5811 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
5812 if(MateTest(boards[i], PosFlags(i), epStatus[i], castlingRights[i]) == MT_CHECK)
5815 reason = "Xboard adjudication: 3rd check";
5816 epStatus[forwardMostMove] = EP_CHECKMATE;
5826 reason = "Xboard adjudication: Stalemate";
5827 if(epStatus[forwardMostMove] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
5828 epStatus[forwardMostMove] = EP_STALEMATE; // default result for stalemate is draw
5829 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
5830 epStatus[forwardMostMove] = EP_WINS; // in these variants stalemated is always a win
5831 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
5832 epStatus[forwardMostMove] = NrW == NrPieces-NrW ? EP_STALEMATE :
5833 ((NrW < NrPieces-NrW) != WhiteOnMove(forwardMostMove) ?
5834 EP_CHECKMATE : EP_WINS);
5835 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi)
5836 epStatus[forwardMostMove] = EP_CHECKMATE; // and in these variants being stalemated loses
5840 reason = "Xboard adjudication: Checkmate";
5841 epStatus[forwardMostMove] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
5845 switch(i = epStatus[forwardMostMove]) {
5847 result = GameIsDrawn; break;
5849 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
5851 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
5853 result = (ChessMove) 0;
5855 if(appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
5856 SendMoveToProgram(forwardMostMove-1, cps->other); /* make sure opponent gets to see move */
5857 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
5858 GameEnds( result, reason, GE_XBOARD );
5862 /* Next absolutely insufficient mating material. */
5863 if( NrPieces == 2 || gameInfo.variant != VariantXiangqi &&
5864 gameInfo.variant != VariantShatranj && // [HGM] baring will remain possible
5865 (NrPieces == 3 && NrWN+NrBN+NrWB+NrBB == 1 ||
5866 NrPieces == NrBB+NrWB+2 && bishopsColor != 3)) // [HGM] all Bishops (Ferz!) same color
5867 { /* KBK, KNK, KK of KBKB with like Bishops */
5869 /* always flag draws, for judging claims */
5870 epStatus[forwardMostMove] = EP_INSUF_DRAW;
5872 if(appData.materialDraws) {
5873 /* but only adjudicate them if adjudication enabled */
5874 SendToProgram("force\n", cps->other); // suppress reply
5875 SendMoveToProgram(forwardMostMove-1, cps->other); /* make sure opponent gets to see last move */
5876 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
5877 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
5882 /* Then some trivial draws (only adjudicate, cannot be claimed) */
5884 ( NrWR == 1 && NrBR == 1 /* KRKR */
5885 || NrWQ==1 && NrBQ==1 /* KQKQ */
5886 || NrWN==2 || NrBN==2 /* KNNK */
5887 || NrWN+NrWB == 1 && NrBN+NrBB == 1 /* KBKN, KBKB, KNKN */
5889 if(--moveCount < 0 && appData.trivialDraws)
5890 { /* if the first 3 moves do not show a tactical win, declare draw */
5891 SendToProgram("force\n", cps->other); // suppress reply
5892 SendMoveToProgram(forwardMostMove-1, cps->other); /* make sure opponent gets to see move */
5893 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
5894 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
5897 } else moveCount = 6;
5901 if (appData.debugMode) { int i;
5902 fprintf(debugFP, "repeat test fmm=%d bmm=%d ep=%d, reps=%d\n",
5903 forwardMostMove, backwardMostMove, epStatus[backwardMostMove],
5904 appData.drawRepeats);
5905 for( i=forwardMostMove; i>=backwardMostMove; i-- )
5906 fprintf(debugFP, "%d ep=%d\n", i, epStatus[i]);
5910 /* Check for rep-draws */
5912 for(k = forwardMostMove-2;
5913 k>=backwardMostMove && k>=forwardMostMove-100 &&
5914 epStatus[k] < EP_UNKNOWN &&
5915 epStatus[k+2] <= EP_NONE && epStatus[k+1] <= EP_NONE;
5919 if (appData.debugMode) {
5920 fprintf(debugFP, " loop\n");
5923 if(CompareBoards(boards[k], boards[forwardMostMove])) {
5925 if (appData.debugMode) {
5926 fprintf(debugFP, "match\n");
5929 /* compare castling rights */
5930 if( castlingRights[forwardMostMove][2] != castlingRights[k][2] &&
5931 (castlingRights[k][0] >= 0 || castlingRights[k][1] >= 0) )
5932 rights++; /* King lost rights, while rook still had them */
5933 if( castlingRights[forwardMostMove][2] >= 0 ) { /* king has rights */
5934 if( castlingRights[forwardMostMove][0] != castlingRights[k][0] ||
5935 castlingRights[forwardMostMove][1] != castlingRights[k][1] )
5936 rights++; /* but at least one rook lost them */
5938 if( castlingRights[forwardMostMove][5] != castlingRights[k][5] &&
5939 (castlingRights[k][3] >= 0 || castlingRights[k][4] >= 0) )
5941 if( castlingRights[forwardMostMove][5] >= 0 ) {
5942 if( castlingRights[forwardMostMove][3] != castlingRights[k][3] ||
5943 castlingRights[forwardMostMove][4] != castlingRights[k][4] )
5947 if (appData.debugMode) {
5948 for(i=0; i<nrCastlingRights; i++)
5949 fprintf(debugFP, " (%d,%d)", castlingRights[forwardMostMove][i], castlingRights[k][i]);
5952 if (appData.debugMode) {
5953 fprintf(debugFP, " %d %d\n", rights, k);
5956 if( rights == 0 && ++count > appData.drawRepeats-2
5957 && appData.drawRepeats > 1) {
5958 /* adjudicate after user-specified nr of repeats */
5959 SendToProgram("force\n", cps->other); // suppress reply
5960 SendMoveToProgram(forwardMostMove-1, cps->other); /* make sure opponent gets to see move */
5961 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
5962 if(gameInfo.variant == VariantXiangqi && appData.testLegality) {
5963 // [HGM] xiangqi: check for forbidden perpetuals
5964 int m, ourPerpetual = 1, hisPerpetual = 1;
5965 for(m=forwardMostMove; m>k; m-=2) {
5966 if(MateTest(boards[m], PosFlags(m),
5967 EP_NONE, castlingRights[m]) != MT_CHECK)
5968 ourPerpetual = 0; // the current mover did not always check
5969 if(MateTest(boards[m-1], PosFlags(m-1),
5970 EP_NONE, castlingRights[m-1]) != MT_CHECK)
5971 hisPerpetual = 0; // the opponent did not always check
5973 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
5974 ourPerpetual, hisPerpetual);
5975 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
5976 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
5977 "Xboard adjudication: perpetual checking", GE_XBOARD );
5980 if(hisPerpetual && !ourPerpetual) // he is checking us, but did not repeat yet
5981 break; // (or we would have caught him before). Abort repetition-checking loop.
5982 // Now check for perpetual chases
5983 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
5984 hisPerpetual = PerpetualChase(k, forwardMostMove);
5985 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
5986 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
5987 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
5988 "Xboard adjudication: perpetual chasing", GE_XBOARD );
5991 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
5992 break; // Abort repetition-checking loop.
5994 // if neither of us is checking or chasing all the time, or both are, it is draw
5996 GameEnds( GameIsDrawn, "Xboard adjudication: repetition draw", GE_XBOARD );
5999 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
6000 epStatus[forwardMostMove] = EP_REP_DRAW;
6004 /* Now we test for 50-move draws. Determine ply count */
6005 count = forwardMostMove;
6006 /* look for last irreversble move */
6007 while( epStatus[count] <= EP_NONE && count > backwardMostMove )
6009 /* if we hit starting position, add initial plies */
6010 if( count == backwardMostMove )
6011 count -= initialRulePlies;
6012 count = forwardMostMove - count;
6014 epStatus[forwardMostMove] = EP_RULE_DRAW;
6015 /* this is used to judge if draw claims are legal */
6016 if(appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
6017 SendToProgram("force\n", cps->other); // suppress reply
6018 SendMoveToProgram(forwardMostMove-1, cps->other); /* make sure opponent gets to see move */
6019 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6020 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
6024 /* if draw offer is pending, treat it as a draw claim
6025 * when draw condition present, to allow engines a way to
6026 * claim draws before making their move to avoid a race
6027 * condition occurring after their move
6029 if( cps->other->offeredDraw || cps->offeredDraw ) {
6031 if(epStatus[forwardMostMove] == EP_RULE_DRAW)
6032 p = "Draw claim: 50-move rule";
6033 if(epStatus[forwardMostMove] == EP_REP_DRAW)
6034 p = "Draw claim: 3-fold repetition";
6035 if(epStatus[forwardMostMove] == EP_INSUF_DRAW)
6036 p = "Draw claim: insufficient mating material";
6038 SendToProgram("force\n", cps->other); // suppress reply
6039 SendMoveToProgram(forwardMostMove-1, cps->other); /* make sure opponent gets to see move */
6040 GameEnds( GameIsDrawn, p, GE_XBOARD );
6041 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6047 if( appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
6048 SendToProgram("force\n", cps->other); // suppress reply
6049 SendMoveToProgram(forwardMostMove-1, cps->other); /* make sure opponent gets to see move */
6050 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6052 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
6059 if (gameMode == TwoMachinesPlay) {
6060 /* [HGM] relaying draw offers moved to after reception of move */
6061 /* and interpreting offer as claim if it brings draw condition */
6062 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
6063 SendToProgram("draw\n", cps->other);
6065 if (cps->other->sendTime) {
6066 SendTimeRemaining(cps->other,
6067 cps->other->twoMachinesColor[0] == 'w');
6069 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
6070 if (firstMove && !bookHit) {
6072 if (cps->other->useColors) {
6073 SendToProgram(cps->other->twoMachinesColor, cps->other);
6075 SendToProgram("go\n", cps->other);
6077 cps->other->maybeThinking = TRUE;
6080 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6082 if (!pausing && appData.ringBellAfterMoves) {
6087 * Reenable menu items that were disabled while
6088 * machine was thinking
6090 if (gameMode != TwoMachinesPlay)
6091 SetUserThinkingEnables();
6093 // [HGM] book: after book hit opponent has received move and is now in force mode
6094 // force the book reply into it, and then fake that it outputted this move by jumping
6095 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
6097 static char bookMove[MSG_SIZ]; // a bit generous?
6099 strcpy(bookMove, "move ");
6100 strcat(bookMove, bookHit);
6103 programStats.nodes = programStats.depth = programStats.time =
6104 programStats.score = programStats.got_only_move = 0;
6105 sprintf(programStats.movelist, "%s (xbook)", bookHit);
6107 if(cps->lastPing != cps->lastPong) {
6108 savedMessage = message; // args for deferred call
6110 ScheduleDelayedEvent(DeferredBookMove, 10);
6119 /* Set special modes for chess engines. Later something general
6120 * could be added here; for now there is just one kludge feature,
6121 * needed because Crafty 15.10 and earlier don't ignore SIGINT
6122 * when "xboard" is given as an interactive command.
6124 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
6125 cps->useSigint = FALSE;
6126 cps->useSigterm = FALSE;
6128 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
6129 ParseFeatures(message+8, cps);
6130 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
6133 /* [HGM] Allow engine to set up a position. Don't ask me why one would
6134 * want this, I was asked to put it in, and obliged.
6136 if (!strncmp(message, "setboard ", 9)) {
6137 Board initial_position; int i;
6139 GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
6141 if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9)) {
6142 DisplayError(_("Bad FEN received from engine"), 0);
6145 Reset(FALSE, FALSE);
6146 CopyBoard(boards[0], initial_position);
6147 initialRulePlies = FENrulePlies;
6148 epStatus[0] = FENepStatus;
6149 for( i=0; i<nrCastlingRights; i++ )
6150 castlingRights[0][i] = FENcastlingRights[i];
6151 if(blackPlaysFirst) gameMode = MachinePlaysWhite;
6152 else gameMode = MachinePlaysBlack;
6153 DrawPosition(FALSE, boards[currentMove]);
6159 * Look for communication commands
6161 if (!strncmp(message, "telluser ", 9)) {
6162 DisplayNote(message + 9);
6165 if (!strncmp(message, "tellusererror ", 14)) {
6166 DisplayError(message + 14, 0);
6169 if (!strncmp(message, "tellopponent ", 13)) {
6170 if (appData.icsActive) {
6172 snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
6176 DisplayNote(message + 13);
6180 if (!strncmp(message, "tellothers ", 11)) {
6181 if (appData.icsActive) {
6183 snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
6189 if (!strncmp(message, "tellall ", 8)) {
6190 if (appData.icsActive) {
6192 snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
6196 DisplayNote(message + 8);
6200 if (strncmp(message, "warning", 7) == 0) {
6201 /* Undocumented feature, use tellusererror in new code */
6202 DisplayError(message, 0);
6205 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
6206 strcpy(realname, cps->tidy);
6207 strcat(realname, " query");
6208 AskQuestion(realname, buf2, buf1, cps->pr);
6211 /* Commands from the engine directly to ICS. We don't allow these to be
6212 * sent until we are logged on. Crafty kibitzes have been known to
6213 * interfere with the login process.
6216 if (!strncmp(message, "tellics ", 8)) {
6217 SendToICS(message + 8);
6221 if (!strncmp(message, "tellicsnoalias ", 15)) {
6222 SendToICS(ics_prefix);
6223 SendToICS(message + 15);
6227 /* The following are for backward compatibility only */
6228 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
6229 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
6230 SendToICS(ics_prefix);
6236 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
6240 * If the move is illegal, cancel it and redraw the board.
6241 * Also deal with other error cases. Matching is rather loose
6242 * here to accommodate engines written before the spec.
6244 if (strncmp(message + 1, "llegal move", 11) == 0 ||
6245 strncmp(message, "Error", 5) == 0) {
6246 if (StrStr(message, "name") ||
6247 StrStr(message, "rating") || StrStr(message, "?") ||
6248 StrStr(message, "result") || StrStr(message, "board") ||
6249 StrStr(message, "bk") || StrStr(message, "computer") ||
6250 StrStr(message, "variant") || StrStr(message, "hint") ||
6251 StrStr(message, "random") || StrStr(message, "depth") ||
6252 StrStr(message, "accepted")) {
6255 if (StrStr(message, "protover")) {
6256 /* Program is responding to input, so it's apparently done
6257 initializing, and this error message indicates it is
6258 protocol version 1. So we don't need to wait any longer
6259 for it to initialize and send feature commands. */
6260 FeatureDone(cps, 1);
6261 cps->protocolVersion = 1;
6264 cps->maybeThinking = FALSE;
6266 if (StrStr(message, "draw")) {
6267 /* Program doesn't have "draw" command */
6268 cps->sendDrawOffers = 0;
6271 if (cps->sendTime != 1 &&
6272 (StrStr(message, "time") || StrStr(message, "otim"))) {
6273 /* Program apparently doesn't have "time" or "otim" command */
6277 if (StrStr(message, "analyze")) {
6278 cps->analysisSupport = FALSE;
6279 cps->analyzing = FALSE;
6281 sprintf(buf2, _("%s does not support analysis"), cps->tidy);
6282 DisplayError(buf2, 0);
6285 if (StrStr(message, "(no matching move)st")) {
6286 /* Special kludge for GNU Chess 4 only */
6287 cps->stKludge = TRUE;
6288 SendTimeControl(cps, movesPerSession, timeControl,
6289 timeIncrement, appData.searchDepth,
6293 if (StrStr(message, "(no matching move)sd")) {
6294 /* Special kludge for GNU Chess 4 only */
6295 cps->sdKludge = TRUE;
6296 SendTimeControl(cps, movesPerSession, timeControl,
6297 timeIncrement, appData.searchDepth,
6301 if (!StrStr(message, "llegal")) {
6304 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
6305 gameMode == IcsIdle) return;
6306 if (forwardMostMove <= backwardMostMove) return;
6308 /* Following removed: it caused a bug where a real illegal move
6309 message in analyze mored would be ignored. */
6310 if (cps == &first && programStats.ok_to_send == 0) {
6311 /* Bogus message from Crafty responding to "." This filtering
6312 can miss some of the bad messages, but fortunately the bug
6313 is fixed in current Crafty versions, so it doesn't matter. */
6317 if (pausing) PauseEvent();
6318 if (gameMode == PlayFromGameFile) {
6319 /* Stop reading this game file */
6320 gameMode = EditGame;
6323 currentMove = --forwardMostMove;
6324 DisplayMove(currentMove-1); /* before DisplayMoveError */
6326 DisplayBothClocks();
6327 sprintf(buf1, _("Illegal move \"%s\" (rejected by %s chess program)"),
6328 parseList[currentMove], cps->which);
6329 DisplayMoveError(buf1);
6330 DrawPosition(FALSE, boards[currentMove]);
6332 /* [HGM] illegal-move claim should forfeit game when Xboard */
6333 /* only passes fully legal moves */
6334 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
6335 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
6336 "False illegal-move claim", GE_XBOARD );
6340 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
6341 /* Program has a broken "time" command that
6342 outputs a string not ending in newline.
6348 * If chess program startup fails, exit with an error message.
6349 * Attempts to recover here are futile.
6351 if ((StrStr(message, "unknown host") != NULL)
6352 || (StrStr(message, "No remote directory") != NULL)
6353 || (StrStr(message, "not found") != NULL)
6354 || (StrStr(message, "No such file") != NULL)
6355 || (StrStr(message, "can't alloc") != NULL)
6356 || (StrStr(message, "Permission denied") != NULL)) {
6358 cps->maybeThinking = FALSE;
6359 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
6360 cps->which, cps->program, cps->host, message);
6361 RemoveInputSource(cps->isr);
6362 DisplayFatalError(buf1, 0, 1);
6367 * Look for hint output
6369 if (sscanf(message, "Hint: %s", buf1) == 1) {
6370 if (cps == &first && hintRequested) {
6371 hintRequested = FALSE;
6372 if (ParseOneMove(buf1, forwardMostMove, &moveType,
6373 &fromX, &fromY, &toX, &toY, &promoChar)) {
6374 (void) CoordsToAlgebraic(boards[forwardMostMove],
6375 PosFlags(forwardMostMove), EP_UNKNOWN,
6376 fromY, fromX, toY, toX, promoChar, buf1);
6377 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
6378 DisplayInformation(buf2);
6380 /* Hint move could not be parsed!? */
6381 snprintf(buf2, sizeof(buf2),
6382 _("Illegal hint move \"%s\"\nfrom %s chess program"),
6384 DisplayError(buf2, 0);
6387 strcpy(lastHint, buf1);
6393 * Ignore other messages if game is not in progress
6395 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
6396 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
6399 * look for win, lose, draw, or draw offer
6401 if (strncmp(message, "1-0", 3) == 0) {
6402 char *p, *q, *r = "";
6403 p = strchr(message, '{');
6411 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
6413 } else if (strncmp(message, "0-1", 3) == 0) {
6414 char *p, *q, *r = "";
6415 p = strchr(message, '{');
6423 /* Kludge for Arasan 4.1 bug */
6424 if (strcmp(r, "Black resigns") == 0) {
6425 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
6428 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
6430 } else if (strncmp(message, "1/2", 3) == 0) {
6431 char *p, *q, *r = "";
6432 p = strchr(message, '{');
6441 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
6444 } else if (strncmp(message, "White resign", 12) == 0) {
6445 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
6447 } else if (strncmp(message, "Black resign", 12) == 0) {
6448 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
6450 } else if (strncmp(message, "White matches", 13) == 0 ||
6451 strncmp(message, "Black matches", 13) == 0 ) {
6452 /* [HGM] ignore GNUShogi noises */
6454 } else if (strncmp(message, "White", 5) == 0 &&
6455 message[5] != '(' &&
6456 StrStr(message, "Black") == NULL) {
6457 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
6459 } else if (strncmp(message, "Black", 5) == 0 &&
6460 message[5] != '(') {
6461 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
6463 } else if (strcmp(message, "resign") == 0 ||
6464 strcmp(message, "computer resigns") == 0) {
6466 case MachinePlaysBlack:
6467 case IcsPlayingBlack:
6468 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
6470 case MachinePlaysWhite:
6471 case IcsPlayingWhite:
6472 GameEnds(BlackWins, "White resigns", GE_ENGINE);
6474 case TwoMachinesPlay:
6475 if (cps->twoMachinesColor[0] == 'w')
6476 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
6478 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
6485 } else if (strncmp(message, "opponent mates", 14) == 0) {
6487 case MachinePlaysBlack:
6488 case IcsPlayingBlack:
6489 GameEnds(WhiteWins, "White mates", GE_ENGINE);
6491 case MachinePlaysWhite:
6492 case IcsPlayingWhite:
6493 GameEnds(BlackWins, "Black mates", GE_ENGINE);
6495 case TwoMachinesPlay:
6496 if (cps->twoMachinesColor[0] == 'w')
6497 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
6499 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
6506 } else if (strncmp(message, "computer mates", 14) == 0) {
6508 case MachinePlaysBlack:
6509 case IcsPlayingBlack:
6510 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
6512 case MachinePlaysWhite:
6513 case IcsPlayingWhite:
6514 GameEnds(WhiteWins, "White mates", GE_ENGINE);
6516 case TwoMachinesPlay:
6517 if (cps->twoMachinesColor[0] == 'w')
6518 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
6520 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
6527 } else if (strncmp(message, "checkmate", 9) == 0) {
6528 if (WhiteOnMove(forwardMostMove)) {
6529 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
6531 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
6534 } else if (strstr(message, "Draw") != NULL ||
6535 strstr(message, "game is a draw") != NULL) {
6536 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
6538 } else if (strstr(message, "offer") != NULL &&
6539 strstr(message, "draw") != NULL) {
6541 if (appData.zippyPlay && first.initDone) {
6542 /* Relay offer to ICS */
6543 SendToICS(ics_prefix);
6544 SendToICS("draw\n");
6547 cps->offeredDraw = 2; /* valid until this engine moves twice */
6548 if (gameMode == TwoMachinesPlay) {
6549 if (cps->other->offeredDraw) {
6550 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
6551 /* [HGM] in two-machine mode we delay relaying draw offer */
6552 /* until after we also have move, to see if it is really claim */
6556 if (cps->other->sendDrawOffers) {
6557 SendToProgram("draw\n", cps->other);
6561 } else if (gameMode == MachinePlaysWhite ||
6562 gameMode == MachinePlaysBlack) {
6563 if (userOfferedDraw) {
6564 DisplayInformation(_("Machine accepts your draw offer"));
6565 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
6567 DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
6574 * Look for thinking output
6576 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
6577 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
6579 int plylev, mvleft, mvtot, curscore, time;
6580 char mvname[MOVE_LEN];
6584 int prefixHint = FALSE;
6585 mvname[0] = NULLCHAR;
6588 case MachinePlaysBlack:
6589 case IcsPlayingBlack:
6590 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
6592 case MachinePlaysWhite:
6593 case IcsPlayingWhite:
6594 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
6599 case IcsObserving: /* [DM] icsEngineAnalyze */
6600 if (!appData.icsEngineAnalyze) ignore = TRUE;
6602 case TwoMachinesPlay:
6603 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
6614 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
6615 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
6617 if (plyext != ' ' && plyext != '\t') {
6621 /* [AS] Negate score if machine is playing black and reporting absolute scores */
6622 if( cps->scoreIsAbsolute &&
6623 ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) )
6625 curscore = -curscore;
6629 programStats.depth = plylev;
6630 programStats.nodes = nodes;
6631 programStats.time = time;
6632 programStats.score = curscore;
6633 programStats.got_only_move = 0;
6635 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
6638 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
6639 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
6640 if(WhiteOnMove(forwardMostMove))
6641 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
6642 else blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
6645 /* Buffer overflow protection */
6646 if (buf1[0] != NULLCHAR) {
6647 if (strlen(buf1) >= sizeof(programStats.movelist)
6648 && appData.debugMode) {
6650 "PV is too long; using the first %d bytes.\n",
6651 sizeof(programStats.movelist) - 1);
6654 safeStrCpy( programStats.movelist, buf1, sizeof(programStats.movelist) );
6656 sprintf(programStats.movelist, " no PV\n");
6659 if (programStats.seen_stat) {
6660 programStats.ok_to_send = 1;
6663 if (strchr(programStats.movelist, '(') != NULL) {
6664 programStats.line_is_book = 1;
6665 programStats.nr_moves = 0;
6666 programStats.moves_left = 0;
6668 programStats.line_is_book = 0;
6671 SendProgramStatsToFrontend( cps, &programStats );
6674 [AS] Protect the thinkOutput buffer from overflow... this
6675 is only useful if buf1 hasn't overflowed first!
6677 sprintf(thinkOutput, "[%d]%c%+.2f %s%s",
6679 (gameMode == TwoMachinesPlay ?
6680 ToUpper(cps->twoMachinesColor[0]) : ' '),
6681 ((double) curscore) / 100.0,
6682 prefixHint ? lastHint : "",
6683 prefixHint ? " " : "" );
6685 if( buf1[0] != NULLCHAR ) {
6686 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
6688 if( strlen(buf1) > max_len ) {
6689 if( appData.debugMode) {
6690 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
6692 buf1[max_len+1] = '\0';
6695 strcat( thinkOutput, buf1 );
6698 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
6699 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
6700 DisplayMove(currentMove - 1);
6705 } else if ((p=StrStr(message, "(only move)")) != NULL) {
6706 /* crafty (9.25+) says "(only move) <move>"
6707 * if there is only 1 legal move
6709 sscanf(p, "(only move) %s", buf1);
6710 sprintf(thinkOutput, "%s (only move)", buf1);
6711 sprintf(programStats.movelist, "%s (only move)", buf1);
6712 programStats.depth = 1;
6713 programStats.nr_moves = 1;
6714 programStats.moves_left = 1;
6715 programStats.nodes = 1;
6716 programStats.time = 1;
6717 programStats.got_only_move = 1;
6719 /* Not really, but we also use this member to
6720 mean "line isn't going to change" (Crafty
6721 isn't searching, so stats won't change) */
6722 programStats.line_is_book = 1;
6724 SendProgramStatsToFrontend( cps, &programStats );
6726 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
6727 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
6728 DisplayMove(currentMove - 1);
6732 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
6733 &time, &nodes, &plylev, &mvleft,
6734 &mvtot, mvname) >= 5) {
6735 /* The stat01: line is from Crafty (9.29+) in response
6736 to the "." command */
6737 programStats.seen_stat = 1;
6738 cps->maybeThinking = TRUE;
6740 if (programStats.got_only_move || !appData.periodicUpdates)
6743 programStats.depth = plylev;
6744 programStats.time = time;
6745 programStats.nodes = nodes;
6746 programStats.moves_left = mvleft;
6747 programStats.nr_moves = mvtot;
6748 strcpy(programStats.move_name, mvname);
6749 programStats.ok_to_send = 1;
6750 programStats.movelist[0] = '\0';
6752 SendProgramStatsToFrontend( cps, &programStats );
6757 } else if (strncmp(message,"++",2) == 0) {
6758 /* Crafty 9.29+ outputs this */
6759 programStats.got_fail = 2;
6762 } else if (strncmp(message,"--",2) == 0) {
6763 /* Crafty 9.29+ outputs this */
6764 programStats.got_fail = 1;
6767 } else if (thinkOutput[0] != NULLCHAR &&
6768 strncmp(message, " ", 4) == 0) {
6769 unsigned message_len;
6772 while (*p && *p == ' ') p++;
6774 message_len = strlen( p );
6776 /* [AS] Avoid buffer overflow */
6777 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
6778 strcat(thinkOutput, " ");
6779 strcat(thinkOutput, p);
6782 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
6783 strcat(programStats.movelist, " ");
6784 strcat(programStats.movelist, p);
6787 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
6788 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
6789 DisplayMove(currentMove - 1);
6798 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
6799 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
6801 ChessProgramStats cpstats;
6803 if (plyext != ' ' && plyext != '\t') {
6807 /* [AS] Negate score if machine is playing black and reporting absolute scores */
6808 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
6809 curscore = -curscore;
6812 cpstats.depth = plylev;
6813 cpstats.nodes = nodes;
6814 cpstats.time = time;
6815 cpstats.score = curscore;
6816 cpstats.got_only_move = 0;
6817 cpstats.movelist[0] = '\0';
6819 if (buf1[0] != NULLCHAR) {
6820 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist) );
6823 cpstats.ok_to_send = 0;
6824 cpstats.line_is_book = 0;
6825 cpstats.nr_moves = 0;
6826 cpstats.moves_left = 0;
6828 SendProgramStatsToFrontend( cps, &cpstats );
6835 /* Parse a game score from the character string "game", and
6836 record it as the history of the current game. The game
6837 score is NOT assumed to start from the standard position.
6838 The display is not updated in any way.
6841 ParseGameHistory(game)
6845 int fromX, fromY, toX, toY, boardIndex;
6850 if (appData.debugMode)
6851 fprintf(debugFP, "Parsing game history: %s\n", game);
6853 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
6854 gameInfo.site = StrSave(appData.icsHost);
6855 gameInfo.date = PGNDate();
6856 gameInfo.round = StrSave("-");
6858 /* Parse out names of players */
6859 while (*game == ' ') game++;
6861 while (*game != ' ') *p++ = *game++;
6863 gameInfo.white = StrSave(buf);
6864 while (*game == ' ') game++;
6866 while (*game != ' ' && *game != '\n') *p++ = *game++;
6868 gameInfo.black = StrSave(buf);
6871 boardIndex = blackPlaysFirst ? 1 : 0;
6874 yyboardindex = boardIndex;
6875 moveType = (ChessMove) yylex();
6877 case IllegalMove: /* maybe suicide chess, etc. */
6878 if (appData.debugMode) {
6879 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
6880 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
6881 setbuf(debugFP, NULL);
6883 case WhitePromotionChancellor:
6884 case BlackPromotionChancellor:
6885 case WhitePromotionArchbishop:
6886 case BlackPromotionArchbishop:
6887 case WhitePromotionQueen:
6888 case BlackPromotionQueen:
6889 case WhitePromotionRook:
6890 case BlackPromotionRook:
6891 case WhitePromotionBishop:
6892 case BlackPromotionBishop:
6893 case WhitePromotionKnight:
6894 case BlackPromotionKnight:
6895 case WhitePromotionKing:
6896 case BlackPromotionKing:
6898 case WhiteCapturesEnPassant:
6899 case BlackCapturesEnPassant:
6900 case WhiteKingSideCastle:
6901 case WhiteQueenSideCastle:
6902 case BlackKingSideCastle:
6903 case BlackQueenSideCastle:
6904 case WhiteKingSideCastleWild:
6905 case WhiteQueenSideCastleWild:
6906 case BlackKingSideCastleWild:
6907 case BlackQueenSideCastleWild:
6909 case WhiteHSideCastleFR:
6910 case WhiteASideCastleFR:
6911 case BlackHSideCastleFR:
6912 case BlackASideCastleFR:
6914 fromX = currentMoveString[0] - AAA;
6915 fromY = currentMoveString[1] - ONE;
6916 toX = currentMoveString[2] - AAA;
6917 toY = currentMoveString[3] - ONE;
6918 promoChar = currentMoveString[4];
6922 fromX = moveType == WhiteDrop ?
6923 (int) CharToPiece(ToUpper(currentMoveString[0])) :
6924 (int) CharToPiece(ToLower(currentMoveString[0]));
6926 toX = currentMoveString[2] - AAA;
6927 toY = currentMoveString[3] - ONE;
6928 promoChar = NULLCHAR;
6932 sprintf(buf, _("Ambiguous move in ICS output: \"%s\""), yy_text);
6933 if (appData.debugMode) {
6934 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
6935 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
6936 setbuf(debugFP, NULL);
6938 DisplayError(buf, 0);
6940 case ImpossibleMove:
6942 sprintf(buf, _("Illegal move in ICS output: \"%s\""), yy_text);
6943 if (appData.debugMode) {
6944 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
6945 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
6946 setbuf(debugFP, NULL);
6948 DisplayError(buf, 0);
6950 case (ChessMove) 0: /* end of file */
6951 if (boardIndex < backwardMostMove) {
6952 /* Oops, gap. How did that happen? */
6953 DisplayError(_("Gap in move list"), 0);
6956 backwardMostMove = blackPlaysFirst ? 1 : 0;
6957 if (boardIndex > forwardMostMove) {
6958 forwardMostMove = boardIndex;
6962 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
6963 strcat(parseList[boardIndex-1], " ");
6964 strcat(parseList[boardIndex-1], yy_text);
6976 case GameUnfinished:
6977 if (gameMode == IcsExamining) {
6978 if (boardIndex < backwardMostMove) {
6979 /* Oops, gap. How did that happen? */
6982 backwardMostMove = blackPlaysFirst ? 1 : 0;
6985 gameInfo.result = moveType;
6986 p = strchr(yy_text, '{');
6987 if (p == NULL) p = strchr(yy_text, '(');
6990 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
6992 q = strchr(p, *p == '{' ? '}' : ')');
6993 if (q != NULL) *q = NULLCHAR;
6996 gameInfo.resultDetails = StrSave(p);
6999 if (boardIndex >= forwardMostMove &&
7000 !(gameMode == IcsObserving && ics_gamenum == -1)) {
7001 backwardMostMove = blackPlaysFirst ? 1 : 0;
7004 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
7005 EP_UNKNOWN, fromY, fromX, toY, toX, promoChar,
7006 parseList[boardIndex]);
7007 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
7008 {int i; for(i=0; i<BOARD_SIZE; i++) castlingRights[boardIndex+1][i] = castlingRights[boardIndex][i];}
7009 /* currentMoveString is set as a side-effect of yylex */
7010 strcpy(moveList[boardIndex], currentMoveString);
7011 strcat(moveList[boardIndex], "\n");
7013 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex],
7014 castlingRights[boardIndex], &epStatus[boardIndex]);
7015 switch (MateTest(boards[boardIndex], PosFlags(boardIndex),
7016 EP_UNKNOWN, castlingRights[boardIndex]) ) {
7022 if(gameInfo.variant != VariantShogi)
7023 strcat(parseList[boardIndex - 1], "+");
7027 strcat(parseList[boardIndex - 1], "#");
7034 /* Apply a move to the given board */
7036 ApplyMove(fromX, fromY, toX, toY, promoChar, board, castling, ep)
7037 int fromX, fromY, toX, toY;
7043 ChessSquare captured = board[toY][toX], piece, king; int p, oldEP = EP_NONE, berolina = 0;
7045 /* [HGM] compute & store e.p. status and castling rights for new position */
7046 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
7049 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
7053 if( board[toY][toX] != EmptySquare )
7056 if( board[fromY][fromX] == WhitePawn ) {
7057 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
7060 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
7061 gameInfo.variant != VariantBerolina || toX < fromX)
7062 *ep = toX | berolina;
7063 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
7064 gameInfo.variant != VariantBerolina || toX > fromX)
7068 if( board[fromY][fromX] == BlackPawn ) {
7069 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
7071 if( toY-fromY== -2) {
7072 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
7073 gameInfo.variant != VariantBerolina || toX < fromX)
7074 *ep = toX | berolina;
7075 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
7076 gameInfo.variant != VariantBerolina || toX > fromX)
7081 for(i=0; i<nrCastlingRights; i++) {
7082 if(castling[i] == fromX && castlingRank[i] == fromY ||
7083 castling[i] == toX && castlingRank[i] == toY
7084 ) castling[i] = -1; // revoke for moved or captured piece
7089 /* [HGM] In Shatranj and Courier all promotions are to Ferz */
7090 if((gameInfo.variant==VariantShatranj || gameInfo.variant==VariantCourier)
7091 && promoChar != 0) promoChar = PieceToChar(WhiteFerz);
7093 if (fromX == toX && fromY == toY) return;
7095 if (fromY == DROP_RANK) {
7097 piece = board[toY][toX] = (ChessSquare) fromX;
7099 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
7100 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
7101 if(gameInfo.variant == VariantKnightmate)
7102 king += (int) WhiteUnicorn - (int) WhiteKing;
7104 /* Code added by Tord: */
7105 /* FRC castling assumed when king captures friendly rook. */
7106 if (board[fromY][fromX] == WhiteKing &&
7107 board[toY][toX] == WhiteRook) {
7108 board[fromY][fromX] = EmptySquare;
7109 board[toY][toX] = EmptySquare;
7111 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
7113 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
7115 } else if (board[fromY][fromX] == BlackKing &&
7116 board[toY][toX] == BlackRook) {
7117 board[fromY][fromX] = EmptySquare;
7118 board[toY][toX] = EmptySquare;
7120 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
7122 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
7124 /* End of code added by Tord */
7126 } else if (board[fromY][fromX] == king
7127 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
7128 && toY == fromY && toX > fromX+1) {
7129 board[fromY][fromX] = EmptySquare;
7130 board[toY][toX] = king;
7131 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
7132 board[fromY][BOARD_RGHT-1] = EmptySquare;
7133 } else if (board[fromY][fromX] == king
7134 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
7135 && toY == fromY && toX < fromX-1) {
7136 board[fromY][fromX] = EmptySquare;
7137 board[toY][toX] = king;
7138 board[toY][toX+1] = board[fromY][BOARD_LEFT];
7139 board[fromY][BOARD_LEFT] = EmptySquare;
7140 } else if (board[fromY][fromX] == WhitePawn
7141 && toY == BOARD_HEIGHT-1
7142 && gameInfo.variant != VariantXiangqi
7144 /* white pawn promotion */
7145 board[toY][toX] = CharToPiece(ToUpper(promoChar));
7146 if (board[toY][toX] == EmptySquare) {
7147 board[toY][toX] = WhiteQueen;
7149 if(gameInfo.variant==VariantBughouse ||
7150 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
7151 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
7152 board[fromY][fromX] = EmptySquare;
7153 } else if ((fromY == BOARD_HEIGHT-4)
7155 && gameInfo.variant != VariantXiangqi
7156 && gameInfo.variant != VariantBerolina
7157 && (board[fromY][fromX] == WhitePawn)
7158 && (board[toY][toX] == EmptySquare)) {
7159 board[fromY][fromX] = EmptySquare;
7160 board[toY][toX] = WhitePawn;
7161 captured = board[toY - 1][toX];
7162 board[toY - 1][toX] = EmptySquare;
7163 } else if ((fromY == BOARD_HEIGHT-4)
7165 && gameInfo.variant == VariantBerolina
7166 && (board[fromY][fromX] == WhitePawn)
7167 && (board[toY][toX] == EmptySquare)) {
7168 board[fromY][fromX] = EmptySquare;
7169 board[toY][toX] = WhitePawn;
7170 if(oldEP & EP_BEROLIN_A) {
7171 captured = board[fromY][fromX-1];
7172 board[fromY][fromX-1] = EmptySquare;
7173 }else{ captured = board[fromY][fromX+1];
7174 board[fromY][fromX+1] = EmptySquare;
7176 } else if (board[fromY][fromX] == king
7177 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
7178 && toY == fromY && toX > fromX+1) {
7179 board[fromY][fromX] = EmptySquare;
7180 board[toY][toX] = king;
7181 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
7182 board[fromY][BOARD_RGHT-1] = EmptySquare;
7183 } else if (board[fromY][fromX] == king
7184 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
7185 && toY == fromY && toX < fromX-1) {
7186 board[fromY][fromX] = EmptySquare;
7187 board[toY][toX] = king;
7188 board[toY][toX+1] = board[fromY][BOARD_LEFT];
7189 board[fromY][BOARD_LEFT] = EmptySquare;
7190 } else if (fromY == 7 && fromX == 3
7191 && board[fromY][fromX] == BlackKing
7192 && toY == 7 && toX == 5) {
7193 board[fromY][fromX] = EmptySquare;
7194 board[toY][toX] = BlackKing;
7195 board[fromY][7] = EmptySquare;
7196 board[toY][4] = BlackRook;
7197 } else if (fromY == 7 && fromX == 3
7198 && board[fromY][fromX] == BlackKing
7199 && toY == 7 && toX == 1) {
7200 board[fromY][fromX] = EmptySquare;
7201 board[toY][toX] = BlackKing;
7202 board[fromY][0] = EmptySquare;
7203 board[toY][2] = BlackRook;
7204 } else if (board[fromY][fromX] == BlackPawn
7206 && gameInfo.variant != VariantXiangqi
7208 /* black pawn promotion */
7209 board[0][toX] = CharToPiece(ToLower(promoChar));
7210 if (board[0][toX] == EmptySquare) {
7211 board[0][toX] = BlackQueen;
7213 if(gameInfo.variant==VariantBughouse ||
7214 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
7215 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
7216 board[fromY][fromX] = EmptySquare;
7217 } else if ((fromY == 3)
7219 && gameInfo.variant != VariantXiangqi
7220 && gameInfo.variant != VariantBerolina
7221 && (board[fromY][fromX] == BlackPawn)
7222 && (board[toY][toX] == EmptySquare)) {
7223 board[fromY][fromX] = EmptySquare;
7224 board[toY][toX] = BlackPawn;
7225 captured = board[toY + 1][toX];
7226 board[toY + 1][toX] = EmptySquare;
7227 } else if ((fromY == 3)
7229 && gameInfo.variant == VariantBerolina
7230 && (board[fromY][fromX] == BlackPawn)
7231 && (board[toY][toX] == EmptySquare)) {
7232 board[fromY][fromX] = EmptySquare;
7233 board[toY][toX] = BlackPawn;
7234 if(oldEP & EP_BEROLIN_A) {
7235 captured = board[fromY][fromX-1];
7236 board[fromY][fromX-1] = EmptySquare;
7237 }else{ captured = board[fromY][fromX+1];
7238 board[fromY][fromX+1] = EmptySquare;
7241 board[toY][toX] = board[fromY][fromX];
7242 board[fromY][fromX] = EmptySquare;
7245 /* [HGM] now we promote for Shogi, if needed */
7246 if(gameInfo.variant == VariantShogi && promoChar == 'q')
7247 board[toY][toX] = (ChessSquare) (PROMOTED piece);
7250 if (gameInfo.holdingsWidth != 0) {
7252 /* !!A lot more code needs to be written to support holdings */
7253 /* [HGM] OK, so I have written it. Holdings are stored in the */
7254 /* penultimate board files, so they are automaticlly stored */
7255 /* in the game history. */
7256 if (fromY == DROP_RANK) {
7257 /* Delete from holdings, by decreasing count */
7258 /* and erasing image if necessary */
7260 if(p < (int) BlackPawn) { /* white drop */
7261 p -= (int)WhitePawn;
7262 if(p >= gameInfo.holdingsSize) p = 0;
7263 if(--board[p][BOARD_WIDTH-2] == 0)
7264 board[p][BOARD_WIDTH-1] = EmptySquare;
7265 } else { /* black drop */
7266 p -= (int)BlackPawn;
7267 if(p >= gameInfo.holdingsSize) p = 0;
7268 if(--board[BOARD_HEIGHT-1-p][1] == 0)
7269 board[BOARD_HEIGHT-1-p][0] = EmptySquare;
7272 if (captured != EmptySquare && gameInfo.holdingsSize > 0
7273 && gameInfo.variant != VariantBughouse ) {
7274 /* [HGM] holdings: Add to holdings, if holdings exist */
7275 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
7276 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
7277 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
7280 if (p >= (int) BlackPawn) {
7281 p -= (int)BlackPawn;
7282 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
7283 /* in Shogi restore piece to its original first */
7284 captured = (ChessSquare) (DEMOTED captured);
7287 p = PieceToNumber((ChessSquare)p);
7288 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
7289 board[p][BOARD_WIDTH-2]++;
7290 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
7292 p -= (int)WhitePawn;
7293 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
7294 captured = (ChessSquare) (DEMOTED captured);
7297 p = PieceToNumber((ChessSquare)p);
7298 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
7299 board[BOARD_HEIGHT-1-p][1]++;
7300 board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
7304 } else if (gameInfo.variant == VariantAtomic) {
7305 if (captured != EmptySquare) {
7307 for (y = toY-1; y <= toY+1; y++) {
7308 for (x = toX-1; x <= toX+1; x++) {
7309 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
7310 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
7311 board[y][x] = EmptySquare;
7315 board[toY][toX] = EmptySquare;
7318 if(gameInfo.variant == VariantShogi && promoChar != NULLCHAR && promoChar != '=') {
7319 /* [HGM] Shogi promotions */
7320 board[toY][toX] = (ChessSquare) (PROMOTED piece);
7323 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
7324 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
7325 // [HGM] superchess: take promotion piece out of holdings
7326 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
7327 if((int)piece < (int)BlackPawn) { // determine stm from piece color
7328 if(!--board[k][BOARD_WIDTH-2])
7329 board[k][BOARD_WIDTH-1] = EmptySquare;
7331 if(!--board[BOARD_HEIGHT-1-k][1])
7332 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
7338 /* Updates forwardMostMove */
7340 MakeMove(fromX, fromY, toX, toY, promoChar)
7341 int fromX, fromY, toX, toY;
7344 // forwardMostMove++; // [HGM] bare: moved downstream
7346 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
7347 int timeLeft; static int lastLoadFlag=0; int king, piece;
7348 piece = boards[forwardMostMove][fromY][fromX];
7349 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
7350 if(gameInfo.variant == VariantKnightmate)
7351 king += (int) WhiteUnicorn - (int) WhiteKing;
7352 if(forwardMostMove == 0) {
7354 fprintf(serverMoves, "%s;", second.tidy);
7355 fprintf(serverMoves, "%s;", first.tidy);
7356 if(!blackPlaysFirst)
7357 fprintf(serverMoves, "%s;", second.tidy);
7358 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
7359 lastLoadFlag = loadFlag;
7361 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
7362 // print castling suffix
7363 if( toY == fromY && piece == king ) {
7365 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
7367 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
7370 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
7371 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
7372 boards[forwardMostMove][toY][toX] == EmptySquare
7374 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
7376 if(promoChar != NULLCHAR)
7377 fprintf(serverMoves, ":%c:%c%c", promoChar, AAA+toX, ONE+toY);
7379 fprintf(serverMoves, "/%d/%d",
7380 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
7381 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
7382 else timeLeft = blackTimeRemaining/1000;
7383 fprintf(serverMoves, "/%d", timeLeft);
7385 fflush(serverMoves);
7388 if (forwardMostMove+1 >= MAX_MOVES) {
7389 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
7394 timeRemaining[0][forwardMostMove+1] = whiteTimeRemaining;
7395 timeRemaining[1][forwardMostMove+1] = blackTimeRemaining;
7396 if (commentList[forwardMostMove+1] != NULL) {
7397 free(commentList[forwardMostMove+1]);
7398 commentList[forwardMostMove+1] = NULL;
7400 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
7401 {int i; for(i=0; i<BOARD_SIZE; i++) castlingRights[forwardMostMove+1][i] = castlingRights[forwardMostMove][i];}
7402 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1],
7403 castlingRights[forwardMostMove+1], &epStatus[forwardMostMove+1]);
7404 forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
7405 gameInfo.result = GameUnfinished;
7406 if (gameInfo.resultDetails != NULL) {
7407 free(gameInfo.resultDetails);
7408 gameInfo.resultDetails = NULL;
7410 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
7411 moveList[forwardMostMove - 1]);
7412 (void) CoordsToAlgebraic(boards[forwardMostMove - 1],
7413 PosFlags(forwardMostMove - 1), EP_UNKNOWN,
7414 fromY, fromX, toY, toX, promoChar,
7415 parseList[forwardMostMove - 1]);
7416 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove),
7417 epStatus[forwardMostMove], /* [HGM] use true e.p. */
7418 castlingRights[forwardMostMove]) ) {
7424 if(gameInfo.variant != VariantShogi)
7425 strcat(parseList[forwardMostMove - 1], "+");
7429 strcat(parseList[forwardMostMove - 1], "#");
7432 if (appData.debugMode) {
7433 fprintf(debugFP, "move: %s, parse: %s (%c)\n", moveList[forwardMostMove-1], parseList[forwardMostMove-1], moveList[forwardMostMove-1][4]);
7438 /* Updates currentMove if not pausing */
7440 ShowMove(fromX, fromY, toX, toY)
7442 int instant = (gameMode == PlayFromGameFile) ?
7443 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
7444 if(appData.noGUI) return;
7445 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
7447 if (forwardMostMove == currentMove + 1) {
7448 AnimateMove(boards[forwardMostMove - 1],
7449 fromX, fromY, toX, toY);
7451 if (appData.highlightLastMove) {
7452 SetHighlights(fromX, fromY, toX, toY);
7455 currentMove = forwardMostMove;
7458 if (instant) return;
7460 DisplayMove(currentMove - 1);
7461 DrawPosition(FALSE, boards[currentMove]);
7462 DisplayBothClocks();
7463 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
7466 void SendEgtPath(ChessProgramState *cps)
7467 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
7468 char buf[MSG_SIZ], name[MSG_SIZ], *p;
7470 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
7473 char c, *q = name+1, *r, *s;
7475 name[0] = ','; // extract next format name from feature and copy with prefixed ','
7476 while(*p && *p != ',') *q++ = *p++;
7478 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
7479 strcmp(name, ",nalimov:") == 0 ) {
7480 // take nalimov path from the menu-changeable option first, if it is defined
7481 sprintf(buf, "egtpath nalimov %s\n", appData.defaultPathEGTB);
7482 SendToProgram(buf,cps); // send egtbpath command for nalimov
7484 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
7485 (s = StrStr(appData.egtFormats, name)) != NULL) {
7486 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
7487 s = r = StrStr(s, ":") + 1; // beginning of path info
7488 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
7489 c = *r; *r = 0; // temporarily null-terminate path info
7490 *--q = 0; // strip of trailig ':' from name
7491 sprintf(buf, "egtbpath %s %s\n", name+1, s);
7493 SendToProgram(buf,cps); // send egtbpath command for this format
7495 if(*p == ',') p++; // read away comma to position for next format name
7500 InitChessProgram(cps, setup)
7501 ChessProgramState *cps;
7502 int setup; /* [HGM] needed to setup FRC opening position */
7504 char buf[MSG_SIZ], b[MSG_SIZ]; int overruled;
7505 if (appData.noChessProgram) return;
7506 hintRequested = FALSE;
7507 bookRequested = FALSE;
7509 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
7510 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
7511 if(cps->memSize) { /* [HGM] memory */
7512 sprintf(buf, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
7513 SendToProgram(buf, cps);
7515 SendEgtPath(cps); /* [HGM] EGT */
7516 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
7517 sprintf(buf, "cores %d\n", appData.smpCores);
7518 SendToProgram(buf, cps);
7521 SendToProgram(cps->initString, cps);
7522 if (gameInfo.variant != VariantNormal &&
7523 gameInfo.variant != VariantLoadable
7524 /* [HGM] also send variant if board size non-standard */
7525 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0
7527 char *v = VariantName(gameInfo.variant);
7528 if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) {
7529 /* [HGM] in protocol 1 we have to assume all variants valid */
7530 sprintf(buf, _("Variant %s not supported by %s"), v, cps->tidy);
7531 DisplayFatalError(buf, 0, 1);
7535 /* [HGM] make prefix for non-standard board size. Awkward testing... */
7536 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
7537 if( gameInfo.variant == VariantXiangqi )
7538 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 0;
7539 if( gameInfo.variant == VariantShogi )
7540 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 9 || gameInfo.holdingsSize != 7;
7541 if( gameInfo.variant == VariantBughouse || gameInfo.variant == VariantCrazyhouse )
7542 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 5;
7543 if( gameInfo.variant == VariantCapablanca || gameInfo.variant == VariantCapaRandom ||
7544 gameInfo.variant == VariantGothic || gameInfo.variant == VariantFalcon )
7545 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
7546 if( gameInfo.variant == VariantCourier )
7547 overruled = gameInfo.boardWidth != 12 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
7548 if( gameInfo.variant == VariantSuper )
7549 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
7550 if( gameInfo.variant == VariantGreat )
7551 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
7554 sprintf(b, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
7555 gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
7556 /* [HGM] varsize: try first if this defiant size variant is specifically known */
7557 if(StrStr(cps->variants, b) == NULL) {
7558 // specific sized variant not known, check if general sizing allowed
7559 if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best
7560 if(StrStr(cps->variants, "boardsize") == NULL) {
7561 sprintf(buf, "Board size %dx%d+%d not supported by %s",
7562 gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy);
7563 DisplayFatalError(buf, 0, 1);
7566 /* [HGM] here we really should compare with the maximum supported board size */
7569 } else sprintf(b, "%s", VariantName(gameInfo.variant));
7570 sprintf(buf, "variant %s\n", b);
7571 SendToProgram(buf, cps);
7573 currentlyInitializedVariant = gameInfo.variant;
7575 /* [HGM] send opening position in FRC to first engine */
7577 SendToProgram("force\n", cps);
7579 /* engine is now in force mode! Set flag to wake it up after first move. */
7580 setboardSpoiledMachineBlack = 1;
7584 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
7585 SendToProgram(buf, cps);
7587 cps->maybeThinking = FALSE;
7588 cps->offeredDraw = 0;
7589 if (!appData.icsActive) {
7590 SendTimeControl(cps, movesPerSession, timeControl,
7591 timeIncrement, appData.searchDepth,
7594 if (appData.showThinking
7595 // [HGM] thinking: four options require thinking output to be sent
7596 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
7598 SendToProgram("post\n", cps);
7600 SendToProgram("hard\n", cps);
7601 if (!appData.ponderNextMove) {
7602 /* Warning: "easy" is a toggle in GNU Chess, so don't send
7603 it without being sure what state we are in first. "hard"
7604 is not a toggle, so that one is OK.
7606 SendToProgram("easy\n", cps);
7609 sprintf(buf, "ping %d\n", ++cps->lastPing);
7610 SendToProgram(buf, cps);
7612 cps->initDone = TRUE;
7617 StartChessProgram(cps)
7618 ChessProgramState *cps;
7623 if (appData.noChessProgram) return;
7624 cps->initDone = FALSE;
7626 if (strcmp(cps->host, "localhost") == 0) {
7627 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
7628 } else if (*appData.remoteShell == NULLCHAR) {
7629 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
7631 if (*appData.remoteUser == NULLCHAR) {
7632 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
7635 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
7636 cps->host, appData.remoteUser, cps->program);
7638 err = StartChildProcess(buf, "", &cps->pr);
7642 sprintf(buf, _("Startup failure on '%s'"), cps->program);
7643 DisplayFatalError(buf, err, 1);
7649 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
7650 if (cps->protocolVersion > 1) {
7651 sprintf(buf, "xboard\nprotover %d\n", cps->protocolVersion);
7652 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
7653 cps->comboCnt = 0; // and values of combo boxes
7654 SendToProgram(buf, cps);
7656 SendToProgram("xboard\n", cps);
7662 TwoMachinesEventIfReady P((void))
7664 if (first.lastPing != first.lastPong) {
7665 DisplayMessage("", _("Waiting for first chess program"));
7666 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
7669 if (second.lastPing != second.lastPong) {
7670 DisplayMessage("", _("Waiting for second chess program"));
7671 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
7679 NextMatchGame P((void))
7681 int index; /* [HGM] autoinc: step lod index during match */
7683 if (*appData.loadGameFile != NULLCHAR) {
7684 index = appData.loadGameIndex;
7685 if(index < 0) { // [HGM] autoinc
7686 lastIndex = index = (index == -2 && first.twoMachinesColor[0] == 'b') ? lastIndex : lastIndex+1;
7687 if(appData.rewindIndex > 0 && index > appData.rewindIndex) lastIndex = index = 1;
7689 LoadGameFromFile(appData.loadGameFile,
7691 appData.loadGameFile, FALSE);
7692 } else if (*appData.loadPositionFile != NULLCHAR) {
7693 index = appData.loadPositionIndex;
7694 if(index < 0) { // [HGM] autoinc
7695 lastIndex = index = (index == -2 && first.twoMachinesColor[0] == 'b') ? lastIndex : lastIndex+1;
7696 if(appData.rewindIndex > 0 && index > appData.rewindIndex) lastIndex = index = 1;
7698 LoadPositionFromFile(appData.loadPositionFile,
7700 appData.loadPositionFile);
7702 TwoMachinesEventIfReady();
7705 void UserAdjudicationEvent( int result )
7707 ChessMove gameResult = GameIsDrawn;
7710 gameResult = WhiteWins;
7712 else if( result < 0 ) {
7713 gameResult = BlackWins;
7716 if( gameMode == TwoMachinesPlay ) {
7717 GameEnds( gameResult, "User adjudication", GE_XBOARD );
7722 // [HGM] save: calculate checksum of game to make games easily identifiable
7723 int StringCheckSum(char *s)
7726 if(s==NULL) return 0;
7727 while(*s) i = i*259 + *s++;
7734 for(i=backwardMostMove; i<forwardMostMove; i++) {
7735 sum += pvInfoList[i].depth;
7736 sum += StringCheckSum(parseList[i]);
7737 sum += StringCheckSum(commentList[i]);
7740 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
7741 return sum + StringCheckSum(commentList[i]);
7742 } // end of save patch
7745 GameEnds(result, resultDetails, whosays)
7747 char *resultDetails;
7750 GameMode nextGameMode;
7754 if(endingGame) return; /* [HGM] crash: forbid recursion */
7757 if (appData.debugMode) {
7758 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
7759 result, resultDetails ? resultDetails : "(null)", whosays);
7762 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
7763 /* If we are playing on ICS, the server decides when the
7764 game is over, but the engine can offer to draw, claim
7768 if (appData.zippyPlay && first.initDone) {
7769 if (result == GameIsDrawn) {
7770 /* In case draw still needs to be claimed */
7771 SendToICS(ics_prefix);
7772 SendToICS("draw\n");
7773 } else if (StrCaseStr(resultDetails, "resign")) {
7774 SendToICS(ics_prefix);
7775 SendToICS("resign\n");
7779 endingGame = 0; /* [HGM] crash */
7783 /* If we're loading the game from a file, stop */
7784 if (whosays == GE_FILE) {
7785 (void) StopLoadGameTimer();
7789 /* Cancel draw offers */
7790 first.offeredDraw = second.offeredDraw = 0;
7792 /* If this is an ICS game, only ICS can really say it's done;
7793 if not, anyone can. */
7794 isIcsGame = (gameMode == IcsPlayingWhite ||
7795 gameMode == IcsPlayingBlack ||
7796 gameMode == IcsObserving ||
7797 gameMode == IcsExamining);
7799 if (!isIcsGame || whosays == GE_ICS) {
7800 /* OK -- not an ICS game, or ICS said it was done */
7802 if (!isIcsGame && !appData.noChessProgram)
7803 SetUserThinkingEnables();
7805 /* [HGM] if a machine claims the game end we verify this claim */
7806 if(gameMode == TwoMachinesPlay && appData.testClaims) {
7807 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
7809 ChessMove trueResult = (ChessMove) -1;
7811 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
7812 first.twoMachinesColor[0] :
7813 second.twoMachinesColor[0] ;
7815 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
7816 if(epStatus[forwardMostMove] == EP_CHECKMATE) {
7817 /* [HGM] verify: engine mate claims accepted if they were flagged */
7818 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
7820 if(epStatus[forwardMostMove] == EP_WINS) { // added code for games where being mated is a win
7821 /* [HGM] verify: engine mate claims accepted if they were flagged */
7822 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7824 if(epStatus[forwardMostMove] == EP_STALEMATE) { // only used to indicate draws now
7825 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
7828 // now verify win claims, but not in drop games, as we don't understand those yet
7829 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
7830 || gameInfo.variant == VariantGreat) &&
7831 (result == WhiteWins && claimer == 'w' ||
7832 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
7833 if (appData.debugMode) {
7834 fprintf(debugFP, "result=%d sp=%d move=%d\n",
7835 result, epStatus[forwardMostMove], forwardMostMove);
7837 if(result != trueResult) {
7838 sprintf(buf, "False win claim: '%s'", resultDetails);
7839 result = claimer == 'w' ? BlackWins : WhiteWins;
7840 resultDetails = buf;
7843 if( result == GameIsDrawn && epStatus[forwardMostMove] > EP_DRAWS
7844 && (forwardMostMove <= backwardMostMove ||
7845 epStatus[forwardMostMove-1] > EP_DRAWS ||
7846 (claimer=='b')==(forwardMostMove&1))
7848 /* [HGM] verify: draws that were not flagged are false claims */
7849 sprintf(buf, "False draw claim: '%s'", resultDetails);
7850 result = claimer == 'w' ? BlackWins : WhiteWins;
7851 resultDetails = buf;
7853 /* (Claiming a loss is accepted no questions asked!) */
7855 /* [HGM] bare: don't allow bare King to win */
7856 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
7857 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
7858 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
7859 && result != GameIsDrawn)
7860 { int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
7861 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
7862 int p = (int)boards[forwardMostMove][i][j] - color;
7863 if(p >= 0 && p <= (int)WhiteKing) k++;
7865 if (appData.debugMode) {
7866 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
7867 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
7870 result = GameIsDrawn;
7871 sprintf(buf, "%s but bare king", resultDetails);
7872 resultDetails = buf;
7878 if(serverMoves != NULL && !loadFlag) { char c = '=';
7879 if(result==WhiteWins) c = '+';
7880 if(result==BlackWins) c = '-';
7881 if(resultDetails != NULL)
7882 fprintf(serverMoves, ";%c;%s\n", c, resultDetails);
7884 if (resultDetails != NULL) {
7885 gameInfo.result = result;
7886 gameInfo.resultDetails = StrSave(resultDetails);
7888 /* display last move only if game was not loaded from file */
7889 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
7890 DisplayMove(currentMove - 1);
7892 if (forwardMostMove != 0) {
7893 if (gameMode != PlayFromGameFile && gameMode != EditGame
7894 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
7896 if (*appData.saveGameFile != NULLCHAR) {
7897 SaveGameToFile(appData.saveGameFile, TRUE);
7898 } else if (appData.autoSaveGames) {
7901 if (*appData.savePositionFile != NULLCHAR) {
7902 SavePositionToFile(appData.savePositionFile);
7907 /* Tell program how game ended in case it is learning */
7908 /* [HGM] Moved this to after saving the PGN, just in case */
7909 /* engine died and we got here through time loss. In that */
7910 /* case we will get a fatal error writing the pipe, which */
7911 /* would otherwise lose us the PGN. */
7912 /* [HGM] crash: not needed anymore, but doesn't hurt; */
7913 /* output during GameEnds should never be fatal anymore */
7914 if (gameMode == MachinePlaysWhite ||
7915 gameMode == MachinePlaysBlack ||
7916 gameMode == TwoMachinesPlay ||
7917 gameMode == IcsPlayingWhite ||
7918 gameMode == IcsPlayingBlack ||
7919 gameMode == BeginningOfGame) {
7921 sprintf(buf, "result %s {%s}\n", PGNResult(result),
7923 if (first.pr != NoProc) {
7924 SendToProgram(buf, &first);
7926 if (second.pr != NoProc &&
7927 gameMode == TwoMachinesPlay) {
7928 SendToProgram(buf, &second);
7933 if (appData.icsActive) {
7934 if (appData.quietPlay &&
7935 (gameMode == IcsPlayingWhite ||
7936 gameMode == IcsPlayingBlack)) {
7937 SendToICS(ics_prefix);
7938 SendToICS("set shout 1\n");
7940 nextGameMode = IcsIdle;
7941 ics_user_moved = FALSE;
7942 /* clean up premove. It's ugly when the game has ended and the
7943 * premove highlights are still on the board.
7947 ClearPremoveHighlights();
7948 DrawPosition(FALSE, boards[currentMove]);
7950 if (whosays == GE_ICS) {
7953 if (gameMode == IcsPlayingWhite)
7955 else if(gameMode == IcsPlayingBlack)
7959 if (gameMode == IcsPlayingBlack)
7961 else if(gameMode == IcsPlayingWhite)
7968 PlayIcsUnfinishedSound();
7971 } else if (gameMode == EditGame ||
7972 gameMode == PlayFromGameFile ||
7973 gameMode == AnalyzeMode ||
7974 gameMode == AnalyzeFile) {
7975 nextGameMode = gameMode;
7977 nextGameMode = EndOfGame;
7982 nextGameMode = gameMode;
7985 if (appData.noChessProgram) {
7986 gameMode = nextGameMode;
7988 endingGame = 0; /* [HGM] crash */
7993 /* Put first chess program into idle state */
7994 if (first.pr != NoProc &&
7995 (gameMode == MachinePlaysWhite ||
7996 gameMode == MachinePlaysBlack ||
7997 gameMode == TwoMachinesPlay ||
7998 gameMode == IcsPlayingWhite ||
7999 gameMode == IcsPlayingBlack ||
8000 gameMode == BeginningOfGame)) {
8001 SendToProgram("force\n", &first);
8002 if (first.usePing) {
8004 sprintf(buf, "ping %d\n", ++first.lastPing);
8005 SendToProgram(buf, &first);
8008 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
8009 /* Kill off first chess program */
8010 if (first.isr != NULL)
8011 RemoveInputSource(first.isr);
8014 if (first.pr != NoProc) {
8016 DoSleep( appData.delayBeforeQuit );
8017 SendToProgram("quit\n", &first);
8018 DoSleep( appData.delayAfterQuit );
8019 DestroyChildProcess(first.pr, first.useSigterm);
8024 /* Put second chess program into idle state */
8025 if (second.pr != NoProc &&
8026 gameMode == TwoMachinesPlay) {
8027 SendToProgram("force\n", &second);
8028 if (second.usePing) {
8030 sprintf(buf, "ping %d\n", ++second.lastPing);
8031 SendToProgram(buf, &second);
8034 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
8035 /* Kill off second chess program */
8036 if (second.isr != NULL)
8037 RemoveInputSource(second.isr);
8040 if (second.pr != NoProc) {
8041 DoSleep( appData.delayBeforeQuit );
8042 SendToProgram("quit\n", &second);
8043 DoSleep( appData.delayAfterQuit );
8044 DestroyChildProcess(second.pr, second.useSigterm);
8049 if (matchMode && gameMode == TwoMachinesPlay) {
8052 if (first.twoMachinesColor[0] == 'w') {
8059 if (first.twoMachinesColor[0] == 'b') {
8068 if (matchGame < appData.matchGames) {
8070 if(appData.sameColorGames <= 1) { /* [HGM] alternate: suppress color swap */
8071 tmp = first.twoMachinesColor;
8072 first.twoMachinesColor = second.twoMachinesColor;
8073 second.twoMachinesColor = tmp;
8075 gameMode = nextGameMode;
8077 if(appData.matchPause>10000 || appData.matchPause<10)
8078 appData.matchPause = 10000; /* [HGM] make pause adjustable */
8079 ScheduleDelayedEvent(NextMatchGame, appData.matchPause);
8080 endingGame = 0; /* [HGM] crash */
8084 gameMode = nextGameMode;
8085 sprintf(buf, _("Match %s vs. %s: final score %d-%d-%d"),
8086 first.tidy, second.tidy,
8087 first.matchWins, second.matchWins,
8088 appData.matchGames - (first.matchWins + second.matchWins));
8089 DisplayFatalError(buf, 0, 0);
8092 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
8093 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
8095 gameMode = nextGameMode;
8097 endingGame = 0; /* [HGM] crash */
8100 /* Assumes program was just initialized (initString sent).
8101 Leaves program in force mode. */
8103 FeedMovesToProgram(cps, upto)
8104 ChessProgramState *cps;
8109 if (appData.debugMode)
8110 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
8111 startedFromSetupPosition ? "position and " : "",
8112 backwardMostMove, upto, cps->which);
8113 if(currentlyInitializedVariant != gameInfo.variant) { char buf[MSG_SIZ];
8114 // [HGM] variantswitch: make engine aware of new variant
8115 if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL)
8116 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
8117 sprintf(buf, "variant %s\n", VariantName(gameInfo.variant));
8118 SendToProgram(buf, cps);
8119 currentlyInitializedVariant = gameInfo.variant;
8121 SendToProgram("force\n", cps);
8122 if (startedFromSetupPosition) {
8123 SendBoard(cps, backwardMostMove);
8124 if (appData.debugMode) {
8125 fprintf(debugFP, "feedMoves\n");
8128 for (i = backwardMostMove; i < upto; i++) {
8129 SendMoveToProgram(i, cps);
8135 ResurrectChessProgram()
8137 /* The chess program may have exited.
8138 If so, restart it and feed it all the moves made so far. */
8140 if (appData.noChessProgram || first.pr != NoProc) return;
8142 StartChessProgram(&first);
8143 InitChessProgram(&first, FALSE);
8144 FeedMovesToProgram(&first, currentMove);
8146 if (!first.sendTime) {
8147 /* can't tell gnuchess what its clock should read,
8148 so we bow to its notion. */
8150 timeRemaining[0][currentMove] = whiteTimeRemaining;
8151 timeRemaining[1][currentMove] = blackTimeRemaining;
8154 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
8155 appData.icsEngineAnalyze) && first.analysisSupport) {
8156 SendToProgram("analyze\n", &first);
8157 first.analyzing = TRUE;
8170 if (appData.debugMode) {
8171 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
8172 redraw, init, gameMode);
8174 pausing = pauseExamInvalid = FALSE;
8175 startedFromSetupPosition = blackPlaysFirst = FALSE;
8177 whiteFlag = blackFlag = FALSE;
8178 userOfferedDraw = FALSE;
8179 hintRequested = bookRequested = FALSE;
8180 first.maybeThinking = FALSE;
8181 second.maybeThinking = FALSE;
8182 first.bookSuspend = FALSE; // [HGM] book
8183 second.bookSuspend = FALSE;
8184 thinkOutput[0] = NULLCHAR;
8185 lastHint[0] = NULLCHAR;
8186 ClearGameInfo(&gameInfo);
8187 gameInfo.variant = StringToVariant(appData.variant);
8188 ics_user_moved = ics_clock_paused = FALSE;
8189 ics_getting_history = H_FALSE;
8191 white_holding[0] = black_holding[0] = NULLCHAR;
8192 ClearProgramStats();
8193 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
8197 flipView = appData.flipView;
8198 ClearPremoveHighlights();
8200 alarmSounded = FALSE;
8202 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
8203 if(appData.serverMovesName != NULL) {
8204 /* [HGM] prepare to make moves file for broadcasting */
8205 clock_t t = clock();
8206 if(serverMoves != NULL) fclose(serverMoves);
8207 serverMoves = fopen(appData.serverMovesName, "r");
8208 if(serverMoves != NULL) {
8209 fclose(serverMoves);
8210 /* delay 15 sec before overwriting, so all clients can see end */
8211 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
8213 serverMoves = fopen(appData.serverMovesName, "w");
8217 gameMode = BeginningOfGame;
8219 if(appData.icsActive) gameInfo.variant = VariantNormal;
8220 InitPosition(redraw);
8221 for (i = 0; i < MAX_MOVES; i++) {
8222 if (commentList[i] != NULL) {
8223 free(commentList[i]);
8224 commentList[i] = NULL;
8228 timeRemaining[0][0] = whiteTimeRemaining;
8229 timeRemaining[1][0] = blackTimeRemaining;
8230 if (first.pr == NULL) {
8231 StartChessProgram(&first);
8234 InitChessProgram(&first, startedFromSetupPosition);
8237 DisplayMessage("", "");
8238 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
8239 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
8246 if (!AutoPlayOneMove())
8248 if (matchMode || appData.timeDelay == 0)
8250 if (appData.timeDelay < 0 || gameMode == AnalyzeFile)
8252 StartLoadGameTimer((long)(1000.0 * appData.timeDelay));
8261 int fromX, fromY, toX, toY;
8263 if (appData.debugMode) {
8264 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
8267 if (gameMode != PlayFromGameFile)
8270 if (currentMove >= forwardMostMove) {
8271 gameMode = EditGame;
8274 /* [AS] Clear current move marker at the end of a game */
8275 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
8280 toX = moveList[currentMove][2] - AAA;
8281 toY = moveList[currentMove][3] - ONE;
8283 if (moveList[currentMove][1] == '@') {
8284 if (appData.highlightLastMove) {
8285 SetHighlights(-1, -1, toX, toY);
8288 fromX = moveList[currentMove][0] - AAA;
8289 fromY = moveList[currentMove][1] - ONE;
8291 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
8293 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
8295 if (appData.highlightLastMove) {
8296 SetHighlights(fromX, fromY, toX, toY);
8299 DisplayMove(currentMove);
8300 SendMoveToProgram(currentMove++, &first);
8301 DisplayBothClocks();
8302 DrawPosition(FALSE, boards[currentMove]);
8303 // [HGM] PV info: always display, routine tests if empty
8304 DisplayComment(currentMove - 1, commentList[currentMove]);
8310 LoadGameOneMove(readAhead)
8311 ChessMove readAhead;
8313 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
8314 char promoChar = NULLCHAR;
8319 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
8320 gameMode != AnalyzeMode && gameMode != Training) {
8325 yyboardindex = forwardMostMove;
8326 if (readAhead != (ChessMove)0) {
8327 moveType = readAhead;
8329 if (gameFileFP == NULL)
8331 moveType = (ChessMove) yylex();
8337 if (appData.debugMode)
8338 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
8340 if (*p == '{' || *p == '[' || *p == '(') {
8341 p[strlen(p) - 1] = NULLCHAR;
8345 /* append the comment but don't display it */
8346 while (*p == '\n') p++;
8347 AppendComment(currentMove, p);
8350 case WhiteCapturesEnPassant:
8351 case BlackCapturesEnPassant:
8352 case WhitePromotionChancellor:
8353 case BlackPromotionChancellor:
8354 case WhitePromotionArchbishop:
8355 case BlackPromotionArchbishop:
8356 case WhitePromotionCentaur:
8357 case BlackPromotionCentaur:
8358 case WhitePromotionQueen:
8359 case BlackPromotionQueen:
8360 case WhitePromotionRook:
8361 case BlackPromotionRook:
8362 case WhitePromotionBishop:
8363 case BlackPromotionBishop:
8364 case WhitePromotionKnight:
8365 case BlackPromotionKnight:
8366 case WhitePromotionKing:
8367 case BlackPromotionKing:
8369 case WhiteKingSideCastle:
8370 case WhiteQueenSideCastle:
8371 case BlackKingSideCastle:
8372 case BlackQueenSideCastle:
8373 case WhiteKingSideCastleWild:
8374 case WhiteQueenSideCastleWild:
8375 case BlackKingSideCastleWild:
8376 case BlackQueenSideCastleWild:
8378 case WhiteHSideCastleFR:
8379 case WhiteASideCastleFR:
8380 case BlackHSideCastleFR:
8381 case BlackASideCastleFR:
8383 if (appData.debugMode)
8384 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
8385 fromX = currentMoveString[0] - AAA;
8386 fromY = currentMoveString[1] - ONE;
8387 toX = currentMoveString[2] - AAA;
8388 toY = currentMoveString[3] - ONE;
8389 promoChar = currentMoveString[4];
8394 if (appData.debugMode)
8395 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
8396 fromX = moveType == WhiteDrop ?
8397 (int) CharToPiece(ToUpper(currentMoveString[0])) :
8398 (int) CharToPiece(ToLower(currentMoveString[0]));
8400 toX = currentMoveString[2] - AAA;
8401 toY = currentMoveString[3] - ONE;
8407 case GameUnfinished:
8408 if (appData.debugMode)
8409 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
8410 p = strchr(yy_text, '{');
8411 if (p == NULL) p = strchr(yy_text, '(');
8414 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
8416 q = strchr(p, *p == '{' ? '}' : ')');
8417 if (q != NULL) *q = NULLCHAR;
8420 GameEnds(moveType, p, GE_FILE);
8422 if (cmailMsgLoaded) {
8424 flipView = WhiteOnMove(currentMove);
8425 if (moveType == GameUnfinished) flipView = !flipView;
8426 if (appData.debugMode)
8427 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
8431 case (ChessMove) 0: /* end of file */
8432 if (appData.debugMode)
8433 fprintf(debugFP, "Parser hit end of file\n");
8434 switch (MateTest(boards[currentMove], PosFlags(currentMove),
8435 EP_UNKNOWN, castlingRights[currentMove]) ) {
8441 if (WhiteOnMove(currentMove)) {
8442 GameEnds(BlackWins, "Black mates", GE_FILE);
8444 GameEnds(WhiteWins, "White mates", GE_FILE);
8448 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
8455 if (lastLoadGameStart == GNUChessGame) {
8456 /* GNUChessGames have numbers, but they aren't move numbers */
8457 if (appData.debugMode)
8458 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
8459 yy_text, (int) moveType);
8460 return LoadGameOneMove((ChessMove)0); /* tail recursion */
8462 /* else fall thru */
8467 /* Reached start of next game in file */
8468 if (appData.debugMode)
8469 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
8470 switch (MateTest(boards[currentMove], PosFlags(currentMove),
8471 EP_UNKNOWN, castlingRights[currentMove]) ) {
8477 if (WhiteOnMove(currentMove)) {
8478 GameEnds(BlackWins, "Black mates", GE_FILE);
8480 GameEnds(WhiteWins, "White mates", GE_FILE);
8484 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
8490 case PositionDiagram: /* should not happen; ignore */
8491 case ElapsedTime: /* ignore */
8492 case NAG: /* ignore */
8493 if (appData.debugMode)
8494 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
8495 yy_text, (int) moveType);
8496 return LoadGameOneMove((ChessMove)0); /* tail recursion */
8499 if (appData.testLegality) {
8500 if (appData.debugMode)
8501 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
8502 sprintf(move, _("Illegal move: %d.%s%s"),
8503 (forwardMostMove / 2) + 1,
8504 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
8505 DisplayError(move, 0);
8508 if (appData.debugMode)
8509 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
8510 yy_text, currentMoveString);
8511 fromX = currentMoveString[0] - AAA;
8512 fromY = currentMoveString[1] - ONE;
8513 toX = currentMoveString[2] - AAA;
8514 toY = currentMoveString[3] - ONE;
8515 promoChar = currentMoveString[4];
8520 if (appData.debugMode)
8521 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
8522 sprintf(move, _("Ambiguous move: %d.%s%s"),
8523 (forwardMostMove / 2) + 1,
8524 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
8525 DisplayError(move, 0);
8530 case ImpossibleMove:
8531 if (appData.debugMode)
8532 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
8533 sprintf(move, _("Illegal move: %d.%s%s"),
8534 (forwardMostMove / 2) + 1,
8535 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
8536 DisplayError(move, 0);
8542 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
8543 DrawPosition(FALSE, boards[currentMove]);
8544 DisplayBothClocks();
8545 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
8546 DisplayComment(currentMove - 1, commentList[currentMove]);
8548 (void) StopLoadGameTimer();
8550 cmailOldMove = forwardMostMove;
8553 /* currentMoveString is set as a side-effect of yylex */
8554 strcat(currentMoveString, "\n");
8555 strcpy(moveList[forwardMostMove], currentMoveString);
8557 thinkOutput[0] = NULLCHAR;
8558 MakeMove(fromX, fromY, toX, toY, promoChar);
8559 currentMove = forwardMostMove;
8564 /* Load the nth game from the given file */
8566 LoadGameFromFile(filename, n, title, useList)
8570 /*Boolean*/ int useList;
8575 if (strcmp(filename, "-") == 0) {
8579 f = fopen(filename, "rb");
8581 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
8582 DisplayError(buf, errno);
8586 if (fseek(f, 0, 0) == -1) {
8587 /* f is not seekable; probably a pipe */
8590 if (useList && n == 0) {
8591 int error = GameListBuild(f);
8593 DisplayError(_("Cannot build game list"), error);
8594 } else if (!ListEmpty(&gameList) &&
8595 ((ListGame *) gameList.tailPred)->number > 1) {
8596 GameListPopUp(f, title);
8603 return LoadGame(f, n, title, FALSE);
8608 MakeRegisteredMove()
8610 int fromX, fromY, toX, toY;
8612 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
8613 switch (cmailMoveType[lastLoadGameNumber - 1]) {
8616 if (appData.debugMode)
8617 fprintf(debugFP, "Restoring %s for game %d\n",
8618 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
8620 thinkOutput[0] = NULLCHAR;
8621 strcpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1]);
8622 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
8623 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
8624 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
8625 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
8626 promoChar = cmailMove[lastLoadGameNumber - 1][4];
8627 MakeMove(fromX, fromY, toX, toY, promoChar);
8628 ShowMove(fromX, fromY, toX, toY);
8630 switch (MateTest(boards[currentMove], PosFlags(currentMove),
8631 EP_UNKNOWN, castlingRights[currentMove]) ) {
8638 if (WhiteOnMove(currentMove)) {
8639 GameEnds(BlackWins, "Black mates", GE_PLAYER);
8641 GameEnds(WhiteWins, "White mates", GE_PLAYER);
8646 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
8653 if (WhiteOnMove(currentMove)) {
8654 GameEnds(BlackWins, "White resigns", GE_PLAYER);
8656 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
8661 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
8672 /* Wrapper around LoadGame for use when a Cmail message is loaded */
8674 CmailLoadGame(f, gameNumber, title, useList)
8682 if (gameNumber > nCmailGames) {
8683 DisplayError(_("No more games in this message"), 0);
8686 if (f == lastLoadGameFP) {
8687 int offset = gameNumber - lastLoadGameNumber;
8689 cmailMsg[0] = NULLCHAR;
8690 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
8691 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
8692 nCmailMovesRegistered--;
8694 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
8695 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
8696 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
8699 if (! RegisterMove()) return FALSE;
8703 retVal = LoadGame(f, gameNumber, title, useList);
8705 /* Make move registered during previous look at this game, if any */
8706 MakeRegisteredMove();
8708 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
8709 commentList[currentMove]
8710 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
8711 DisplayComment(currentMove - 1, commentList[currentMove]);
8717 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
8722 int gameNumber = lastLoadGameNumber + offset;
8723 if (lastLoadGameFP == NULL) {
8724 DisplayError(_("No game has been loaded yet"), 0);
8727 if (gameNumber <= 0) {
8728 DisplayError(_("Can't back up any further"), 0);
8731 if (cmailMsgLoaded) {
8732 return CmailLoadGame(lastLoadGameFP, gameNumber,
8733 lastLoadGameTitle, lastLoadGameUseList);
8735 return LoadGame(lastLoadGameFP, gameNumber,
8736 lastLoadGameTitle, lastLoadGameUseList);
8742 /* Load the nth game from open file f */
8744 LoadGame(f, gameNumber, title, useList)
8752 int gn = gameNumber;
8753 ListGame *lg = NULL;
8756 GameMode oldGameMode;
8757 VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
8759 if (appData.debugMode)
8760 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
8762 if (gameMode == Training )
8763 SetTrainingModeOff();
8765 oldGameMode = gameMode;
8766 if (gameMode != BeginningOfGame) {
8771 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
8772 fclose(lastLoadGameFP);
8776 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
8779 fseek(f, lg->offset, 0);
8780 GameListHighlight(gameNumber);
8784 DisplayError(_("Game number out of range"), 0);
8789 if (fseek(f, 0, 0) == -1) {
8790 if (f == lastLoadGameFP ?
8791 gameNumber == lastLoadGameNumber + 1 :
8795 DisplayError(_("Can't seek on game file"), 0);
8801 lastLoadGameNumber = gameNumber;
8802 strcpy(lastLoadGameTitle, title);
8803 lastLoadGameUseList = useList;
8807 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
8808 snprintf(buf, sizeof(buf), "%s vs. %s", lg->gameInfo.white,
8809 lg->gameInfo.black);
8811 } else if (*title != NULLCHAR) {
8812 if (gameNumber > 1) {
8813 sprintf(buf, "%s %d", title, gameNumber);
8816 DisplayTitle(title);
8820 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
8821 gameMode = PlayFromGameFile;
8825 currentMove = forwardMostMove = backwardMostMove = 0;
8826 CopyBoard(boards[0], initialPosition);
8830 * Skip the first gn-1 games in the file.
8831 * Also skip over anything that precedes an identifiable
8832 * start of game marker, to avoid being confused by
8833 * garbage at the start of the file. Currently
8834 * recognized start of game markers are the move number "1",
8835 * the pattern "gnuchess .* game", the pattern
8836 * "^[#;%] [^ ]* game file", and a PGN tag block.
8837 * A game that starts with one of the latter two patterns
8838 * will also have a move number 1, possibly
8839 * following a position diagram.
8840 * 5-4-02: Let's try being more lenient and allowing a game to
8841 * start with an unnumbered move. Does that break anything?
8843 cm = lastLoadGameStart = (ChessMove) 0;
8845 yyboardindex = forwardMostMove;
8846 cm = (ChessMove) yylex();
8849 if (cmailMsgLoaded) {
8850 nCmailGames = CMAIL_MAX_GAMES - gn;
8853 DisplayError(_("Game not found in file"), 0);
8860 lastLoadGameStart = cm;
8864 switch (lastLoadGameStart) {
8871 gn--; /* count this game */
8872 lastLoadGameStart = cm;
8881 switch (lastLoadGameStart) {
8886 gn--; /* count this game */
8887 lastLoadGameStart = cm;
8890 lastLoadGameStart = cm; /* game counted already */
8898 yyboardindex = forwardMostMove;
8899 cm = (ChessMove) yylex();
8900 } while (cm == PGNTag || cm == Comment);
8907 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
8908 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
8909 != CMAIL_OLD_RESULT) {
8911 cmailResult[ CMAIL_MAX_GAMES
8912 - gn - 1] = CMAIL_OLD_RESULT;
8918 /* Only a NormalMove can be at the start of a game
8919 * without a position diagram. */
8920 if (lastLoadGameStart == (ChessMove) 0) {
8922 lastLoadGameStart = MoveNumberOne;
8931 if (appData.debugMode)
8932 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
8934 if (cm == XBoardGame) {
8935 /* Skip any header junk before position diagram and/or move 1 */
8937 yyboardindex = forwardMostMove;
8938 cm = (ChessMove) yylex();
8940 if (cm == (ChessMove) 0 ||
8941 cm == GNUChessGame || cm == XBoardGame) {
8942 /* Empty game; pretend end-of-file and handle later */
8947 if (cm == MoveNumberOne || cm == PositionDiagram ||
8948 cm == PGNTag || cm == Comment)
8951 } else if (cm == GNUChessGame) {
8952 if (gameInfo.event != NULL) {
8953 free(gameInfo.event);
8955 gameInfo.event = StrSave(yy_text);
8958 startedFromSetupPosition = FALSE;
8959 while (cm == PGNTag) {
8960 if (appData.debugMode)
8961 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
8962 err = ParsePGNTag(yy_text, &gameInfo);
8963 if (!err) numPGNTags++;
8965 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
8966 if(gameInfo.variant != oldVariant) {
8967 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
8969 oldVariant = gameInfo.variant;
8970 if (appData.debugMode)
8971 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
8975 if (gameInfo.fen != NULL) {
8976 Board initial_position;
8977 startedFromSetupPosition = TRUE;
8978 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
8980 DisplayError(_("Bad FEN position in file"), 0);
8983 CopyBoard(boards[0], initial_position);
8984 if (blackPlaysFirst) {
8985 currentMove = forwardMostMove = backwardMostMove = 1;
8986 CopyBoard(boards[1], initial_position);
8987 strcpy(moveList[0], "");
8988 strcpy(parseList[0], "");
8989 timeRemaining[0][1] = whiteTimeRemaining;
8990 timeRemaining[1][1] = blackTimeRemaining;
8991 if (commentList[0] != NULL) {
8992 commentList[1] = commentList[0];
8993 commentList[0] = NULL;
8996 currentMove = forwardMostMove = backwardMostMove = 0;
8998 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
9000 initialRulePlies = FENrulePlies;
9001 epStatus[forwardMostMove] = FENepStatus;
9002 for( i=0; i< nrCastlingRights; i++ )
9003 initialRights[i] = castlingRights[forwardMostMove][i] = FENcastlingRights[i];
9005 yyboardindex = forwardMostMove;
9007 gameInfo.fen = NULL;
9010 yyboardindex = forwardMostMove;
9011 cm = (ChessMove) yylex();
9013 /* Handle comments interspersed among the tags */
9014 while (cm == Comment) {
9016 if (appData.debugMode)
9017 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
9019 if (*p == '{' || *p == '[' || *p == '(') {
9020 p[strlen(p) - 1] = NULLCHAR;
9023 while (*p == '\n') p++;
9024 AppendComment(currentMove, p);
9025 yyboardindex = forwardMostMove;
9026 cm = (ChessMove) yylex();
9030 /* don't rely on existence of Event tag since if game was
9031 * pasted from clipboard the Event tag may not exist
9033 if (numPGNTags > 0){
9035 if (gameInfo.variant == VariantNormal) {
9036 gameInfo.variant = StringToVariant(gameInfo.event);
9039 if( appData.autoDisplayTags ) {
9040 tags = PGNTags(&gameInfo);
9041 TagsPopUp(tags, CmailMsg());
9046 /* Make something up, but don't display it now */
9051 if (cm == PositionDiagram) {
9054 Board initial_position;
9056 if (appData.debugMode)
9057 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
9059 if (!startedFromSetupPosition) {
9061 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
9062 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
9072 initial_position[i][j++] = CharToPiece(*p);
9075 while (*p == ' ' || *p == '\t' ||
9076 *p == '\n' || *p == '\r') p++;
9078 if (strncmp(p, "black", strlen("black"))==0)
9079 blackPlaysFirst = TRUE;
9081 blackPlaysFirst = FALSE;
9082 startedFromSetupPosition = TRUE;
9084 CopyBoard(boards[0], initial_position);
9085 if (blackPlaysFirst) {
9086 currentMove = forwardMostMove = backwardMostMove = 1;
9087 CopyBoard(boards[1], initial_position);
9088 strcpy(moveList[0], "");
9089 strcpy(parseList[0], "");
9090 timeRemaining[0][1] = whiteTimeRemaining;
9091 timeRemaining[1][1] = blackTimeRemaining;
9092 if (commentList[0] != NULL) {
9093 commentList[1] = commentList[0];
9094 commentList[0] = NULL;
9097 currentMove = forwardMostMove = backwardMostMove = 0;
9100 yyboardindex = forwardMostMove;
9101 cm = (ChessMove) yylex();
9104 if (first.pr == NoProc) {
9105 StartChessProgram(&first);
9107 InitChessProgram(&first, FALSE);
9108 SendToProgram("force\n", &first);
9109 if (startedFromSetupPosition) {
9110 SendBoard(&first, forwardMostMove);
9111 if (appData.debugMode) {
9112 fprintf(debugFP, "Load Game\n");
9114 DisplayBothClocks();
9117 /* [HGM] server: flag to write setup moves in broadcast file as one */
9118 loadFlag = appData.suppressLoadMoves;
9120 while (cm == Comment) {
9122 if (appData.debugMode)
9123 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
9125 if (*p == '{' || *p == '[' || *p == '(') {
9126 p[strlen(p) - 1] = NULLCHAR;
9129 while (*p == '\n') p++;
9130 AppendComment(currentMove, p);
9131 yyboardindex = forwardMostMove;
9132 cm = (ChessMove) yylex();
9135 if ((cm == (ChessMove) 0 && lastLoadGameStart != (ChessMove) 0) ||
9136 cm == WhiteWins || cm == BlackWins ||
9137 cm == GameIsDrawn || cm == GameUnfinished) {
9138 DisplayMessage("", _("No moves in game"));
9139 if (cmailMsgLoaded) {
9140 if (appData.debugMode)
9141 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
9145 DrawPosition(FALSE, boards[currentMove]);
9146 DisplayBothClocks();
9147 gameMode = EditGame;
9154 // [HGM] PV info: routine tests if comment empty
9155 if (!matchMode && (pausing || appData.timeDelay != 0)) {
9156 DisplayComment(currentMove - 1, commentList[currentMove]);
9158 if (!matchMode && appData.timeDelay != 0)
9159 DrawPosition(FALSE, boards[currentMove]);
9161 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
9162 programStats.ok_to_send = 1;
9165 /* if the first token after the PGN tags is a move
9166 * and not move number 1, retrieve it from the parser
9168 if (cm != MoveNumberOne)
9169 LoadGameOneMove(cm);
9171 /* load the remaining moves from the file */
9172 while (LoadGameOneMove((ChessMove)0)) {
9173 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
9174 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
9177 /* rewind to the start of the game */
9178 currentMove = backwardMostMove;
9180 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
9182 if (oldGameMode == AnalyzeFile ||
9183 oldGameMode == AnalyzeMode) {
9187 if (matchMode || appData.timeDelay == 0) {
9189 gameMode = EditGame;
9191 } else if (appData.timeDelay > 0) {
9195 if (appData.debugMode)
9196 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
9198 loadFlag = 0; /* [HGM] true game starts */
9202 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
9204 ReloadPosition(offset)
9207 int positionNumber = lastLoadPositionNumber + offset;
9208 if (lastLoadPositionFP == NULL) {
9209 DisplayError(_("No position has been loaded yet"), 0);
9212 if (positionNumber <= 0) {
9213 DisplayError(_("Can't back up any further"), 0);
9216 return LoadPosition(lastLoadPositionFP, positionNumber,
9217 lastLoadPositionTitle);
9220 /* Load the nth position from the given file */
9222 LoadPositionFromFile(filename, n, title)
9230 if (strcmp(filename, "-") == 0) {
9231 return LoadPosition(stdin, n, "stdin");
9233 f = fopen(filename, "rb");
9235 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
9236 DisplayError(buf, errno);
9239 return LoadPosition(f, n, title);
9244 /* Load the nth position from the given open file, and close it */
9246 LoadPosition(f, positionNumber, title)
9251 char *p, line[MSG_SIZ];
9252 Board initial_position;
9253 int i, j, fenMode, pn;
9255 if (gameMode == Training )
9256 SetTrainingModeOff();
9258 if (gameMode != BeginningOfGame) {
9261 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
9262 fclose(lastLoadPositionFP);
9264 if (positionNumber == 0) positionNumber = 1;
9265 lastLoadPositionFP = f;
9266 lastLoadPositionNumber = positionNumber;
9267 strcpy(lastLoadPositionTitle, title);
9268 if (first.pr == NoProc) {
9269 StartChessProgram(&first);
9270 InitChessProgram(&first, FALSE);
9272 pn = positionNumber;
9273 if (positionNumber < 0) {
9274 /* Negative position number means to seek to that byte offset */
9275 if (fseek(f, -positionNumber, 0) == -1) {
9276 DisplayError(_("Can't seek on position file"), 0);
9281 if (fseek(f, 0, 0) == -1) {
9282 if (f == lastLoadPositionFP ?
9283 positionNumber == lastLoadPositionNumber + 1 :
9284 positionNumber == 1) {
9287 DisplayError(_("Can't seek on position file"), 0);
9292 /* See if this file is FEN or old-style xboard */
9293 if (fgets(line, MSG_SIZ, f) == NULL) {
9294 DisplayError(_("Position not found in file"), 0);
9303 case 'p': case 'n': case 'b': case 'r': case 'q': case 'k':
9304 case 'P': case 'N': case 'B': case 'R': case 'Q': case 'K':
9305 case '1': case '2': case '3': case '4': case '5': case '6':
9306 case '7': case '8': case '9':
9307 case 'H': case 'A': case 'M': case 'h': case 'a': case 'm':
9308 case 'E': case 'F': case 'G': case 'e': case 'f': case 'g':
9309 case 'C': case 'W': case 'c': case 'w':
9314 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
9315 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
9319 if (fenMode || line[0] == '#') pn--;
9321 /* skip positions before number pn */
9322 if (fgets(line, MSG_SIZ, f) == NULL) {
9324 DisplayError(_("Position not found in file"), 0);
9327 if (fenMode || line[0] == '#') pn--;
9332 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
9333 DisplayError(_("Bad FEN position in file"), 0);
9337 (void) fgets(line, MSG_SIZ, f);
9338 (void) fgets(line, MSG_SIZ, f);
9340 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
9341 (void) fgets(line, MSG_SIZ, f);
9342 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
9345 initial_position[i][j++] = CharToPiece(*p);
9349 blackPlaysFirst = FALSE;
9351 (void) fgets(line, MSG_SIZ, f);
9352 if (strncmp(line, "black", strlen("black"))==0)
9353 blackPlaysFirst = TRUE;
9356 startedFromSetupPosition = TRUE;
9358 SendToProgram("force\n", &first);
9359 CopyBoard(boards[0], initial_position);
9360 if (blackPlaysFirst) {
9361 currentMove = forwardMostMove = backwardMostMove = 1;
9362 strcpy(moveList[0], "");
9363 strcpy(parseList[0], "");
9364 CopyBoard(boards[1], initial_position);
9365 DisplayMessage("", _("Black to play"));
9367 currentMove = forwardMostMove = backwardMostMove = 0;
9368 DisplayMessage("", _("White to play"));
9370 /* [HGM] copy FEN attributes as well */
9372 initialRulePlies = FENrulePlies;
9373 epStatus[forwardMostMove] = FENepStatus;
9374 for( i=0; i< nrCastlingRights; i++ )
9375 castlingRights[forwardMostMove][i] = FENcastlingRights[i];
9377 SendBoard(&first, forwardMostMove);
9378 if (appData.debugMode) {
9380 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", castlingRights[i][j]);fprintf(debugFP,"\n");}
9381 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
9382 fprintf(debugFP, "Load Position\n");
9385 if (positionNumber > 1) {
9386 sprintf(line, "%s %d", title, positionNumber);
9389 DisplayTitle(title);
9391 gameMode = EditGame;
9394 timeRemaining[0][1] = whiteTimeRemaining;
9395 timeRemaining[1][1] = blackTimeRemaining;
9396 DrawPosition(FALSE, boards[currentMove]);
9403 CopyPlayerNameIntoFileName(dest, src)
9406 while (*src != NULLCHAR && *src != ',') {
9411 *(*dest)++ = *src++;
9416 char *DefaultFileName(ext)
9419 static char def[MSG_SIZ];
9422 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
9424 CopyPlayerNameIntoFileName(&p, gameInfo.white);
9426 CopyPlayerNameIntoFileName(&p, gameInfo.black);
9435 /* Save the current game to the given file */
9437 SaveGameToFile(filename, append)
9444 if (strcmp(filename, "-") == 0) {
9445 return SaveGame(stdout, 0, NULL);
9447 f = fopen(filename, append ? "a" : "w");
9449 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
9450 DisplayError(buf, errno);
9453 return SaveGame(f, 0, NULL);
9462 static char buf[MSG_SIZ];
9465 p = strchr(str, ' ');
9466 if (p == NULL) return str;
9467 strncpy(buf, str, p - str);
9468 buf[p - str] = NULLCHAR;
9472 #define PGN_MAX_LINE 75
9474 #define PGN_SIDE_WHITE 0
9475 #define PGN_SIDE_BLACK 1
9478 static int FindFirstMoveOutOfBook( int side )
9482 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
9483 int index = backwardMostMove;
9484 int has_book_hit = 0;
9486 if( (index % 2) != side ) {
9490 while( index < forwardMostMove ) {
9491 /* Check to see if engine is in book */
9492 int depth = pvInfoList[index].depth;
9493 int score = pvInfoList[index].score;
9499 else if( score == 0 && depth == 63 ) {
9500 in_book = 1; /* Zappa */
9502 else if( score == 2 && depth == 99 ) {
9503 in_book = 1; /* Abrok */
9506 has_book_hit += in_book;
9522 void GetOutOfBookInfo( char * buf )
9526 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
9528 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
9529 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
9533 if( oob[0] >= 0 || oob[1] >= 0 ) {
9534 for( i=0; i<2; i++ ) {
9538 if( i > 0 && oob[0] >= 0 ) {
9542 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
9543 sprintf( buf+strlen(buf), "%s%.2f",
9544 pvInfoList[idx].score >= 0 ? "+" : "",
9545 pvInfoList[idx].score / 100.0 );
9551 /* Save game in PGN style and close the file */
9556 int i, offset, linelen, newblock;
9560 int movelen, numlen, blank;
9561 char move_buffer[100]; /* [AS] Buffer for move+PV info */
9563 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
9565 tm = time((time_t *) NULL);
9567 PrintPGNTags(f, &gameInfo);
9569 if (backwardMostMove > 0 || startedFromSetupPosition) {
9570 char *fen = PositionToFEN(backwardMostMove, NULL);
9571 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
9572 fprintf(f, "\n{--------------\n");
9573 PrintPosition(f, backwardMostMove);
9574 fprintf(f, "--------------}\n");
9578 /* [AS] Out of book annotation */
9579 if( appData.saveOutOfBookInfo ) {
9582 GetOutOfBookInfo( buf );
9584 if( buf[0] != '\0' ) {
9585 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
9592 i = backwardMostMove;
9596 while (i < forwardMostMove) {
9597 /* Print comments preceding this move */
9598 if (commentList[i] != NULL) {
9599 if (linelen > 0) fprintf(f, "\n");
9600 fprintf(f, "{\n%s}\n", commentList[i]);
9605 /* Format move number */
9607 sprintf(numtext, "%d.", (i - offset)/2 + 1);
9610 sprintf(numtext, "%d...", (i - offset)/2 + 1);
9612 numtext[0] = NULLCHAR;
9615 numlen = strlen(numtext);
9618 /* Print move number */
9619 blank = linelen > 0 && numlen > 0;
9620 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
9629 fprintf(f, numtext);
9633 strcpy(move_buffer, SavePart(parseList[i])); // [HGM] pgn: print move via buffer, so it can be edited
9634 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
9636 // SavePart already does this!
9637 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
9638 int p = movelen - 1;
9639 if(move_buffer[p] == ' ') p--;
9640 if(move_buffer[p] == ')') { // [HGM] pgn: strip off ICS time if we have extended info
9641 while(p && move_buffer[--p] != '(');
9642 if(p && move_buffer[p-1] == ' ') move_buffer[movelen=p-1] = 0;
9647 blank = linelen > 0 && movelen > 0;
9648 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
9657 fprintf(f, move_buffer);
9660 /* [AS] Add PV info if present */
9661 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
9662 /* [HGM] add time */
9663 char buf[MSG_SIZ]; int seconds = 0;
9666 if(i >= backwardMostMove) {
9668 seconds = timeRemaining[0][i] - timeRemaining[0][i+1]
9669 + GetTimeQuota(i/2) / (1000*WhitePlayer()->timeOdds);
9671 seconds = timeRemaining[1][i] - timeRemaining[1][i+1]
9672 + GetTimeQuota(i/2) / (1000*WhitePlayer()->other->timeOdds);
9674 seconds = (seconds+50)/100; // deci-seconds, rounded to nearest
9676 seconds = (pvInfoList[i].time + 5)/10; // [HGM] PVtime: use engine time
9679 if( seconds <= 0) buf[0] = 0; else
9680 if( seconds < 30 ) sprintf(buf, " %3.1f%c", seconds/10., 0); else {
9681 seconds = (seconds + 4)/10; // round to full seconds
9682 if( seconds < 60 ) sprintf(buf, " %d%c", seconds, 0); else
9683 sprintf(buf, " %d:%02d%c", seconds/60, seconds%60, 0);
9686 sprintf( move_buffer, "{%s%.2f/%d%s}",
9687 pvInfoList[i].score >= 0 ? "+" : "",
9688 pvInfoList[i].score / 100.0,
9689 pvInfoList[i].depth,
9692 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
9694 /* Print score/depth */
9695 blank = linelen > 0 && movelen > 0;
9696 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
9705 fprintf(f, move_buffer);
9712 /* Start a new line */
9713 if (linelen > 0) fprintf(f, "\n");
9715 /* Print comments after last move */
9716 if (commentList[i] != NULL) {
9717 fprintf(f, "{\n%s}\n", commentList[i]);
9721 if (gameInfo.resultDetails != NULL &&
9722 gameInfo.resultDetails[0] != NULLCHAR) {
9723 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
9724 PGNResult(gameInfo.result));
9726 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
9730 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
9734 /* Save game in old style and close the file */
9742 tm = time((time_t *) NULL);
9744 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
9747 if (backwardMostMove > 0 || startedFromSetupPosition) {
9748 fprintf(f, "\n[--------------\n");
9749 PrintPosition(f, backwardMostMove);
9750 fprintf(f, "--------------]\n");
9755 i = backwardMostMove;
9756 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
9758 while (i < forwardMostMove) {
9759 if (commentList[i] != NULL) {
9760 fprintf(f, "[%s]\n", commentList[i]);
9764 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
9767 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
9769 if (commentList[i] != NULL) {
9773 if (i >= forwardMostMove) {
9777 fprintf(f, "%s\n", parseList[i]);
9782 if (commentList[i] != NULL) {
9783 fprintf(f, "[%s]\n", commentList[i]);
9786 /* This isn't really the old style, but it's close enough */
9787 if (gameInfo.resultDetails != NULL &&
9788 gameInfo.resultDetails[0] != NULLCHAR) {
9789 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
9790 gameInfo.resultDetails);
9792 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
9799 /* Save the current game to open file f and close the file */
9801 SaveGame(f, dummy, dummy2)
9806 if (gameMode == EditPosition) EditPositionDone();
9807 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
9808 if (appData.oldSaveStyle)
9809 return SaveGameOldStyle(f);
9811 return SaveGamePGN(f);
9814 /* Save the current position to the given file */
9816 SavePositionToFile(filename)
9822 if (strcmp(filename, "-") == 0) {
9823 return SavePosition(stdout, 0, NULL);
9825 f = fopen(filename, "a");
9827 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
9828 DisplayError(buf, errno);
9831 SavePosition(f, 0, NULL);
9837 /* Save the current position to the given open file and close the file */
9839 SavePosition(f, dummy, dummy2)
9847 if (appData.oldSaveStyle) {
9848 tm = time((time_t *) NULL);
9850 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
9852 fprintf(f, "[--------------\n");
9853 PrintPosition(f, currentMove);
9854 fprintf(f, "--------------]\n");
9856 fen = PositionToFEN(currentMove, NULL);
9857 fprintf(f, "%s\n", fen);
9865 ReloadCmailMsgEvent(unregister)
9869 static char *inFilename = NULL;
9870 static char *outFilename;
9872 struct stat inbuf, outbuf;
9875 /* Any registered moves are unregistered if unregister is set, */
9876 /* i.e. invoked by the signal handler */
9878 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
9879 cmailMoveRegistered[i] = FALSE;
9880 if (cmailCommentList[i] != NULL) {
9881 free(cmailCommentList[i]);
9882 cmailCommentList[i] = NULL;
9885 nCmailMovesRegistered = 0;
9888 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
9889 cmailResult[i] = CMAIL_NOT_RESULT;
9893 if (inFilename == NULL) {
9894 /* Because the filenames are static they only get malloced once */
9895 /* and they never get freed */
9896 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
9897 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
9899 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
9900 sprintf(outFilename, "%s.out", appData.cmailGameName);
9903 status = stat(outFilename, &outbuf);
9905 cmailMailedMove = FALSE;
9907 status = stat(inFilename, &inbuf);
9908 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
9911 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
9912 counts the games, notes how each one terminated, etc.
9914 It would be nice to remove this kludge and instead gather all
9915 the information while building the game list. (And to keep it
9916 in the game list nodes instead of having a bunch of fixed-size
9917 parallel arrays.) Note this will require getting each game's
9918 termination from the PGN tags, as the game list builder does
9919 not process the game moves. --mann
9921 cmailMsgLoaded = TRUE;
9922 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
9924 /* Load first game in the file or popup game menu */
9925 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
9935 char string[MSG_SIZ];
9937 if ( cmailMailedMove
9938 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
9939 return TRUE; /* Allow free viewing */
9942 /* Unregister move to ensure that we don't leave RegisterMove */
9943 /* with the move registered when the conditions for registering no */
9945 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
9946 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
9947 nCmailMovesRegistered --;
9949 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
9951 free(cmailCommentList[lastLoadGameNumber - 1]);
9952 cmailCommentList[lastLoadGameNumber - 1] = NULL;
9956 if (cmailOldMove == -1) {
9957 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
9961 if (currentMove > cmailOldMove + 1) {
9962 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
9966 if (currentMove < cmailOldMove) {
9967 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
9971 if (forwardMostMove > currentMove) {
9972 /* Silently truncate extra moves */
9976 if ( (currentMove == cmailOldMove + 1)
9977 || ( (currentMove == cmailOldMove)
9978 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
9979 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
9980 if (gameInfo.result != GameUnfinished) {
9981 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
9984 if (commentList[currentMove] != NULL) {
9985 cmailCommentList[lastLoadGameNumber - 1]
9986 = StrSave(commentList[currentMove]);
9988 strcpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1]);
9990 if (appData.debugMode)
9991 fprintf(debugFP, "Saving %s for game %d\n",
9992 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
9995 "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
9997 f = fopen(string, "w");
9998 if (appData.oldSaveStyle) {
9999 SaveGameOldStyle(f); /* also closes the file */
10001 sprintf(string, "%s.pos.out", appData.cmailGameName);
10002 f = fopen(string, "w");
10003 SavePosition(f, 0, NULL); /* also closes the file */
10005 fprintf(f, "{--------------\n");
10006 PrintPosition(f, currentMove);
10007 fprintf(f, "--------------}\n\n");
10009 SaveGame(f, 0, NULL); /* also closes the file*/
10012 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
10013 nCmailMovesRegistered ++;
10014 } else if (nCmailGames == 1) {
10015 DisplayError(_("You have not made a move yet"), 0);
10026 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
10027 FILE *commandOutput;
10028 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
10029 int nBytes = 0; /* Suppress warnings on uninitialized variables */
10035 if (! cmailMsgLoaded) {
10036 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
10040 if (nCmailGames == nCmailResults) {
10041 DisplayError(_("No unfinished games"), 0);
10045 #if CMAIL_PROHIBIT_REMAIL
10046 if (cmailMailedMove) {
10047 sprintf(msg, _("You have already mailed a move.\nWait until a move arrives from your opponent.\nTo resend the same move, type\n\"cmail -remail -game %s\"\non the command line."), appData.cmailGameName);
10048 DisplayError(msg, 0);
10053 if (! (cmailMailedMove || RegisterMove())) return;
10055 if ( cmailMailedMove
10056 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
10057 sprintf(string, partCommandString,
10058 appData.debugMode ? " -v" : "", appData.cmailGameName);
10059 commandOutput = popen(string, "r");
10061 if (commandOutput == NULL) {
10062 DisplayError(_("Failed to invoke cmail"), 0);
10064 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
10065 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
10067 if (nBuffers > 1) {
10068 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
10069 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
10070 nBytes = MSG_SIZ - 1;
10072 (void) memcpy(msg, buffer, nBytes);
10074 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
10076 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
10077 cmailMailedMove = TRUE; /* Prevent >1 moves */
10080 for (i = 0; i < nCmailGames; i ++) {
10081 if (cmailResult[i] == CMAIL_NOT_RESULT) {
10086 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
10088 sprintf(buffer, "%s/%s.%s.archive",
10090 appData.cmailGameName,
10092 LoadGameFromFile(buffer, 1, buffer, FALSE);
10093 cmailMsgLoaded = FALSE;
10097 DisplayInformation(msg);
10098 pclose(commandOutput);
10101 if ((*cmailMsg) != '\0') {
10102 DisplayInformation(cmailMsg);
10107 #endif /* !WIN32 */
10116 int prependComma = 0;
10118 char string[MSG_SIZ]; /* Space for game-list */
10121 if (!cmailMsgLoaded) return "";
10123 if (cmailMailedMove) {
10124 sprintf(cmailMsg, _("Waiting for reply from opponent\n"));
10126 /* Create a list of games left */
10127 sprintf(string, "[");
10128 for (i = 0; i < nCmailGames; i ++) {
10129 if (! ( cmailMoveRegistered[i]
10130 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
10131 if (prependComma) {
10132 sprintf(number, ",%d", i + 1);
10134 sprintf(number, "%d", i + 1);
10138 strcat(string, number);
10141 strcat(string, "]");
10143 if (nCmailMovesRegistered + nCmailResults == 0) {
10144 switch (nCmailGames) {
10147 _("Still need to make move for game\n"));
10152 _("Still need to make moves for both games\n"));
10157 _("Still need to make moves for all %d games\n"),
10162 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
10165 _("Still need to make a move for game %s\n"),
10170 if (nCmailResults == nCmailGames) {
10171 sprintf(cmailMsg, _("No unfinished games\n"));
10173 sprintf(cmailMsg, _("Ready to send mail\n"));
10179 _("Still need to make moves for games %s\n"),
10191 if (gameMode == Training)
10192 SetTrainingModeOff();
10195 cmailMsgLoaded = FALSE;
10196 if (appData.icsActive) {
10197 SendToICS(ics_prefix);
10198 SendToICS("refresh\n");
10208 /* Give up on clean exit */
10212 /* Keep trying for clean exit */
10216 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
10218 if (telnetISR != NULL) {
10219 RemoveInputSource(telnetISR);
10221 if (icsPR != NoProc) {
10222 DestroyChildProcess(icsPR, TRUE);
10225 /* Save game if resource set and not already saved by GameEnds() */
10226 if ((gameInfo.resultDetails == NULL || errorExitFlag )
10227 && forwardMostMove > 0) {
10228 if (*appData.saveGameFile != NULLCHAR) {
10229 SaveGameToFile(appData.saveGameFile, TRUE);
10230 } else if (appData.autoSaveGames) {
10233 if (*appData.savePositionFile != NULLCHAR) {
10234 SavePositionToFile(appData.savePositionFile);
10237 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
10239 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
10240 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
10242 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
10243 /* make sure this other one finishes before killing it! */
10244 if(endingGame) { int count = 0;
10245 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
10246 while(endingGame && count++ < 10) DoSleep(1);
10247 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
10250 /* Kill off chess programs */
10251 if (first.pr != NoProc) {
10254 DoSleep( appData.delayBeforeQuit );
10255 SendToProgram("quit\n", &first);
10256 DoSleep( appData.delayAfterQuit );
10257 DestroyChildProcess(first.pr, 10 /* [AS] first.useSigterm */ );
10259 if (second.pr != NoProc) {
10260 DoSleep( appData.delayBeforeQuit );
10261 SendToProgram("quit\n", &second);
10262 DoSleep( appData.delayAfterQuit );
10263 DestroyChildProcess(second.pr, 10 /* [AS] second.useSigterm */ );
10265 if (first.isr != NULL) {
10266 RemoveInputSource(first.isr);
10268 if (second.isr != NULL) {
10269 RemoveInputSource(second.isr);
10272 ShutDownFrontEnd();
10279 if (appData.debugMode)
10280 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
10284 if (gameMode == MachinePlaysWhite ||
10285 gameMode == MachinePlaysBlack) {
10288 DisplayBothClocks();
10290 if (gameMode == PlayFromGameFile) {
10291 if (appData.timeDelay >= 0)
10292 AutoPlayGameLoop();
10293 } else if (gameMode == IcsExamining && pauseExamInvalid) {
10294 Reset(FALSE, TRUE);
10295 SendToICS(ics_prefix);
10296 SendToICS("refresh\n");
10297 } else if (currentMove < forwardMostMove) {
10298 ForwardInner(forwardMostMove);
10300 pauseExamInvalid = FALSE;
10302 switch (gameMode) {
10306 pauseExamForwardMostMove = forwardMostMove;
10307 pauseExamInvalid = FALSE;
10310 case IcsPlayingWhite:
10311 case IcsPlayingBlack:
10315 case PlayFromGameFile:
10316 (void) StopLoadGameTimer();
10320 case BeginningOfGame:
10321 if (appData.icsActive) return;
10322 /* else fall through */
10323 case MachinePlaysWhite:
10324 case MachinePlaysBlack:
10325 case TwoMachinesPlay:
10326 if (forwardMostMove == 0)
10327 return; /* don't pause if no one has moved */
10328 if ((gameMode == MachinePlaysWhite &&
10329 !WhiteOnMove(forwardMostMove)) ||
10330 (gameMode == MachinePlaysBlack &&
10331 WhiteOnMove(forwardMostMove))) {
10344 char title[MSG_SIZ];
10346 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
10347 strcpy(title, _("Edit comment"));
10349 sprintf(title, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
10350 WhiteOnMove(currentMove - 1) ? " " : ".. ",
10351 parseList[currentMove - 1]);
10354 EditCommentPopUp(currentMove, title, commentList[currentMove]);
10361 char *tags = PGNTags(&gameInfo);
10362 EditTagsPopUp(tags);
10369 if (appData.noChessProgram || gameMode == AnalyzeMode)
10372 if (gameMode != AnalyzeFile) {
10373 if (!appData.icsEngineAnalyze) {
10375 if (gameMode != EditGame) return;
10377 ResurrectChessProgram();
10378 SendToProgram("analyze\n", &first);
10379 first.analyzing = TRUE;
10380 /*first.maybeThinking = TRUE;*/
10381 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
10382 AnalysisPopUp(_("Analysis"),
10383 _("Starting analysis mode...\nIf this message stays up, your chess program does not support analysis."));
10385 if (!appData.icsEngineAnalyze) gameMode = AnalyzeMode;
10390 StartAnalysisClock();
10391 GetTimeMark(&lastNodeCountTime);
10398 if (appData.noChessProgram || gameMode == AnalyzeFile)
10401 if (gameMode != AnalyzeMode) {
10403 if (gameMode != EditGame) return;
10404 ResurrectChessProgram();
10405 SendToProgram("analyze\n", &first);
10406 first.analyzing = TRUE;
10407 /*first.maybeThinking = TRUE;*/
10408 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
10409 AnalysisPopUp(_("Analysis"),
10410 _("Starting analysis mode...\nIf this message stays up, your chess program does not support analysis."));
10412 gameMode = AnalyzeFile;
10417 StartAnalysisClock();
10418 GetTimeMark(&lastNodeCountTime);
10423 MachineWhiteEvent()
10426 char *bookHit = NULL;
10428 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
10432 if (gameMode == PlayFromGameFile ||
10433 gameMode == TwoMachinesPlay ||
10434 gameMode == Training ||
10435 gameMode == AnalyzeMode ||
10436 gameMode == EndOfGame)
10439 if (gameMode == EditPosition)
10440 EditPositionDone();
10442 if (!WhiteOnMove(currentMove)) {
10443 DisplayError(_("It is not White's turn"), 0);
10447 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
10450 if (gameMode == EditGame || gameMode == AnalyzeMode ||
10451 gameMode == AnalyzeFile)
10454 ResurrectChessProgram(); /* in case it isn't running */
10455 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
10456 gameMode = MachinePlaysWhite;
10459 gameMode = MachinePlaysWhite;
10463 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
10465 if (first.sendName) {
10466 sprintf(buf, "name %s\n", gameInfo.black);
10467 SendToProgram(buf, &first);
10469 if (first.sendTime) {
10470 if (first.useColors) {
10471 SendToProgram("black\n", &first); /*gnu kludge*/
10473 SendTimeRemaining(&first, TRUE);
10475 if (first.useColors) {
10476 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
10478 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
10479 SetMachineThinkingEnables();
10480 first.maybeThinking = TRUE;
10483 if (appData.autoFlipView && !flipView) {
10484 flipView = !flipView;
10485 DrawPosition(FALSE, NULL);
10486 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
10489 if(bookHit) { // [HGM] book: simulate book reply
10490 static char bookMove[MSG_SIZ]; // a bit generous?
10492 programStats.nodes = programStats.depth = programStats.time =
10493 programStats.score = programStats.got_only_move = 0;
10494 sprintf(programStats.movelist, "%s (xbook)", bookHit);
10496 strcpy(bookMove, "move ");
10497 strcat(bookMove, bookHit);
10498 HandleMachineMove(bookMove, &first);
10503 MachineBlackEvent()
10506 char *bookHit = NULL;
10508 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
10512 if (gameMode == PlayFromGameFile ||
10513 gameMode == TwoMachinesPlay ||
10514 gameMode == Training ||
10515 gameMode == AnalyzeMode ||
10516 gameMode == EndOfGame)
10519 if (gameMode == EditPosition)
10520 EditPositionDone();
10522 if (WhiteOnMove(currentMove)) {
10523 DisplayError(_("It is not Black's turn"), 0);
10527 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
10530 if (gameMode == EditGame || gameMode == AnalyzeMode ||
10531 gameMode == AnalyzeFile)
10534 ResurrectChessProgram(); /* in case it isn't running */
10535 gameMode = MachinePlaysBlack;
10539 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
10541 if (first.sendName) {
10542 sprintf(buf, "name %s\n", gameInfo.white);
10543 SendToProgram(buf, &first);
10545 if (first.sendTime) {
10546 if (first.useColors) {
10547 SendToProgram("white\n", &first); /*gnu kludge*/
10549 SendTimeRemaining(&first, FALSE);
10551 if (first.useColors) {
10552 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
10554 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
10555 SetMachineThinkingEnables();
10556 first.maybeThinking = TRUE;
10559 if (appData.autoFlipView && flipView) {
10560 flipView = !flipView;
10561 DrawPosition(FALSE, NULL);
10562 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
10564 if(bookHit) { // [HGM] book: simulate book reply
10565 static char bookMove[MSG_SIZ]; // a bit generous?
10567 programStats.nodes = programStats.depth = programStats.time =
10568 programStats.score = programStats.got_only_move = 0;
10569 sprintf(programStats.movelist, "%s (xbook)", bookHit);
10571 strcpy(bookMove, "move ");
10572 strcat(bookMove, bookHit);
10573 HandleMachineMove(bookMove, &first);
10579 DisplayTwoMachinesTitle()
10582 if (appData.matchGames > 0) {
10583 if (first.twoMachinesColor[0] == 'w') {
10584 sprintf(buf, "%s vs. %s (%d-%d-%d)",
10585 gameInfo.white, gameInfo.black,
10586 first.matchWins, second.matchWins,
10587 matchGame - 1 - (first.matchWins + second.matchWins));
10589 sprintf(buf, "%s vs. %s (%d-%d-%d)",
10590 gameInfo.white, gameInfo.black,
10591 second.matchWins, first.matchWins,
10592 matchGame - 1 - (first.matchWins + second.matchWins));
10595 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
10601 TwoMachinesEvent P((void))
10605 ChessProgramState *onmove;
10606 char *bookHit = NULL;
10608 if (appData.noChessProgram) return;
10610 switch (gameMode) {
10611 case TwoMachinesPlay:
10613 case MachinePlaysWhite:
10614 case MachinePlaysBlack:
10615 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
10616 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
10620 case BeginningOfGame:
10621 case PlayFromGameFile:
10624 if (gameMode != EditGame) return;
10627 EditPositionDone();
10638 forwardMostMove = currentMove;
10639 ResurrectChessProgram(); /* in case first program isn't running */
10641 if (second.pr == NULL) {
10642 StartChessProgram(&second);
10643 if (second.protocolVersion == 1) {
10644 TwoMachinesEventIfReady();
10646 /* kludge: allow timeout for initial "feature" command */
10648 DisplayMessage("", _("Starting second chess program"));
10649 ScheduleDelayedEvent(TwoMachinesEventIfReady, FEATURE_TIMEOUT);
10653 DisplayMessage("", "");
10654 InitChessProgram(&second, FALSE);
10655 SendToProgram("force\n", &second);
10656 if (startedFromSetupPosition) {
10657 SendBoard(&second, backwardMostMove);
10658 if (appData.debugMode) {
10659 fprintf(debugFP, "Two Machines\n");
10662 for (i = backwardMostMove; i < forwardMostMove; i++) {
10663 SendMoveToProgram(i, &second);
10666 gameMode = TwoMachinesPlay;
10670 DisplayTwoMachinesTitle();
10672 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
10678 SendToProgram(first.computerString, &first);
10679 if (first.sendName) {
10680 sprintf(buf, "name %s\n", second.tidy);
10681 SendToProgram(buf, &first);
10683 SendToProgram(second.computerString, &second);
10684 if (second.sendName) {
10685 sprintf(buf, "name %s\n", first.tidy);
10686 SendToProgram(buf, &second);
10690 if (!first.sendTime || !second.sendTime) {
10691 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
10692 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
10694 if (onmove->sendTime) {
10695 if (onmove->useColors) {
10696 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
10698 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
10700 if (onmove->useColors) {
10701 SendToProgram(onmove->twoMachinesColor, onmove);
10703 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
10704 // SendToProgram("go\n", onmove);
10705 onmove->maybeThinking = TRUE;
10706 SetMachineThinkingEnables();
10710 if(bookHit) { // [HGM] book: simulate book reply
10711 static char bookMove[MSG_SIZ]; // a bit generous?
10713 programStats.nodes = programStats.depth = programStats.time =
10714 programStats.score = programStats.got_only_move = 0;
10715 sprintf(programStats.movelist, "%s (xbook)", bookHit);
10717 strcpy(bookMove, "move ");
10718 strcat(bookMove, bookHit);
10719 HandleMachineMove(bookMove, &first);
10726 if (gameMode == Training) {
10727 SetTrainingModeOff();
10728 gameMode = PlayFromGameFile;
10729 DisplayMessage("", _("Training mode off"));
10731 gameMode = Training;
10732 animateTraining = appData.animate;
10734 /* make sure we are not already at the end of the game */
10735 if (currentMove < forwardMostMove) {
10736 SetTrainingModeOn();
10737 DisplayMessage("", _("Training mode on"));
10739 gameMode = PlayFromGameFile;
10740 DisplayError(_("Already at end of game"), 0);
10749 if (!appData.icsActive) return;
10750 switch (gameMode) {
10751 case IcsPlayingWhite:
10752 case IcsPlayingBlack:
10755 case BeginningOfGame:
10763 EditPositionDone();
10776 gameMode = IcsIdle;
10787 switch (gameMode) {
10789 SetTrainingModeOff();
10791 case MachinePlaysWhite:
10792 case MachinePlaysBlack:
10793 case BeginningOfGame:
10794 SendToProgram("force\n", &first);
10795 SetUserThinkingEnables();
10797 case PlayFromGameFile:
10798 (void) StopLoadGameTimer();
10799 if (gameFileFP != NULL) {
10804 EditPositionDone();
10809 SendToProgram("force\n", &first);
10811 case TwoMachinesPlay:
10812 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
10813 ResurrectChessProgram();
10814 SetUserThinkingEnables();
10817 ResurrectChessProgram();
10819 case IcsPlayingBlack:
10820 case IcsPlayingWhite:
10821 DisplayError(_("Warning: You are still playing a game"), 0);
10824 DisplayError(_("Warning: You are still observing a game"), 0);
10827 DisplayError(_("Warning: You are still examining a game"), 0);
10838 first.offeredDraw = second.offeredDraw = 0;
10840 if (gameMode == PlayFromGameFile) {
10841 whiteTimeRemaining = timeRemaining[0][currentMove];
10842 blackTimeRemaining = timeRemaining[1][currentMove];
10846 if (gameMode == MachinePlaysWhite ||
10847 gameMode == MachinePlaysBlack ||
10848 gameMode == TwoMachinesPlay ||
10849 gameMode == EndOfGame) {
10850 i = forwardMostMove;
10851 while (i > currentMove) {
10852 SendToProgram("undo\n", &first);
10855 whiteTimeRemaining = timeRemaining[0][currentMove];
10856 blackTimeRemaining = timeRemaining[1][currentMove];
10857 DisplayBothClocks();
10858 if (whiteFlag || blackFlag) {
10859 whiteFlag = blackFlag = 0;
10864 gameMode = EditGame;
10871 EditPositionEvent()
10873 if (gameMode == EditPosition) {
10879 if (gameMode != EditGame) return;
10881 gameMode = EditPosition;
10884 if (currentMove > 0)
10885 CopyBoard(boards[0], boards[currentMove]);
10887 blackPlaysFirst = !WhiteOnMove(currentMove);
10889 currentMove = forwardMostMove = backwardMostMove = 0;
10890 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
10897 /* [DM] icsEngineAnalyze - possible call from other functions */
10898 if (appData.icsEngineAnalyze) {
10899 appData.icsEngineAnalyze = FALSE;
10901 DisplayMessage("",_("Close ICS engine analyze..."));
10903 if (first.analysisSupport && first.analyzing) {
10904 SendToProgram("exit\n", &first);
10905 first.analyzing = FALSE;
10908 thinkOutput[0] = NULLCHAR;
10914 startedFromSetupPosition = TRUE;
10915 InitChessProgram(&first, FALSE);
10916 SendToProgram("force\n", &first);
10917 if (blackPlaysFirst) {
10918 strcpy(moveList[0], "");
10919 strcpy(parseList[0], "");
10920 currentMove = forwardMostMove = backwardMostMove = 1;
10921 CopyBoard(boards[1], boards[0]);
10922 /* [HGM] copy rights as well, as this code is also used after pasting a FEN */
10924 epStatus[1] = epStatus[0];
10925 for(i=0; i<nrCastlingRights; i++) castlingRights[1][i] = castlingRights[0][i];
10928 currentMove = forwardMostMove = backwardMostMove = 0;
10930 SendBoard(&first, forwardMostMove);
10931 if (appData.debugMode) {
10932 fprintf(debugFP, "EditPosDone\n");
10935 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
10936 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
10937 gameMode = EditGame;
10939 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
10940 ClearHighlights(); /* [AS] */
10943 /* Pause for `ms' milliseconds */
10944 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
10954 } while (SubtractTimeMarks(&m2, &m1) < ms);
10957 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
10959 SendMultiLineToICS(buf)
10962 char temp[MSG_SIZ+1], *p;
10969 strncpy(temp, buf, len);
10974 if (*p == '\n' || *p == '\r')
10979 strcat(temp, "\n");
10981 SendToPlayer(temp, strlen(temp));
10985 SetWhiteToPlayEvent()
10987 if (gameMode == EditPosition) {
10988 blackPlaysFirst = FALSE;
10989 DisplayBothClocks(); /* works because currentMove is 0 */
10990 } else if (gameMode == IcsExamining) {
10991 SendToICS(ics_prefix);
10992 SendToICS("tomove white\n");
10997 SetBlackToPlayEvent()
10999 if (gameMode == EditPosition) {
11000 blackPlaysFirst = TRUE;
11001 currentMove = 1; /* kludge */
11002 DisplayBothClocks();
11004 } else if (gameMode == IcsExamining) {
11005 SendToICS(ics_prefix);
11006 SendToICS("tomove black\n");
11011 EditPositionMenuEvent(selection, x, y)
11012 ChessSquare selection;
11016 ChessSquare piece = boards[0][y][x];
11018 if (gameMode != EditPosition && gameMode != IcsExamining) return;
11020 switch (selection) {
11022 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
11023 SendToICS(ics_prefix);
11024 SendToICS("bsetup clear\n");
11025 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
11026 SendToICS(ics_prefix);
11027 SendToICS("clearboard\n");
11029 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
11030 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
11031 for (y = 0; y < BOARD_HEIGHT; y++) {
11032 if (gameMode == IcsExamining) {
11033 if (boards[currentMove][y][x] != EmptySquare) {
11034 sprintf(buf, "%sx@%c%c\n", ics_prefix,
11039 boards[0][y][x] = p;
11044 if (gameMode == EditPosition) {
11045 DrawPosition(FALSE, boards[0]);
11050 SetWhiteToPlayEvent();
11054 SetBlackToPlayEvent();
11058 if (gameMode == IcsExamining) {
11059 sprintf(buf, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
11062 boards[0][y][x] = EmptySquare;
11063 DrawPosition(FALSE, boards[0]);
11068 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
11069 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
11070 selection = (ChessSquare) (PROMOTED piece);
11071 } else if(piece == EmptySquare) selection = WhiteSilver;
11072 else selection = (ChessSquare)((int)piece - 1);
11076 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
11077 piece > (int)BlackMan && piece <= (int)BlackKing ) {
11078 selection = (ChessSquare) (DEMOTED piece);
11079 } else if(piece == EmptySquare) selection = BlackSilver;
11080 else selection = (ChessSquare)((int)piece + 1);
11085 if(gameInfo.variant == VariantShatranj ||
11086 gameInfo.variant == VariantXiangqi ||
11087 gameInfo.variant == VariantCourier )
11088 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
11093 if(gameInfo.variant == VariantXiangqi)
11094 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
11095 if(gameInfo.variant == VariantKnightmate)
11096 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
11099 if (gameMode == IcsExamining) {
11100 sprintf(buf, "%s%c@%c%c\n", ics_prefix,
11101 PieceToChar(selection), AAA + x, ONE + y);
11104 boards[0][y][x] = selection;
11105 DrawPosition(FALSE, boards[0]);
11113 DropMenuEvent(selection, x, y)
11114 ChessSquare selection;
11117 ChessMove moveType;
11119 switch (gameMode) {
11120 case IcsPlayingWhite:
11121 case MachinePlaysBlack:
11122 if (!WhiteOnMove(currentMove)) {
11123 DisplayMoveError(_("It is Black's turn"));
11126 moveType = WhiteDrop;
11128 case IcsPlayingBlack:
11129 case MachinePlaysWhite:
11130 if (WhiteOnMove(currentMove)) {
11131 DisplayMoveError(_("It is White's turn"));
11134 moveType = BlackDrop;
11137 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
11143 if (moveType == BlackDrop && selection < BlackPawn) {
11144 selection = (ChessSquare) ((int) selection
11145 + (int) BlackPawn - (int) WhitePawn);
11147 if (boards[currentMove][y][x] != EmptySquare) {
11148 DisplayMoveError(_("That square is occupied"));
11152 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
11158 /* Accept a pending offer of any kind from opponent */
11160 if (appData.icsActive) {
11161 SendToICS(ics_prefix);
11162 SendToICS("accept\n");
11163 } else if (cmailMsgLoaded) {
11164 if (currentMove == cmailOldMove &&
11165 commentList[cmailOldMove] != NULL &&
11166 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
11167 "Black offers a draw" : "White offers a draw")) {
11169 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
11170 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
11172 DisplayError(_("There is no pending offer on this move"), 0);
11173 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
11176 /* Not used for offers from chess program */
11183 /* Decline a pending offer of any kind from opponent */
11185 if (appData.icsActive) {
11186 SendToICS(ics_prefix);
11187 SendToICS("decline\n");
11188 } else if (cmailMsgLoaded) {
11189 if (currentMove == cmailOldMove &&
11190 commentList[cmailOldMove] != NULL &&
11191 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
11192 "Black offers a draw" : "White offers a draw")) {
11194 AppendComment(cmailOldMove, "Draw declined");
11195 DisplayComment(cmailOldMove - 1, "Draw declined");
11198 DisplayError(_("There is no pending offer on this move"), 0);
11201 /* Not used for offers from chess program */
11208 /* Issue ICS rematch command */
11209 if (appData.icsActive) {
11210 SendToICS(ics_prefix);
11211 SendToICS("rematch\n");
11218 /* Call your opponent's flag (claim a win on time) */
11219 if (appData.icsActive) {
11220 SendToICS(ics_prefix);
11221 SendToICS("flag\n");
11223 switch (gameMode) {
11226 case MachinePlaysWhite:
11229 GameEnds(GameIsDrawn, "Both players ran out of time",
11232 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
11234 DisplayError(_("Your opponent is not out of time"), 0);
11237 case MachinePlaysBlack:
11240 GameEnds(GameIsDrawn, "Both players ran out of time",
11243 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
11245 DisplayError(_("Your opponent is not out of time"), 0);
11255 /* Offer draw or accept pending draw offer from opponent */
11257 if (appData.icsActive) {
11258 /* Note: tournament rules require draw offers to be
11259 made after you make your move but before you punch
11260 your clock. Currently ICS doesn't let you do that;
11261 instead, you immediately punch your clock after making
11262 a move, but you can offer a draw at any time. */
11264 SendToICS(ics_prefix);
11265 SendToICS("draw\n");
11266 } else if (cmailMsgLoaded) {
11267 if (currentMove == cmailOldMove &&
11268 commentList[cmailOldMove] != NULL &&
11269 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
11270 "Black offers a draw" : "White offers a draw")) {
11271 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
11272 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
11273 } else if (currentMove == cmailOldMove + 1) {
11274 char *offer = WhiteOnMove(cmailOldMove) ?
11275 "White offers a draw" : "Black offers a draw";
11276 AppendComment(currentMove, offer);
11277 DisplayComment(currentMove - 1, offer);
11278 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
11280 DisplayError(_("You must make your move before offering a draw"), 0);
11281 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
11283 } else if (first.offeredDraw) {
11284 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
11286 if (first.sendDrawOffers) {
11287 SendToProgram("draw\n", &first);
11288 userOfferedDraw = TRUE;
11296 /* Offer Adjourn or accept pending Adjourn offer from opponent */
11298 if (appData.icsActive) {
11299 SendToICS(ics_prefix);
11300 SendToICS("adjourn\n");
11302 /* Currently GNU Chess doesn't offer or accept Adjourns */
11310 /* Offer Abort or accept pending Abort offer from opponent */
11312 if (appData.icsActive) {
11313 SendToICS(ics_prefix);
11314 SendToICS("abort\n");
11316 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
11323 /* Resign. You can do this even if it's not your turn. */
11325 if (appData.icsActive) {
11326 SendToICS(ics_prefix);
11327 SendToICS("resign\n");
11329 switch (gameMode) {
11330 case MachinePlaysWhite:
11331 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
11333 case MachinePlaysBlack:
11334 GameEnds(BlackWins, "White resigns", GE_PLAYER);
11337 if (cmailMsgLoaded) {
11339 if (WhiteOnMove(cmailOldMove)) {
11340 GameEnds(BlackWins, "White resigns", GE_PLAYER);
11342 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
11344 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
11355 StopObservingEvent()
11357 /* Stop observing current games */
11358 SendToICS(ics_prefix);
11359 SendToICS("unobserve\n");
11363 StopExaminingEvent()
11365 /* Stop observing current game */
11366 SendToICS(ics_prefix);
11367 SendToICS("unexamine\n");
11371 ForwardInner(target)
11376 if (appData.debugMode)
11377 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
11378 target, currentMove, forwardMostMove);
11380 if (gameMode == EditPosition)
11383 if (gameMode == PlayFromGameFile && !pausing)
11386 if (gameMode == IcsExamining && pausing)
11387 limit = pauseExamForwardMostMove;
11389 limit = forwardMostMove;
11391 if (target > limit) target = limit;
11393 if (target > 0 && moveList[target - 1][0]) {
11394 int fromX, fromY, toX, toY;
11395 toX = moveList[target - 1][2] - AAA;
11396 toY = moveList[target - 1][3] - ONE;
11397 if (moveList[target - 1][1] == '@') {
11398 if (appData.highlightLastMove) {
11399 SetHighlights(-1, -1, toX, toY);
11402 fromX = moveList[target - 1][0] - AAA;
11403 fromY = moveList[target - 1][1] - ONE;
11404 if (target == currentMove + 1) {
11405 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
11407 if (appData.highlightLastMove) {
11408 SetHighlights(fromX, fromY, toX, toY);
11412 if (gameMode == EditGame || gameMode == AnalyzeMode ||
11413 gameMode == Training || gameMode == PlayFromGameFile ||
11414 gameMode == AnalyzeFile) {
11415 while (currentMove < target) {
11416 SendMoveToProgram(currentMove++, &first);
11419 currentMove = target;
11422 if (gameMode == EditGame || gameMode == EndOfGame) {
11423 whiteTimeRemaining = timeRemaining[0][currentMove];
11424 blackTimeRemaining = timeRemaining[1][currentMove];
11426 DisplayBothClocks();
11427 DisplayMove(currentMove - 1);
11428 DrawPosition(FALSE, boards[currentMove]);
11429 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
11430 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
11431 DisplayComment(currentMove - 1, commentList[currentMove]);
11439 if (gameMode == IcsExamining && !pausing) {
11440 SendToICS(ics_prefix);
11441 SendToICS("forward\n");
11443 ForwardInner(currentMove + 1);
11450 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
11451 /* to optimze, we temporarily turn off analysis mode while we feed
11452 * the remaining moves to the engine. Otherwise we get analysis output
11455 if (first.analysisSupport) {
11456 SendToProgram("exit\nforce\n", &first);
11457 first.analyzing = FALSE;
11461 if (gameMode == IcsExamining && !pausing) {
11462 SendToICS(ics_prefix);
11463 SendToICS("forward 999999\n");
11465 ForwardInner(forwardMostMove);
11468 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
11469 /* we have fed all the moves, so reactivate analysis mode */
11470 SendToProgram("analyze\n", &first);
11471 first.analyzing = TRUE;
11472 /*first.maybeThinking = TRUE;*/
11473 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11478 BackwardInner(target)
11481 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
11483 if (appData.debugMode)
11484 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
11485 target, currentMove, forwardMostMove);
11487 if (gameMode == EditPosition) return;
11488 if (currentMove <= backwardMostMove) {
11490 DrawPosition(full_redraw, boards[currentMove]);
11493 if (gameMode == PlayFromGameFile && !pausing)
11496 if (moveList[target][0]) {
11497 int fromX, fromY, toX, toY;
11498 toX = moveList[target][2] - AAA;
11499 toY = moveList[target][3] - ONE;
11500 if (moveList[target][1] == '@') {
11501 if (appData.highlightLastMove) {
11502 SetHighlights(-1, -1, toX, toY);
11505 fromX = moveList[target][0] - AAA;
11506 fromY = moveList[target][1] - ONE;
11507 if (target == currentMove - 1) {
11508 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
11510 if (appData.highlightLastMove) {
11511 SetHighlights(fromX, fromY, toX, toY);
11515 if (gameMode == EditGame || gameMode==AnalyzeMode ||
11516 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
11517 while (currentMove > target) {
11518 SendToProgram("undo\n", &first);
11522 currentMove = target;
11525 if (gameMode == EditGame || gameMode == EndOfGame) {
11526 whiteTimeRemaining = timeRemaining[0][currentMove];
11527 blackTimeRemaining = timeRemaining[1][currentMove];
11529 DisplayBothClocks();
11530 DisplayMove(currentMove - 1);
11531 DrawPosition(full_redraw, boards[currentMove]);
11532 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
11533 // [HGM] PV info: routine tests if comment empty
11534 DisplayComment(currentMove - 1, commentList[currentMove]);
11540 if (gameMode == IcsExamining && !pausing) {
11541 SendToICS(ics_prefix);
11542 SendToICS("backward\n");
11544 BackwardInner(currentMove - 1);
11551 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
11552 /* to optimze, we temporarily turn off analysis mode while we undo
11553 * all the moves. Otherwise we get analysis output after each undo.
11555 if (first.analysisSupport) {
11556 SendToProgram("exit\nforce\n", &first);
11557 first.analyzing = FALSE;
11561 if (gameMode == IcsExamining && !pausing) {
11562 SendToICS(ics_prefix);
11563 SendToICS("backward 999999\n");
11565 BackwardInner(backwardMostMove);
11568 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
11569 /* we have fed all the moves, so reactivate analysis mode */
11570 SendToProgram("analyze\n", &first);
11571 first.analyzing = TRUE;
11572 /*first.maybeThinking = TRUE;*/
11573 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11580 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
11581 if (to >= forwardMostMove) to = forwardMostMove;
11582 if (to <= backwardMostMove) to = backwardMostMove;
11583 if (to < currentMove) {
11593 if (gameMode != IcsExamining) {
11594 DisplayError(_("You are not examining a game"), 0);
11598 DisplayError(_("You can't revert while pausing"), 0);
11601 SendToICS(ics_prefix);
11602 SendToICS("revert\n");
11608 switch (gameMode) {
11609 case MachinePlaysWhite:
11610 case MachinePlaysBlack:
11611 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
11612 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
11615 if (forwardMostMove < 2) return;
11616 currentMove = forwardMostMove = forwardMostMove - 2;
11617 whiteTimeRemaining = timeRemaining[0][currentMove];
11618 blackTimeRemaining = timeRemaining[1][currentMove];
11619 DisplayBothClocks();
11620 DisplayMove(currentMove - 1);
11621 ClearHighlights();/*!! could figure this out*/
11622 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
11623 SendToProgram("remove\n", &first);
11624 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
11627 case BeginningOfGame:
11631 case IcsPlayingWhite:
11632 case IcsPlayingBlack:
11633 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
11634 SendToICS(ics_prefix);
11635 SendToICS("takeback 2\n");
11637 SendToICS(ics_prefix);
11638 SendToICS("takeback 1\n");
11647 ChessProgramState *cps;
11649 switch (gameMode) {
11650 case MachinePlaysWhite:
11651 if (!WhiteOnMove(forwardMostMove)) {
11652 DisplayError(_("It is your turn"), 0);
11657 case MachinePlaysBlack:
11658 if (WhiteOnMove(forwardMostMove)) {
11659 DisplayError(_("It is your turn"), 0);
11664 case TwoMachinesPlay:
11665 if (WhiteOnMove(forwardMostMove) ==
11666 (first.twoMachinesColor[0] == 'w')) {
11672 case BeginningOfGame:
11676 SendToProgram("?\n", cps);
11680 TruncateGameEvent()
11683 if (gameMode != EditGame) return;
11690 if (forwardMostMove > currentMove) {
11691 if (gameInfo.resultDetails != NULL) {
11692 free(gameInfo.resultDetails);
11693 gameInfo.resultDetails = NULL;
11694 gameInfo.result = GameUnfinished;
11696 forwardMostMove = currentMove;
11697 HistorySet(parseList, backwardMostMove, forwardMostMove,
11705 if (appData.noChessProgram) return;
11706 switch (gameMode) {
11707 case MachinePlaysWhite:
11708 if (WhiteOnMove(forwardMostMove)) {
11709 DisplayError(_("Wait until your turn"), 0);
11713 case BeginningOfGame:
11714 case MachinePlaysBlack:
11715 if (!WhiteOnMove(forwardMostMove)) {
11716 DisplayError(_("Wait until your turn"), 0);
11721 DisplayError(_("No hint available"), 0);
11724 SendToProgram("hint\n", &first);
11725 hintRequested = TRUE;
11731 if (appData.noChessProgram) return;
11732 switch (gameMode) {
11733 case MachinePlaysWhite:
11734 if (WhiteOnMove(forwardMostMove)) {
11735 DisplayError(_("Wait until your turn"), 0);
11739 case BeginningOfGame:
11740 case MachinePlaysBlack:
11741 if (!WhiteOnMove(forwardMostMove)) {
11742 DisplayError(_("Wait until your turn"), 0);
11747 EditPositionDone();
11749 case TwoMachinesPlay:
11754 SendToProgram("bk\n", &first);
11755 bookOutput[0] = NULLCHAR;
11756 bookRequested = TRUE;
11762 char *tags = PGNTags(&gameInfo);
11763 TagsPopUp(tags, CmailMsg());
11767 /* end button procedures */
11770 PrintPosition(fp, move)
11776 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
11777 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
11778 char c = PieceToChar(boards[move][i][j]);
11779 fputc(c == 'x' ? '.' : c, fp);
11780 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
11783 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
11784 fprintf(fp, "white to play\n");
11786 fprintf(fp, "black to play\n");
11793 if (gameInfo.white != NULL) {
11794 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
11800 /* Find last component of program's own name, using some heuristics */
11802 TidyProgramName(prog, host, buf)
11803 char *prog, *host, buf[MSG_SIZ];
11806 int local = (strcmp(host, "localhost") == 0);
11807 while (!local && (p = strchr(prog, ';')) != NULL) {
11809 while (*p == ' ') p++;
11812 if (*prog == '"' || *prog == '\'') {
11813 q = strchr(prog + 1, *prog);
11815 q = strchr(prog, ' ');
11817 if (q == NULL) q = prog + strlen(prog);
11819 while (p >= prog && *p != '/' && *p != '\\') p--;
11821 if(p == prog && *p == '"') p++;
11822 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) q -= 4;
11823 memcpy(buf, p, q - p);
11824 buf[q - p] = NULLCHAR;
11832 TimeControlTagValue()
11835 if (!appData.clockMode) {
11837 } else if (movesPerSession > 0) {
11838 sprintf(buf, "%d/%ld", movesPerSession, timeControl/1000);
11839 } else if (timeIncrement == 0) {
11840 sprintf(buf, "%ld", timeControl/1000);
11842 sprintf(buf, "%ld+%ld", timeControl/1000, timeIncrement/1000);
11844 return StrSave(buf);
11850 /* This routine is used only for certain modes */
11851 VariantClass v = gameInfo.variant;
11852 ClearGameInfo(&gameInfo);
11853 gameInfo.variant = v;
11855 switch (gameMode) {
11856 case MachinePlaysWhite:
11857 gameInfo.event = StrSave( appData.pgnEventHeader );
11858 gameInfo.site = StrSave(HostName());
11859 gameInfo.date = PGNDate();
11860 gameInfo.round = StrSave("-");
11861 gameInfo.white = StrSave(first.tidy);
11862 gameInfo.black = StrSave(UserName());
11863 gameInfo.timeControl = TimeControlTagValue();
11866 case MachinePlaysBlack:
11867 gameInfo.event = StrSave( appData.pgnEventHeader );
11868 gameInfo.site = StrSave(HostName());
11869 gameInfo.date = PGNDate();
11870 gameInfo.round = StrSave("-");
11871 gameInfo.white = StrSave(UserName());
11872 gameInfo.black = StrSave(first.tidy);
11873 gameInfo.timeControl = TimeControlTagValue();
11876 case TwoMachinesPlay:
11877 gameInfo.event = StrSave( appData.pgnEventHeader );
11878 gameInfo.site = StrSave(HostName());
11879 gameInfo.date = PGNDate();
11880 if (matchGame > 0) {
11882 sprintf(buf, "%d", matchGame);
11883 gameInfo.round = StrSave(buf);
11885 gameInfo.round = StrSave("-");
11887 if (first.twoMachinesColor[0] == 'w') {
11888 gameInfo.white = StrSave(first.tidy);
11889 gameInfo.black = StrSave(second.tidy);
11891 gameInfo.white = StrSave(second.tidy);
11892 gameInfo.black = StrSave(first.tidy);
11894 gameInfo.timeControl = TimeControlTagValue();
11898 gameInfo.event = StrSave("Edited game");
11899 gameInfo.site = StrSave(HostName());
11900 gameInfo.date = PGNDate();
11901 gameInfo.round = StrSave("-");
11902 gameInfo.white = StrSave("-");
11903 gameInfo.black = StrSave("-");
11907 gameInfo.event = StrSave("Edited position");
11908 gameInfo.site = StrSave(HostName());
11909 gameInfo.date = PGNDate();
11910 gameInfo.round = StrSave("-");
11911 gameInfo.white = StrSave("-");
11912 gameInfo.black = StrSave("-");
11915 case IcsPlayingWhite:
11916 case IcsPlayingBlack:
11921 case PlayFromGameFile:
11922 gameInfo.event = StrSave("Game from non-PGN file");
11923 gameInfo.site = StrSave(HostName());
11924 gameInfo.date = PGNDate();
11925 gameInfo.round = StrSave("-");
11926 gameInfo.white = StrSave("?");
11927 gameInfo.black = StrSave("?");
11936 ReplaceComment(index, text)
11942 while (*text == '\n') text++;
11943 len = strlen(text);
11944 while (len > 0 && text[len - 1] == '\n') len--;
11946 if (commentList[index] != NULL)
11947 free(commentList[index]);
11950 commentList[index] = NULL;
11953 commentList[index] = (char *) malloc(len + 2);
11954 strncpy(commentList[index], text, len);
11955 commentList[index][len] = '\n';
11956 commentList[index][len + 1] = NULLCHAR;
11969 if (ch == '\r') continue;
11971 } while (ch != '\0');
11975 AppendComment(index, text)
11982 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
11985 while (*text == '\n') text++;
11986 len = strlen(text);
11987 while (len > 0 && text[len - 1] == '\n') len--;
11989 if (len == 0) return;
11991 if (commentList[index] != NULL) {
11992 old = commentList[index];
11993 oldlen = strlen(old);
11994 commentList[index] = (char *) malloc(oldlen + len + 2);
11995 strcpy(commentList[index], old);
11997 strncpy(&commentList[index][oldlen], text, len);
11998 commentList[index][oldlen + len] = '\n';
11999 commentList[index][oldlen + len + 1] = NULLCHAR;
12001 commentList[index] = (char *) malloc(len + 2);
12002 strncpy(commentList[index], text, len);
12003 commentList[index][len] = '\n';
12004 commentList[index][len + 1] = NULLCHAR;
12008 static char * FindStr( char * text, char * sub_text )
12010 char * result = strstr( text, sub_text );
12012 if( result != NULL ) {
12013 result += strlen( sub_text );
12019 /* [AS] Try to extract PV info from PGN comment */
12020 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
12021 char *GetInfoFromComment( int index, char * text )
12025 if( text != NULL && index > 0 ) {
12028 int time = -1, sec = 0, deci;
12029 char * s_eval = FindStr( text, "[%eval " );
12030 char * s_emt = FindStr( text, "[%emt " );
12032 if( s_eval != NULL || s_emt != NULL ) {
12036 if( s_eval != NULL ) {
12037 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
12041 if( delim != ']' ) {
12046 if( s_emt != NULL ) {
12050 /* We expect something like: [+|-]nnn.nn/dd */
12053 sep = strchr( text, '/' );
12054 if( sep == NULL || sep < (text+4) ) {
12058 time = -1; sec = -1; deci = -1;
12059 if( sscanf( text, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
12060 sscanf( text, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
12061 sscanf( text, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
12062 sscanf( text, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
12066 if( score_lo < 0 || score_lo >= 100 ) {
12070 if(sec >= 0) time = 600*time + 10*sec; else
12071 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
12073 score = score >= 0 ? score*100 + score_lo : score*100 - score_lo;
12075 /* [HGM] PV time: now locate end of PV info */
12076 while( *++sep >= '0' && *sep <= '9'); // strip depth
12078 while( *++sep >= '0' && *sep <= '9'); // strip time
12080 while( *++sep >= '0' && *sep <= '9'); // strip seconds
12082 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
12083 while(*sep == ' ') sep++;
12094 pvInfoList[index-1].depth = depth;
12095 pvInfoList[index-1].score = score;
12096 pvInfoList[index-1].time = 10*time; // centi-sec
12102 SendToProgram(message, cps)
12104 ChessProgramState *cps;
12106 int count, outCount, error;
12109 if (cps->pr == NULL) return;
12112 if (appData.debugMode) {
12115 fprintf(debugFP, "%ld >%-6s: %s",
12116 SubtractTimeMarks(&now, &programStartTime),
12117 cps->which, message);
12120 count = strlen(message);
12121 outCount = OutputToProcess(cps->pr, message, count, &error);
12122 if (outCount < count && !exiting
12123 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
12124 sprintf(buf, _("Error writing to %s chess program"), cps->which);
12125 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
12126 if(epStatus[forwardMostMove] <= EP_DRAWS) {
12127 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
12128 sprintf(buf, "%s program exits in draw position (%s)", cps->which, cps->program);
12130 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
12132 gameInfo.resultDetails = buf;
12134 DisplayFatalError(buf, error, 1);
12139 ReceiveFromProgram(isr, closure, message, count, error)
12140 InputSourceRef isr;
12148 ChessProgramState *cps = (ChessProgramState *)closure;
12150 if (isr != cps->isr) return; /* Killed intentionally */
12154 _("Error: %s chess program (%s) exited unexpectedly"),
12155 cps->which, cps->program);
12156 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
12157 if(epStatus[forwardMostMove] <= EP_DRAWS) {
12158 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
12159 sprintf(buf, _("%s program exits in draw position (%s)"), cps->which, cps->program);
12161 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
12163 gameInfo.resultDetails = buf;
12165 RemoveInputSource(cps->isr);
12166 DisplayFatalError(buf, 0, 1);
12169 _("Error reading from %s chess program (%s)"),
12170 cps->which, cps->program);
12171 RemoveInputSource(cps->isr);
12173 /* [AS] Program is misbehaving badly... kill it */
12174 if( count == -2 ) {
12175 DestroyChildProcess( cps->pr, 9 );
12179 DisplayFatalError(buf, error, 1);
12184 if ((end_str = strchr(message, '\r')) != NULL)
12185 *end_str = NULLCHAR;
12186 if ((end_str = strchr(message, '\n')) != NULL)
12187 *end_str = NULLCHAR;
12189 if (appData.debugMode) {
12190 TimeMark now; int print = 1;
12191 char *quote = ""; char c; int i;
12193 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
12194 char start = message[0];
12195 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
12196 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
12197 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
12198 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
12199 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
12200 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
12201 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 && start != '#')
12202 { quote = "# "; print = (appData.engineComments == 2); }
12203 message[0] = start; // restore original message
12207 fprintf(debugFP, "%ld <%-6s: %s%s\n",
12208 SubtractTimeMarks(&now, &programStartTime), cps->which,
12214 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
12215 if (appData.icsEngineAnalyze) {
12216 if (strstr(message, "whisper") != NULL ||
12217 strstr(message, "kibitz") != NULL ||
12218 strstr(message, "tellics") != NULL) return;
12221 HandleMachineMove(message, cps);
12226 SendTimeControl(cps, mps, tc, inc, sd, st)
12227 ChessProgramState *cps;
12228 int mps, inc, sd, st;
12234 if( timeControl_2 > 0 ) {
12235 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
12236 tc = timeControl_2;
12239 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
12240 inc /= cps->timeOdds;
12241 st /= cps->timeOdds;
12243 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
12246 /* Set exact time per move, normally using st command */
12247 if (cps->stKludge) {
12248 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
12250 if (seconds == 0) {
12251 sprintf(buf, "level 1 %d\n", st/60);
12253 sprintf(buf, "level 1 %d:%02d\n", st/60, seconds);
12256 sprintf(buf, "st %d\n", st);
12259 /* Set conventional or incremental time control, using level command */
12260 if (seconds == 0) {
12261 /* Note old gnuchess bug -- minutes:seconds used to not work.
12262 Fixed in later versions, but still avoid :seconds
12263 when seconds is 0. */
12264 sprintf(buf, "level %d %ld %d\n", mps, tc/60000, inc/1000);
12266 sprintf(buf, "level %d %ld:%02d %d\n", mps, tc/60000,
12267 seconds, inc/1000);
12270 SendToProgram(buf, cps);
12272 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
12273 /* Orthogonally, limit search to given depth */
12275 if (cps->sdKludge) {
12276 sprintf(buf, "depth\n%d\n", sd);
12278 sprintf(buf, "sd %d\n", sd);
12280 SendToProgram(buf, cps);
12283 if(cps->nps > 0) { /* [HGM] nps */
12284 if(cps->supportsNPS == FALSE) cps->nps = -1; // don't use if engine explicitly says not supported!
12286 sprintf(buf, "nps %d\n", cps->nps);
12287 SendToProgram(buf, cps);
12292 ChessProgramState *WhitePlayer()
12293 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
12295 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
12296 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
12302 SendTimeRemaining(cps, machineWhite)
12303 ChessProgramState *cps;
12304 int /*boolean*/ machineWhite;
12306 char message[MSG_SIZ];
12309 /* Note: this routine must be called when the clocks are stopped
12310 or when they have *just* been set or switched; otherwise
12311 it will be off by the time since the current tick started.
12313 if (machineWhite) {
12314 time = whiteTimeRemaining / 10;
12315 otime = blackTimeRemaining / 10;
12317 time = blackTimeRemaining / 10;
12318 otime = whiteTimeRemaining / 10;
12320 /* [HGM] translate opponent's time by time-odds factor */
12321 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
12322 if (appData.debugMode) {
12323 fprintf(debugFP, "time odds: %d %d \n", cps->timeOdds, cps->other->timeOdds);
12326 if (time <= 0) time = 1;
12327 if (otime <= 0) otime = 1;
12329 sprintf(message, "time %ld\n", time);
12330 SendToProgram(message, cps);
12332 sprintf(message, "otim %ld\n", otime);
12333 SendToProgram(message, cps);
12337 BoolFeature(p, name, loc, cps)
12341 ChessProgramState *cps;
12344 int len = strlen(name);
12346 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
12348 sscanf(*p, "%d", &val);
12350 while (**p && **p != ' ') (*p)++;
12351 sprintf(buf, "accepted %s\n", name);
12352 SendToProgram(buf, cps);
12359 IntFeature(p, name, loc, cps)
12363 ChessProgramState *cps;
12366 int len = strlen(name);
12367 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
12369 sscanf(*p, "%d", loc);
12370 while (**p && **p != ' ') (*p)++;
12371 sprintf(buf, "accepted %s\n", name);
12372 SendToProgram(buf, cps);
12379 StringFeature(p, name, loc, cps)
12383 ChessProgramState *cps;
12386 int len = strlen(name);
12387 if (strncmp((*p), name, len) == 0
12388 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
12390 sscanf(*p, "%[^\"]", loc);
12391 while (**p && **p != '\"') (*p)++;
12392 if (**p == '\"') (*p)++;
12393 sprintf(buf, "accepted %s\n", name);
12394 SendToProgram(buf, cps);
12401 ParseOption(Option *opt, ChessProgramState *cps)
12402 // [HGM] options: process the string that defines an engine option, and determine
12403 // name, type, default value, and allowed value range
12405 char *p, *q, buf[MSG_SIZ];
12406 int n, min = (-1)<<31, max = 1<<31, def;
12408 if(p = strstr(opt->name, " -spin ")) {
12409 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
12410 if(max < min) max = min; // enforce consistency
12411 if(def < min) def = min;
12412 if(def > max) def = max;
12417 } else if((p = strstr(opt->name, " -slider "))) {
12418 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
12419 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
12420 if(max < min) max = min; // enforce consistency
12421 if(def < min) def = min;
12422 if(def > max) def = max;
12426 opt->type = Spin; // Slider;
12427 } else if((p = strstr(opt->name, " -string "))) {
12428 opt->textValue = p+9;
12429 opt->type = TextBox;
12430 } else if((p = strstr(opt->name, " -file "))) {
12431 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
12432 opt->textValue = p+7;
12433 opt->type = TextBox; // FileName;
12434 } else if((p = strstr(opt->name, " -path "))) {
12435 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
12436 opt->textValue = p+7;
12437 opt->type = TextBox; // PathName;
12438 } else if(p = strstr(opt->name, " -check ")) {
12439 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
12440 opt->value = (def != 0);
12441 opt->type = CheckBox;
12442 } else if(p = strstr(opt->name, " -combo ")) {
12443 opt->textValue = (char*) (&cps->comboList[cps->comboCnt]); // cheat with pointer type
12444 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
12445 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
12446 opt->value = n = 0;
12447 while(q = StrStr(q, " /// ")) {
12448 n++; *q = 0; // count choices, and null-terminate each of them
12450 if(*q == '*') { // remember default, which is marked with * prefix
12454 cps->comboList[cps->comboCnt++] = q;
12456 cps->comboList[cps->comboCnt++] = NULL;
12458 opt->type = ComboBox;
12459 } else if(p = strstr(opt->name, " -button")) {
12460 opt->type = Button;
12461 } else if(p = strstr(opt->name, " -save")) {
12462 opt->type = SaveButton;
12463 } else return FALSE;
12464 *p = 0; // terminate option name
12465 // now look if the command-line options define a setting for this engine option.
12466 if(cps->optionSettings && cps->optionSettings[0])
12467 p = strstr(cps->optionSettings, opt->name); else p = NULL;
12468 if(p && (p == cps->optionSettings || p[-1] == ',')) {
12469 sprintf(buf, "option %s", p);
12470 if(p = strstr(buf, ",")) *p = 0;
12472 SendToProgram(buf, cps);
12478 FeatureDone(cps, val)
12479 ChessProgramState* cps;
12482 DelayedEventCallback cb = GetDelayedEvent();
12483 if ((cb == InitBackEnd3 && cps == &first) ||
12484 (cb == TwoMachinesEventIfReady && cps == &second)) {
12485 CancelDelayedEvent();
12486 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
12488 cps->initDone = val;
12491 /* Parse feature command from engine */
12493 ParseFeatures(args, cps)
12495 ChessProgramState *cps;
12503 while (*p == ' ') p++;
12504 if (*p == NULLCHAR) return;
12506 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
12507 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
12508 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
12509 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
12510 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
12511 if (BoolFeature(&p, "reuse", &val, cps)) {
12512 /* Engine can disable reuse, but can't enable it if user said no */
12513 if (!val) cps->reuse = FALSE;
12516 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
12517 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
12518 if (gameMode == TwoMachinesPlay) {
12519 DisplayTwoMachinesTitle();
12525 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
12526 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
12527 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
12528 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
12529 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
12530 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
12531 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
12532 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
12533 if (BoolFeature(&p, "pause", &val, cps)) continue; /* unused at present */
12534 if (IntFeature(&p, "done", &val, cps)) {
12535 FeatureDone(cps, val);
12538 /* Added by Tord: */
12539 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
12540 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
12541 /* End of additions by Tord */
12543 /* [HGM] added features: */
12544 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
12545 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
12546 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
12547 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
12548 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
12549 if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
12550 if (StringFeature(&p, "option", &(cps->option[cps->nrOptions].name), cps)) {
12551 ParseOption(&(cps->option[cps->nrOptions++]), cps); // [HGM] options: add option feature
12552 if(cps->nrOptions >= MAX_OPTIONS) {
12554 sprintf(buf, "%s engine has too many options\n", cps->which);
12555 DisplayError(buf, 0);
12559 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
12560 /* End of additions by HGM */
12562 /* unknown feature: complain and skip */
12564 while (*q && *q != '=') q++;
12565 sprintf(buf, "rejected %.*s\n", q-p, p);
12566 SendToProgram(buf, cps);
12572 while (*p && *p != '\"') p++;
12573 if (*p == '\"') p++;
12575 while (*p && *p != ' ') p++;
12583 PeriodicUpdatesEvent(newState)
12586 if (newState == appData.periodicUpdates)
12589 appData.periodicUpdates=newState;
12591 /* Display type changes, so update it now */
12594 /* Get the ball rolling again... */
12596 AnalysisPeriodicEvent(1);
12597 StartAnalysisClock();
12602 PonderNextMoveEvent(newState)
12605 if (newState == appData.ponderNextMove) return;
12606 if (gameMode == EditPosition) EditPositionDone();
12608 SendToProgram("hard\n", &first);
12609 if (gameMode == TwoMachinesPlay) {
12610 SendToProgram("hard\n", &second);
12613 SendToProgram("easy\n", &first);
12614 thinkOutput[0] = NULLCHAR;
12615 if (gameMode == TwoMachinesPlay) {
12616 SendToProgram("easy\n", &second);
12619 appData.ponderNextMove = newState;
12623 NewSettingEvent(option, command, value)
12629 if (gameMode == EditPosition) EditPositionDone();
12630 sprintf(buf, "%s%s %d\n", (option ? "option ": ""), command, value);
12631 SendToProgram(buf, &first);
12632 if (gameMode == TwoMachinesPlay) {
12633 SendToProgram(buf, &second);
12638 ShowThinkingEvent()
12639 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
12641 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
12642 int newState = appData.showThinking
12643 // [HGM] thinking: other features now need thinking output as well
12644 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
12646 if (oldState == newState) return;
12647 oldState = newState;
12648 if (gameMode == EditPosition) EditPositionDone();
12650 SendToProgram("post\n", &first);
12651 if (gameMode == TwoMachinesPlay) {
12652 SendToProgram("post\n", &second);
12655 SendToProgram("nopost\n", &first);
12656 thinkOutput[0] = NULLCHAR;
12657 if (gameMode == TwoMachinesPlay) {
12658 SendToProgram("nopost\n", &second);
12661 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
12665 AskQuestionEvent(title, question, replyPrefix, which)
12666 char *title; char *question; char *replyPrefix; char *which;
12668 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
12669 if (pr == NoProc) return;
12670 AskQuestion(title, question, replyPrefix, pr);
12674 DisplayMove(moveNumber)
12677 char message[MSG_SIZ];
12679 char cpThinkOutput[MSG_SIZ];
12681 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
12683 if (moveNumber == forwardMostMove - 1 ||
12684 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
12686 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput));
12688 if (strchr(cpThinkOutput, '\n')) {
12689 *strchr(cpThinkOutput, '\n') = NULLCHAR;
12692 *cpThinkOutput = NULLCHAR;
12695 /* [AS] Hide thinking from human user */
12696 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
12697 *cpThinkOutput = NULLCHAR;
12698 if( thinkOutput[0] != NULLCHAR ) {
12701 for( i=0; i<=hiddenThinkOutputState; i++ ) {
12702 cpThinkOutput[i] = '.';
12704 cpThinkOutput[i] = NULLCHAR;
12705 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
12709 if (moveNumber == forwardMostMove - 1 &&
12710 gameInfo.resultDetails != NULL) {
12711 if (gameInfo.resultDetails[0] == NULLCHAR) {
12712 sprintf(res, " %s", PGNResult(gameInfo.result));
12714 sprintf(res, " {%s} %s",
12715 gameInfo.resultDetails, PGNResult(gameInfo.result));
12721 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
12722 DisplayMessage(res, cpThinkOutput);
12724 sprintf(message, "%d.%s%s%s", moveNumber / 2 + 1,
12725 WhiteOnMove(moveNumber) ? " " : ".. ",
12726 parseList[moveNumber], res);
12727 DisplayMessage(message, cpThinkOutput);
12732 DisplayAnalysisText(text)
12737 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile
12738 || appData.icsEngineAnalyze) {
12739 sprintf(buf, "Analysis (%s)", first.tidy);
12740 AnalysisPopUp(buf, text);
12748 while (*str && isspace(*str)) ++str;
12749 while (*str && !isspace(*str)) ++str;
12750 if (!*str) return 1;
12751 while (*str && isspace(*str)) ++str;
12752 if (!*str) return 1;
12760 char lst[MSG_SIZ / 2];
12762 static char *xtra[] = { "", " (--)", " (++)" };
12765 if (programStats.time == 0) {
12766 programStats.time = 1;
12769 if (programStats.got_only_move) {
12770 safeStrCpy(buf, programStats.movelist, sizeof(buf));
12772 safeStrCpy( lst, programStats.movelist, sizeof(lst));
12774 nps = (u64ToDouble(programStats.nodes) /
12775 ((double)programStats.time /100.0));
12777 cs = programStats.time % 100;
12778 s = programStats.time / 100;
12784 if (programStats.moves_left > 0 && appData.periodicUpdates) {
12785 if (programStats.move_name[0] != NULLCHAR) {
12786 sprintf(buf, "depth=%d %d/%d(%s) %+.2f %s%s\nNodes: " u64Display " NPS: %d\nTime: %02d:%02d:%02d.%02d",
12787 programStats.depth,
12788 programStats.nr_moves-programStats.moves_left,
12789 programStats.nr_moves, programStats.move_name,
12790 ((float)programStats.score)/100.0, lst,
12791 only_one_move(lst)?
12792 xtra[programStats.got_fail] : "",
12793 (u64)programStats.nodes, (int)nps, h, m, s, cs);
12795 sprintf(buf, "depth=%d %d/%d %+.2f %s%s\nNodes: " u64Display " NPS: %d\nTime: %02d:%02d:%02d.%02d",
12796 programStats.depth,
12797 programStats.nr_moves-programStats.moves_left,
12798 programStats.nr_moves, ((float)programStats.score)/100.0,
12800 only_one_move(lst)?
12801 xtra[programStats.got_fail] : "",
12802 (u64)programStats.nodes, (int)nps, h, m, s, cs);
12805 sprintf(buf, "depth=%d %+.2f %s%s\nNodes: " u64Display " NPS: %d\nTime: %02d:%02d:%02d.%02d",
12806 programStats.depth,
12807 ((float)programStats.score)/100.0,
12809 only_one_move(lst)?
12810 xtra[programStats.got_fail] : "",
12811 (u64)programStats.nodes, (int)nps, h, m, s, cs);
12814 DisplayAnalysisText(buf);
12818 DisplayComment(moveNumber, text)
12822 char title[MSG_SIZ];
12823 char buf[8000]; // comment can be long!
12826 if( appData.autoDisplayComment ) {
12827 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
12828 strcpy(title, "Comment");
12830 sprintf(title, "Comment on %d.%s%s", moveNumber / 2 + 1,
12831 WhiteOnMove(moveNumber) ? " " : ".. ",
12832 parseList[moveNumber]);
12834 // [HGM] PV info: display PV info together with (or as) comment
12835 if(moveNumber >= 0 && (depth = pvInfoList[moveNumber].depth) > 0) {
12836 if(text == NULL) text = "";
12837 score = pvInfoList[moveNumber].score;
12838 sprintf(buf, "%s%.2f/%d %d\n%s", score>0 ? "+" : "", score/100.,
12839 depth, (pvInfoList[moveNumber].time+50)/100, text);
12842 } else title[0] = 0;
12845 CommentPopUp(title, text);
12848 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
12849 * might be busy thinking or pondering. It can be omitted if your
12850 * gnuchess is configured to stop thinking immediately on any user
12851 * input. However, that gnuchess feature depends on the FIONREAD
12852 * ioctl, which does not work properly on some flavors of Unix.
12856 ChessProgramState *cps;
12859 if (!cps->useSigint) return;
12860 if (appData.noChessProgram || (cps->pr == NoProc)) return;
12861 switch (gameMode) {
12862 case MachinePlaysWhite:
12863 case MachinePlaysBlack:
12864 case TwoMachinesPlay:
12865 case IcsPlayingWhite:
12866 case IcsPlayingBlack:
12869 /* Skip if we know it isn't thinking */
12870 if (!cps->maybeThinking) return;
12871 if (appData.debugMode)
12872 fprintf(debugFP, "Interrupting %s\n", cps->which);
12873 InterruptChildProcess(cps->pr);
12874 cps->maybeThinking = FALSE;
12879 #endif /*ATTENTION*/
12885 if (whiteTimeRemaining <= 0) {
12888 if (appData.icsActive) {
12889 if (appData.autoCallFlag &&
12890 gameMode == IcsPlayingBlack && !blackFlag) {
12891 SendToICS(ics_prefix);
12892 SendToICS("flag\n");
12896 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
12898 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
12899 if (appData.autoCallFlag) {
12900 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
12907 if (blackTimeRemaining <= 0) {
12910 if (appData.icsActive) {
12911 if (appData.autoCallFlag &&
12912 gameMode == IcsPlayingWhite && !whiteFlag) {
12913 SendToICS(ics_prefix);
12914 SendToICS("flag\n");
12918 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
12920 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
12921 if (appData.autoCallFlag) {
12922 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
12935 if (!appData.clockMode || appData.icsActive ||
12936 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
12939 * add time to clocks when time control is achieved ([HGM] now also used for increment)
12941 if ( !WhiteOnMove(forwardMostMove) )
12942 /* White made time control */
12943 whiteTimeRemaining += GetTimeQuota((forwardMostMove-1)/2)
12944 /* [HGM] time odds: correct new time quota for time odds! */
12945 / WhitePlayer()->timeOdds;
12947 /* Black made time control */
12948 blackTimeRemaining += GetTimeQuota((forwardMostMove-1)/2)
12949 / WhitePlayer()->other->timeOdds;
12953 DisplayBothClocks()
12955 int wom = gameMode == EditPosition ?
12956 !blackPlaysFirst : WhiteOnMove(currentMove);
12957 DisplayWhiteClock(whiteTimeRemaining, wom);
12958 DisplayBlackClock(blackTimeRemaining, !wom);
12962 /* Timekeeping seems to be a portability nightmare. I think everyone
12963 has ftime(), but I'm really not sure, so I'm including some ifdefs
12964 to use other calls if you don't. Clocks will be less accurate if
12965 you have neither ftime nor gettimeofday.
12968 /* VS 2008 requires the #include outside of the function */
12969 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
12970 #include <sys/timeb.h>
12973 /* Get the current time as a TimeMark */
12978 #if HAVE_GETTIMEOFDAY
12980 struct timeval timeVal;
12981 struct timezone timeZone;
12983 gettimeofday(&timeVal, &timeZone);
12984 tm->sec = (long) timeVal.tv_sec;
12985 tm->ms = (int) (timeVal.tv_usec / 1000L);
12987 #else /*!HAVE_GETTIMEOFDAY*/
12990 // include <sys/timeb.h> / moved to just above start of function
12991 struct timeb timeB;
12994 tm->sec = (long) timeB.time;
12995 tm->ms = (int) timeB.millitm;
12997 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
12998 tm->sec = (long) time(NULL);
13004 /* Return the difference in milliseconds between two
13005 time marks. We assume the difference will fit in a long!
13008 SubtractTimeMarks(tm2, tm1)
13009 TimeMark *tm2, *tm1;
13011 return 1000L*(tm2->sec - tm1->sec) +
13012 (long) (tm2->ms - tm1->ms);
13017 * Code to manage the game clocks.
13019 * In tournament play, black starts the clock and then white makes a move.
13020 * We give the human user a slight advantage if he is playing white---the
13021 * clocks don't run until he makes his first move, so it takes zero time.
13022 * Also, we don't account for network lag, so we could get out of sync
13023 * with GNU Chess's clock -- but then, referees are always right.
13026 static TimeMark tickStartTM;
13027 static long intendedTickLength;
13030 NextTickLength(timeRemaining)
13031 long timeRemaining;
13033 long nominalTickLength, nextTickLength;
13035 if (timeRemaining > 0L && timeRemaining <= 10000L)
13036 nominalTickLength = 100L;
13038 nominalTickLength = 1000L;
13039 nextTickLength = timeRemaining % nominalTickLength;
13040 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
13042 return nextTickLength;
13045 /* Adjust clock one minute up or down */
13047 AdjustClock(Boolean which, int dir)
13049 if(which) blackTimeRemaining += 60000*dir;
13050 else whiteTimeRemaining += 60000*dir;
13051 DisplayBothClocks();
13054 /* Stop clocks and reset to a fresh time control */
13058 (void) StopClockTimer();
13059 if (appData.icsActive) {
13060 whiteTimeRemaining = blackTimeRemaining = 0;
13061 } else { /* [HGM] correct new time quote for time odds */
13062 whiteTimeRemaining = GetTimeQuota(-1) / WhitePlayer()->timeOdds;
13063 blackTimeRemaining = GetTimeQuota(-1) / WhitePlayer()->other->timeOdds;
13065 if (whiteFlag || blackFlag) {
13067 whiteFlag = blackFlag = FALSE;
13069 DisplayBothClocks();
13072 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
13074 /* Decrement running clock by amount of time that has passed */
13078 long timeRemaining;
13079 long lastTickLength, fudge;
13082 if (!appData.clockMode) return;
13083 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
13087 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
13089 /* Fudge if we woke up a little too soon */
13090 fudge = intendedTickLength - lastTickLength;
13091 if (fudge < 0 || fudge > FUDGE) fudge = 0;
13093 if (WhiteOnMove(forwardMostMove)) {
13094 if(whiteNPS >= 0) lastTickLength = 0;
13095 timeRemaining = whiteTimeRemaining -= lastTickLength;
13096 DisplayWhiteClock(whiteTimeRemaining - fudge,
13097 WhiteOnMove(currentMove));
13099 if(blackNPS >= 0) lastTickLength = 0;
13100 timeRemaining = blackTimeRemaining -= lastTickLength;
13101 DisplayBlackClock(blackTimeRemaining - fudge,
13102 !WhiteOnMove(currentMove));
13105 if (CheckFlags()) return;
13108 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
13109 StartClockTimer(intendedTickLength);
13111 /* if the time remaining has fallen below the alarm threshold, sound the
13112 * alarm. if the alarm has sounded and (due to a takeback or time control
13113 * with increment) the time remaining has increased to a level above the
13114 * threshold, reset the alarm so it can sound again.
13117 if (appData.icsActive && appData.icsAlarm) {
13119 /* make sure we are dealing with the user's clock */
13120 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
13121 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
13124 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
13125 alarmSounded = FALSE;
13126 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
13128 alarmSounded = TRUE;
13134 /* A player has just moved, so stop the previously running
13135 clock and (if in clock mode) start the other one.
13136 We redisplay both clocks in case we're in ICS mode, because
13137 ICS gives us an update to both clocks after every move.
13138 Note that this routine is called *after* forwardMostMove
13139 is updated, so the last fractional tick must be subtracted
13140 from the color that is *not* on move now.
13145 long lastTickLength;
13147 int flagged = FALSE;
13151 if (StopClockTimer() && appData.clockMode) {
13152 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
13153 if (WhiteOnMove(forwardMostMove)) {
13154 if(blackNPS >= 0) lastTickLength = 0;
13155 blackTimeRemaining -= lastTickLength;
13156 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
13157 // if(pvInfoList[forwardMostMove-1].time == -1)
13158 pvInfoList[forwardMostMove-1].time = // use GUI time
13159 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
13161 if(whiteNPS >= 0) lastTickLength = 0;
13162 whiteTimeRemaining -= lastTickLength;
13163 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
13164 // if(pvInfoList[forwardMostMove-1].time == -1)
13165 pvInfoList[forwardMostMove-1].time =
13166 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
13168 flagged = CheckFlags();
13170 CheckTimeControl();
13172 if (flagged || !appData.clockMode) return;
13174 switch (gameMode) {
13175 case MachinePlaysBlack:
13176 case MachinePlaysWhite:
13177 case BeginningOfGame:
13178 if (pausing) return;
13182 case PlayFromGameFile:
13191 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
13192 whiteTimeRemaining : blackTimeRemaining);
13193 StartClockTimer(intendedTickLength);
13197 /* Stop both clocks */
13201 long lastTickLength;
13204 if (!StopClockTimer()) return;
13205 if (!appData.clockMode) return;
13209 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
13210 if (WhiteOnMove(forwardMostMove)) {
13211 if(whiteNPS >= 0) lastTickLength = 0;
13212 whiteTimeRemaining -= lastTickLength;
13213 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
13215 if(blackNPS >= 0) lastTickLength = 0;
13216 blackTimeRemaining -= lastTickLength;
13217 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
13222 /* Start clock of player on move. Time may have been reset, so
13223 if clock is already running, stop and restart it. */
13227 (void) StopClockTimer(); /* in case it was running already */
13228 DisplayBothClocks();
13229 if (CheckFlags()) return;
13231 if (!appData.clockMode) return;
13232 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
13234 GetTimeMark(&tickStartTM);
13235 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
13236 whiteTimeRemaining : blackTimeRemaining);
13238 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
13239 whiteNPS = blackNPS = -1;
13240 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
13241 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
13242 whiteNPS = first.nps;
13243 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
13244 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
13245 blackNPS = first.nps;
13246 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
13247 whiteNPS = second.nps;
13248 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
13249 blackNPS = second.nps;
13250 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
13252 StartClockTimer(intendedTickLength);
13259 long second, minute, hour, day;
13261 static char buf[32];
13263 if (ms > 0 && ms <= 9900) {
13264 /* convert milliseconds to tenths, rounding up */
13265 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
13267 sprintf(buf, " %03.1f ", tenths/10.0);
13271 /* convert milliseconds to seconds, rounding up */
13272 /* use floating point to avoid strangeness of integer division
13273 with negative dividends on many machines */
13274 second = (long) floor(((double) (ms + 999L)) / 1000.0);
13281 day = second / (60 * 60 * 24);
13282 second = second % (60 * 60 * 24);
13283 hour = second / (60 * 60);
13284 second = second % (60 * 60);
13285 minute = second / 60;
13286 second = second % 60;
13289 sprintf(buf, " %s%ld:%02ld:%02ld:%02ld ",
13290 sign, day, hour, minute, second);
13292 sprintf(buf, " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
13294 sprintf(buf, " %s%2ld:%02ld ", sign, minute, second);
13301 * This is necessary because some C libraries aren't ANSI C compliant yet.
13304 StrStr(string, match)
13305 char *string, *match;
13309 length = strlen(match);
13311 for (i = strlen(string) - length; i >= 0; i--, string++)
13312 if (!strncmp(match, string, length))
13319 StrCaseStr(string, match)
13320 char *string, *match;
13324 length = strlen(match);
13326 for (i = strlen(string) - length; i >= 0; i--, string++) {
13327 for (j = 0; j < length; j++) {
13328 if (ToLower(match[j]) != ToLower(string[j]))
13331 if (j == length) return string;
13345 c1 = ToLower(*s1++);
13346 c2 = ToLower(*s2++);
13347 if (c1 > c2) return 1;
13348 if (c1 < c2) return -1;
13349 if (c1 == NULLCHAR) return 0;
13358 return isupper(c) ? tolower(c) : c;
13366 return islower(c) ? toupper(c) : c;
13368 #endif /* !_amigados */
13376 if ((ret = (char *) malloc(strlen(s) + 1))) {
13383 StrSavePtr(s, savePtr)
13384 char *s, **savePtr;
13389 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
13390 strcpy(*savePtr, s);
13402 clock = time((time_t *)NULL);
13403 tm = localtime(&clock);
13404 sprintf(buf, "%04d.%02d.%02d",
13405 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
13406 return StrSave(buf);
13411 PositionToFEN(move, overrideCastling)
13413 char *overrideCastling;
13415 int i, j, fromX, fromY, toX, toY;
13422 whiteToPlay = (gameMode == EditPosition) ?
13423 !blackPlaysFirst : (move % 2 == 0);
13426 /* Piece placement data */
13427 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
13429 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
13430 if (boards[move][i][j] == EmptySquare) {
13432 } else { ChessSquare piece = boards[move][i][j];
13433 if (emptycount > 0) {
13434 if(emptycount<10) /* [HGM] can be >= 10 */
13435 *p++ = '0' + emptycount;
13436 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
13439 if(PieceToChar(piece) == '+') {
13440 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
13442 piece = (ChessSquare)(DEMOTED piece);
13444 *p++ = PieceToChar(piece);
13446 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
13447 p[-1] = PieceToChar((ChessSquare)(DEMOTED piece));
13452 if (emptycount > 0) {
13453 if(emptycount<10) /* [HGM] can be >= 10 */
13454 *p++ = '0' + emptycount;
13455 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
13462 /* [HGM] print Crazyhouse or Shogi holdings */
13463 if( gameInfo.holdingsWidth ) {
13464 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
13466 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
13467 piece = boards[move][i][BOARD_WIDTH-1];
13468 if( piece != EmptySquare )
13469 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
13470 *p++ = PieceToChar(piece);
13472 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
13473 piece = boards[move][BOARD_HEIGHT-i-1][0];
13474 if( piece != EmptySquare )
13475 for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
13476 *p++ = PieceToChar(piece);
13479 if( q == p ) *p++ = '-';
13485 *p++ = whiteToPlay ? 'w' : 'b';
13488 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
13489 while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' ';
13491 if(nrCastlingRights) {
13493 if(gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) {
13494 /* [HGM] write directly from rights */
13495 if(castlingRights[move][2] >= 0 &&
13496 castlingRights[move][0] >= 0 )
13497 *p++ = castlingRights[move][0] + AAA + 'A' - 'a';
13498 if(castlingRights[move][2] >= 0 &&
13499 castlingRights[move][1] >= 0 )
13500 *p++ = castlingRights[move][1] + AAA + 'A' - 'a';
13501 if(castlingRights[move][5] >= 0 &&
13502 castlingRights[move][3] >= 0 )
13503 *p++ = castlingRights[move][3] + AAA;
13504 if(castlingRights[move][5] >= 0 &&
13505 castlingRights[move][4] >= 0 )
13506 *p++ = castlingRights[move][4] + AAA;
13509 /* [HGM] write true castling rights */
13510 if( nrCastlingRights == 6 ) {
13511 if(castlingRights[move][0] == BOARD_RGHT-1 &&
13512 castlingRights[move][2] >= 0 ) *p++ = 'K';
13513 if(castlingRights[move][1] == BOARD_LEFT &&
13514 castlingRights[move][2] >= 0 ) *p++ = 'Q';
13515 if(castlingRights[move][3] == BOARD_RGHT-1 &&
13516 castlingRights[move][5] >= 0 ) *p++ = 'k';
13517 if(castlingRights[move][4] == BOARD_LEFT &&
13518 castlingRights[move][5] >= 0 ) *p++ = 'q';
13521 if (q == p) *p++ = '-'; /* No castling rights */
13525 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
13526 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier ) {
13527 /* En passant target square */
13528 if (move > backwardMostMove) {
13529 fromX = moveList[move - 1][0] - AAA;
13530 fromY = moveList[move - 1][1] - ONE;
13531 toX = moveList[move - 1][2] - AAA;
13532 toY = moveList[move - 1][3] - ONE;
13533 if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
13534 toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
13535 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
13537 /* 2-square pawn move just happened */
13539 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
13550 /* [HGM] find reversible plies */
13551 { int i = 0, j=move;
13553 if (appData.debugMode) { int k;
13554 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
13555 for(k=backwardMostMove; k<=forwardMostMove; k++)
13556 fprintf(debugFP, "e%d. p=%d\n", k, epStatus[k]);
13560 while(j > backwardMostMove && epStatus[j] <= EP_NONE) j--,i++;
13561 if( j == backwardMostMove ) i += initialRulePlies;
13562 sprintf(p, "%d ", i);
13563 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
13565 /* Fullmove number */
13566 sprintf(p, "%d", (move / 2) + 1);
13568 return StrSave(buf);
13572 ParseFEN(board, blackPlaysFirst, fen)
13574 int *blackPlaysFirst;
13584 /* [HGM] by default clear Crazyhouse holdings, if present */
13585 if(gameInfo.holdingsWidth) {
13586 for(i=0; i<BOARD_HEIGHT; i++) {
13587 board[i][0] = EmptySquare; /* black holdings */
13588 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
13589 board[i][1] = (ChessSquare) 0; /* black counts */
13590 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
13594 /* Piece placement data */
13595 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
13598 if (*p == '/' || *p == ' ' || (*p == '[' && i == 0) ) {
13599 if (*p == '/') p++;
13600 emptycount = gameInfo.boardWidth - j;
13601 while (emptycount--)
13602 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
13604 #if(BOARD_SIZE >= 10)
13605 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
13606 p++; emptycount=10;
13607 if (j + emptycount > gameInfo.boardWidth) return FALSE;
13608 while (emptycount--)
13609 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
13611 } else if (isdigit(*p)) {
13612 emptycount = *p++ - '0';
13613 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
13614 if (j + emptycount > gameInfo.boardWidth) return FALSE;
13615 while (emptycount--)
13616 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
13617 } else if (*p == '+' || isalpha(*p)) {
13618 if (j >= gameInfo.boardWidth) return FALSE;
13620 piece = CharToPiece(*++p);
13621 if(piece == EmptySquare) return FALSE; /* unknown piece */
13622 piece = (ChessSquare) (PROMOTED piece ); p++;
13623 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
13624 } else piece = CharToPiece(*p++);
13626 if(piece==EmptySquare) return FALSE; /* unknown piece */
13627 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
13628 piece = (ChessSquare) (PROMOTED piece);
13629 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
13632 board[i][(j++)+gameInfo.holdingsWidth] = piece;
13638 while (*p == '/' || *p == ' ') p++;
13640 /* [HGM] look for Crazyhouse holdings here */
13641 while(*p==' ') p++;
13642 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
13644 if(*p == '-' ) *p++; /* empty holdings */ else {
13645 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
13646 /* if we would allow FEN reading to set board size, we would */
13647 /* have to add holdings and shift the board read so far here */
13648 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
13650 if((int) piece >= (int) BlackPawn ) {
13651 i = (int)piece - (int)BlackPawn;
13652 i = PieceToNumber((ChessSquare)i);
13653 if( i >= gameInfo.holdingsSize ) return FALSE;
13654 board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
13655 board[BOARD_HEIGHT-1-i][1]++; /* black counts */
13657 i = (int)piece - (int)WhitePawn;
13658 i = PieceToNumber((ChessSquare)i);
13659 if( i >= gameInfo.holdingsSize ) return FALSE;
13660 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
13661 board[i][BOARD_WIDTH-2]++; /* black holdings */
13665 if(*p == ']') *p++;
13668 while(*p == ' ') p++;
13673 *blackPlaysFirst = FALSE;
13676 *blackPlaysFirst = TRUE;
13682 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
13683 /* return the extra info in global variiables */
13685 /* set defaults in case FEN is incomplete */
13686 FENepStatus = EP_UNKNOWN;
13687 for(i=0; i<nrCastlingRights; i++ ) {
13688 FENcastlingRights[i] =
13689 gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom ? -1 : initialRights[i];
13690 } /* assume possible unless obviously impossible */
13691 if(initialRights[0]>=0 && board[castlingRank[0]][initialRights[0]] != WhiteRook) FENcastlingRights[0] = -1;
13692 if(initialRights[1]>=0 && board[castlingRank[1]][initialRights[1]] != WhiteRook) FENcastlingRights[1] = -1;
13693 if(initialRights[2]>=0 && board[castlingRank[2]][initialRights[2]] != WhiteKing) FENcastlingRights[2] = -1;
13694 if(initialRights[3]>=0 && board[castlingRank[3]][initialRights[3]] != BlackRook) FENcastlingRights[3] = -1;
13695 if(initialRights[4]>=0 && board[castlingRank[4]][initialRights[4]] != BlackRook) FENcastlingRights[4] = -1;
13696 if(initialRights[5]>=0 && board[castlingRank[5]][initialRights[5]] != BlackKing) FENcastlingRights[5] = -1;
13699 while(*p==' ') p++;
13700 if(nrCastlingRights) {
13701 if(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-') {
13702 /* castling indicator present, so default becomes no castlings */
13703 for(i=0; i<nrCastlingRights; i++ ) {
13704 FENcastlingRights[i] = -1;
13707 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
13708 (gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) &&
13709 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
13710 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
13711 char c = *p++; int whiteKingFile=-1, blackKingFile=-1;
13713 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
13714 if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
13715 if(board[0 ][i] == WhiteKing) whiteKingFile = i;
13719 for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
13720 FENcastlingRights[0] = i != whiteKingFile ? i : -1;
13721 FENcastlingRights[2] = whiteKingFile;
13724 for(i=BOARD_LEFT; board[0][i]!=WhiteRook && i<whiteKingFile; i++);
13725 FENcastlingRights[1] = i != whiteKingFile ? i : -1;
13726 FENcastlingRights[2] = whiteKingFile;
13729 for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
13730 FENcastlingRights[3] = i != blackKingFile ? i : -1;
13731 FENcastlingRights[5] = blackKingFile;
13734 for(i=BOARD_LEFT; board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
13735 FENcastlingRights[4] = i != blackKingFile ? i : -1;
13736 FENcastlingRights[5] = blackKingFile;
13739 default: /* FRC castlings */
13740 if(c >= 'a') { /* black rights */
13741 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
13742 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
13743 if(i == BOARD_RGHT) break;
13744 FENcastlingRights[5] = i;
13746 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
13747 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
13749 FENcastlingRights[3] = c;
13751 FENcastlingRights[4] = c;
13752 } else { /* white rights */
13753 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
13754 if(board[0][i] == WhiteKing) break;
13755 if(i == BOARD_RGHT) break;
13756 FENcastlingRights[2] = i;
13757 c -= AAA - 'a' + 'A';
13758 if(board[0][c] >= WhiteKing) break;
13760 FENcastlingRights[0] = c;
13762 FENcastlingRights[1] = c;
13766 if (appData.debugMode) {
13767 fprintf(debugFP, "FEN castling rights:");
13768 for(i=0; i<nrCastlingRights; i++)
13769 fprintf(debugFP, " %d", FENcastlingRights[i]);
13770 fprintf(debugFP, "\n");
13773 while(*p==' ') p++;
13776 /* read e.p. field in games that know e.p. capture */
13777 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
13778 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier ) {
13780 p++; FENepStatus = EP_NONE;
13782 char c = *p++ - AAA;
13784 if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
13785 if(*p >= '0' && *p <='9') *p++;
13791 if(sscanf(p, "%d", &i) == 1) {
13792 FENrulePlies = i; /* 50-move ply counter */
13793 /* (The move number is still ignored) */
13800 EditPositionPasteFEN(char *fen)
13803 Board initial_position;
13805 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
13806 DisplayError(_("Bad FEN position in clipboard"), 0);
13809 int savedBlackPlaysFirst = blackPlaysFirst;
13810 EditPositionEvent();
13811 blackPlaysFirst = savedBlackPlaysFirst;
13812 CopyBoard(boards[0], initial_position);
13813 /* [HGM] copy FEN attributes as well */
13815 initialRulePlies = FENrulePlies;
13816 epStatus[0] = FENepStatus;
13817 for( i=0; i<nrCastlingRights; i++ )
13818 castlingRights[0][i] = FENcastlingRights[i];
13820 EditPositionDone();
13821 DisplayBothClocks();
13822 DrawPosition(FALSE, boards[currentMove]);