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, 2010 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>
81 #else /* not STDC_HEADERS */
84 # else /* not HAVE_STRING_H */
86 # endif /* not HAVE_STRING_H */
87 #endif /* not STDC_HEADERS */
90 # include <sys/fcntl.h>
91 #else /* not HAVE_SYS_FCNTL_H */
94 # endif /* HAVE_FCNTL_H */
95 #endif /* not HAVE_SYS_FCNTL_H */
97 #if TIME_WITH_SYS_TIME
98 # include <sys/time.h>
102 # include <sys/time.h>
108 #if defined(_amigados) && !defined(__GNUC__)
113 extern int gettimeofday(struct timeval *, struct timezone *);
121 #include "frontend.h"
128 #include "backendz.h"
132 # define _(s) gettext (s)
133 # define N_(s) gettext_noop (s)
140 /* A point in time */
142 long sec; /* Assuming this is >= 32 bits */
143 int ms; /* Assuming this is >= 16 bits */
146 int establish P((void));
147 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
148 char *buf, int count, int error));
149 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
150 char *buf, int count, int error));
151 void ics_printf P((char *format, ...));
152 void SendToICS P((char *s));
153 void SendToICSDelayed P((char *s, long msdelay));
154 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY,
156 void HandleMachineMove P((char *message, ChessProgramState *cps));
157 int AutoPlayOneMove P((void));
158 int LoadGameOneMove P((ChessMove readAhead));
159 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
160 int LoadPositionFromFile P((char *filename, int n, char *title));
161 int SavePositionToFile P((char *filename));
162 void ApplyMove P((int fromX, int fromY, int toX, int toY, int promoChar,
164 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
165 void ShowMove P((int fromX, int fromY, int toX, int toY));
166 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
167 /*char*/int promoChar));
168 void BackwardInner P((int target));
169 void ForwardInner P((int target));
170 int Adjudicate P((ChessProgramState *cps));
171 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
172 void EditPositionDone P((Boolean fakeRights));
173 void PrintOpponents P((FILE *fp));
174 void PrintPosition P((FILE *fp, int move));
175 void StartChessProgram P((ChessProgramState *cps));
176 void SendToProgram P((char *message, ChessProgramState *cps));
177 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
178 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
179 char *buf, int count, int error));
180 void SendTimeControl P((ChessProgramState *cps,
181 int mps, long tc, int inc, int sd, int st));
182 char *TimeControlTagValue P((void));
183 void Attention P((ChessProgramState *cps));
184 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
185 void ResurrectChessProgram P((void));
186 void DisplayComment P((int moveNumber, char *text));
187 void DisplayMove P((int moveNumber));
189 void ParseGameHistory P((char *game));
190 void ParseBoard12 P((char *string));
191 void KeepAlive P((void));
192 void StartClocks P((void));
193 void SwitchClocks P((int nr));
194 void StopClocks P((void));
195 void ResetClocks P((void));
196 char *PGNDate P((void));
197 void SetGameInfo P((void));
198 Boolean ParseFEN P((Board board, int *blackPlaysFirst, char *fen));
199 int RegisterMove P((void));
200 void MakeRegisteredMove P((void));
201 void TruncateGame P((void));
202 int looking_at P((char *, int *, char *));
203 void CopyPlayerNameIntoFileName P((char **, char *));
204 char *SavePart P((char *));
205 int SaveGameOldStyle P((FILE *));
206 int SaveGamePGN P((FILE *));
207 void GetTimeMark P((TimeMark *));
208 long SubtractTimeMarks P((TimeMark *, TimeMark *));
209 int CheckFlags P((void));
210 long NextTickLength P((long));
211 void CheckTimeControl P((void));
212 void show_bytes P((FILE *, char *, int));
213 int string_to_rating P((char *str));
214 void ParseFeatures P((char* args, ChessProgramState *cps));
215 void InitBackEnd3 P((void));
216 void FeatureDone P((ChessProgramState* cps, int val));
217 void InitChessProgram P((ChessProgramState *cps, int setup));
218 void OutputKibitz(int window, char *text);
219 int PerpetualChase(int first, int last);
220 int EngineOutputIsUp();
221 void InitDrawingSizes(int x, int y);
224 extern void ConsoleCreate();
227 ChessProgramState *WhitePlayer();
228 void InsertIntoMemo P((int which, char *text)); // [HGM] kibitz: in engineo.c
229 int VerifyDisplayMode P(());
231 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
232 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
233 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
234 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
235 void ics_update_width P((int new_width));
236 extern char installDir[MSG_SIZ];
237 VariantClass startVariant; /* [HGM] nicks: initial variant */
239 extern int tinyLayout, smallLayout;
240 ChessProgramStats programStats;
241 char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
243 static int exiting = 0; /* [HGM] moved to top */
244 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
245 int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
246 Board partnerBoard; /* [HGM] bughouse: for peeking at partner game */
247 int partnerHighlight[2];
248 Boolean partnerBoardValid = 0;
249 char partnerStatus[MSG_SIZ];
251 Boolean originalFlip;
252 Boolean twoBoards = 0;
253 char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
254 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
255 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
256 int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
257 Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing */
258 int opponentKibitzes;
259 int lastSavedGame; /* [HGM] save: ID of game */
260 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
261 extern int chatCount;
263 char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
265 /* States for ics_getting_history */
267 #define H_REQUESTED 1
268 #define H_GOT_REQ_HEADER 2
269 #define H_GOT_UNREQ_HEADER 3
270 #define H_GETTING_MOVES 4
271 #define H_GOT_UNWANTED_HEADER 5
273 /* whosays values for GameEnds */
282 /* Maximum number of games in a cmail message */
283 #define CMAIL_MAX_GAMES 20
285 /* Different types of move when calling RegisterMove */
287 #define CMAIL_RESIGN 1
289 #define CMAIL_ACCEPT 3
291 /* Different types of result to remember for each game */
292 #define CMAIL_NOT_RESULT 0
293 #define CMAIL_OLD_RESULT 1
294 #define CMAIL_NEW_RESULT 2
296 /* Telnet protocol constants */
307 static char * safeStrCpy( char * dst, const char * src, size_t count )
309 assert( dst != NULL );
310 assert( src != NULL );
313 strncpy( dst, src, count );
314 dst[ count-1 ] = '\0';
318 /* Some compiler can't cast u64 to double
319 * This function do the job for us:
321 * We use the highest bit for cast, this only
322 * works if the highest bit is not
323 * in use (This should not happen)
325 * We used this for all compiler
328 u64ToDouble(u64 value)
331 u64 tmp = value & u64Const(0x7fffffffffffffff);
332 r = (double)(s64)tmp;
333 if (value & u64Const(0x8000000000000000))
334 r += 9.2233720368547758080e18; /* 2^63 */
338 /* Fake up flags for now, as we aren't keeping track of castling
339 availability yet. [HGM] Change of logic: the flag now only
340 indicates the type of castlings allowed by the rule of the game.
341 The actual rights themselves are maintained in the array
342 castlingRights, as part of the game history, and are not probed
348 int flags = F_ALL_CASTLE_OK;
349 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
350 switch (gameInfo.variant) {
352 flags &= ~F_ALL_CASTLE_OK;
353 case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
354 flags |= F_IGNORE_CHECK;
356 flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
359 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
361 case VariantKriegspiel:
362 flags |= F_KRIEGSPIEL_CAPTURE;
364 case VariantCapaRandom:
365 case VariantFischeRandom:
366 flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
367 case VariantNoCastle:
368 case VariantShatranj:
371 flags &= ~F_ALL_CASTLE_OK;
379 FILE *gameFileFP, *debugFP;
382 [AS] Note: sometimes, the sscanf() function is used to parse the input
383 into a fixed-size buffer. Because of this, we must be prepared to
384 receive strings as long as the size of the input buffer, which is currently
385 set to 4K for Windows and 8K for the rest.
386 So, we must either allocate sufficiently large buffers here, or
387 reduce the size of the input buffer in the input reading part.
390 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
391 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
392 char thinkOutput1[MSG_SIZ*10];
394 ChessProgramState first, second;
396 /* premove variables */
399 int premoveFromX = 0;
400 int premoveFromY = 0;
401 int premovePromoChar = 0;
403 Boolean alarmSounded;
404 /* end premove variables */
406 char *ics_prefix = "$";
407 int ics_type = ICS_GENERIC;
409 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
410 int pauseExamForwardMostMove = 0;
411 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
412 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
413 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
414 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
415 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
416 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
417 int whiteFlag = FALSE, blackFlag = FALSE;
418 int userOfferedDraw = FALSE;
419 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
420 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
421 int cmailMoveType[CMAIL_MAX_GAMES];
422 long ics_clock_paused = 0;
423 ProcRef icsPR = NoProc, cmailPR = NoProc;
424 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
425 GameMode gameMode = BeginningOfGame;
426 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
427 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
428 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
429 int hiddenThinkOutputState = 0; /* [AS] */
430 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
431 int adjudicateLossPlies = 6;
432 char white_holding[64], black_holding[64];
433 TimeMark lastNodeCountTime;
434 long lastNodeCount=0;
435 int have_sent_ICS_logon = 0;
437 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement;
438 long timeControl_2; /* [AS] Allow separate time controls */
439 char *fullTimeControlString = NULL; /* [HGM] secondary TC: merge of MPS, TC and inc */
440 long timeRemaining[2][MAX_MOVES];
442 TimeMark programStartTime;
443 char ics_handle[MSG_SIZ];
444 int have_set_title = 0;
446 /* animateTraining preserves the state of appData.animate
447 * when Training mode is activated. This allows the
448 * response to be animated when appData.animate == TRUE and
449 * appData.animateDragging == TRUE.
451 Boolean animateTraining;
457 Board boards[MAX_MOVES];
458 /* [HGM] Following 7 needed for accurate legality tests: */
459 signed char castlingRank[BOARD_FILES]; // and corresponding ranks
460 signed char initialRights[BOARD_FILES];
461 int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
462 int initialRulePlies, FENrulePlies;
463 FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
466 int mute; // mute all sounds
468 // [HGM] vari: next 12 to save and restore variations
469 #define MAX_VARIATIONS 10
470 int framePtr = MAX_MOVES-1; // points to free stack entry
472 int savedFirst[MAX_VARIATIONS];
473 int savedLast[MAX_VARIATIONS];
474 int savedFramePtr[MAX_VARIATIONS];
475 char *savedDetails[MAX_VARIATIONS];
476 ChessMove savedResult[MAX_VARIATIONS];
478 void PushTail P((int firstMove, int lastMove));
479 Boolean PopTail P((Boolean annotate));
480 void CleanupTail P((void));
482 ChessSquare FIDEArray[2][BOARD_FILES] = {
483 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
484 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
485 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
486 BlackKing, BlackBishop, BlackKnight, BlackRook }
489 ChessSquare twoKingsArray[2][BOARD_FILES] = {
490 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
491 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
492 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
493 BlackKing, BlackKing, BlackKnight, BlackRook }
496 ChessSquare KnightmateArray[2][BOARD_FILES] = {
497 { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
498 WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
499 { BlackRook, BlackMan, BlackBishop, BlackQueen,
500 BlackUnicorn, BlackBishop, BlackMan, BlackRook }
503 ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
504 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
505 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
506 { BlackLance, BlackAlfil, BlackMarshall, BlackAngel,
507 BlackKing, BlackMarshall, BlackAlfil, BlackLance }
510 ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
511 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
512 WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
513 { BlackRook, BlackKnight, BlackAlfil, BlackKing,
514 BlackFerz, BlackAlfil, BlackKnight, BlackRook }
517 ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
518 { WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
519 WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
520 { BlackRook, BlackKnight, BlackMan, BlackFerz,
521 BlackKing, BlackMan, BlackKnight, BlackRook }
525 #if (BOARD_FILES>=10)
526 ChessSquare ShogiArray[2][BOARD_FILES] = {
527 { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
528 WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
529 { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
530 BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
533 ChessSquare XiangqiArray[2][BOARD_FILES] = {
534 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
535 WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
536 { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
537 BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
540 ChessSquare CapablancaArray[2][BOARD_FILES] = {
541 { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
542 WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
543 { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
544 BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
547 ChessSquare GreatArray[2][BOARD_FILES] = {
548 { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
549 WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
550 { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
551 BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
554 ChessSquare JanusArray[2][BOARD_FILES] = {
555 { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
556 WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
557 { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
558 BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
562 ChessSquare GothicArray[2][BOARD_FILES] = {
563 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
564 WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
565 { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
566 BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
569 #define GothicArray CapablancaArray
573 ChessSquare FalconArray[2][BOARD_FILES] = {
574 { WhiteRook, WhiteKnight, WhiteBishop, WhiteLance, WhiteQueen,
575 WhiteKing, WhiteLance, WhiteBishop, WhiteKnight, WhiteRook },
576 { BlackRook, BlackKnight, BlackBishop, BlackLance, BlackQueen,
577 BlackKing, BlackLance, BlackBishop, BlackKnight, BlackRook }
580 #define FalconArray CapablancaArray
583 #else // !(BOARD_FILES>=10)
584 #define XiangqiPosition FIDEArray
585 #define CapablancaArray FIDEArray
586 #define GothicArray FIDEArray
587 #define GreatArray FIDEArray
588 #endif // !(BOARD_FILES>=10)
590 #if (BOARD_FILES>=12)
591 ChessSquare CourierArray[2][BOARD_FILES] = {
592 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
593 WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
594 { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
595 BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
597 #else // !(BOARD_FILES>=12)
598 #define CourierArray CapablancaArray
599 #endif // !(BOARD_FILES>=12)
602 Board initialPosition;
605 /* Convert str to a rating. Checks for special cases of "----",
607 "++++", etc. Also strips ()'s */
609 string_to_rating(str)
612 while(*str && !isdigit(*str)) ++str;
614 return 0; /* One of the special "no rating" cases */
622 /* Init programStats */
623 programStats.movelist[0] = 0;
624 programStats.depth = 0;
625 programStats.nr_moves = 0;
626 programStats.moves_left = 0;
627 programStats.nodes = 0;
628 programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
629 programStats.score = 0;
630 programStats.got_only_move = 0;
631 programStats.got_fail = 0;
632 programStats.line_is_book = 0;
638 int matched, min, sec;
640 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
641 startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
643 GetTimeMark(&programStartTime);
644 srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
647 programStats.ok_to_send = 1;
648 programStats.seen_stat = 0;
651 * Initialize game list
657 * Internet chess server status
659 if (appData.icsActive) {
660 appData.matchMode = FALSE;
661 appData.matchGames = 0;
663 appData.noChessProgram = !appData.zippyPlay;
665 appData.zippyPlay = FALSE;
666 appData.zippyTalk = FALSE;
667 appData.noChessProgram = TRUE;
669 if (*appData.icsHelper != NULLCHAR) {
670 appData.useTelnet = TRUE;
671 appData.telnetProgram = appData.icsHelper;
674 appData.zippyTalk = appData.zippyPlay = FALSE;
677 /* [AS] Initialize pv info list [HGM] and game state */
681 for( i=0; i<=framePtr; i++ ) {
682 pvInfoList[i].depth = -1;
683 boards[i][EP_STATUS] = EP_NONE;
684 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
689 * Parse timeControl resource
691 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
692 appData.movesPerSession)) {
694 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
695 DisplayFatalError(buf, 0, 2);
699 * Parse searchTime resource
701 if (*appData.searchTime != NULLCHAR) {
702 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
704 searchTime = min * 60;
705 } else if (matched == 2) {
706 searchTime = min * 60 + sec;
709 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
710 DisplayFatalError(buf, 0, 2);
714 /* [AS] Adjudication threshold */
715 adjudicateLossThreshold = appData.adjudicateLossThreshold;
717 first.which = "first";
718 second.which = "second";
719 first.maybeThinking = second.maybeThinking = FALSE;
720 first.pr = second.pr = NoProc;
721 first.isr = second.isr = NULL;
722 first.sendTime = second.sendTime = 2;
723 first.sendDrawOffers = 1;
724 if (appData.firstPlaysBlack) {
725 first.twoMachinesColor = "black\n";
726 second.twoMachinesColor = "white\n";
728 first.twoMachinesColor = "white\n";
729 second.twoMachinesColor = "black\n";
731 first.program = appData.firstChessProgram;
732 second.program = appData.secondChessProgram;
733 first.host = appData.firstHost;
734 second.host = appData.secondHost;
735 first.dir = appData.firstDirectory;
736 second.dir = appData.secondDirectory;
737 first.other = &second;
738 second.other = &first;
739 first.initString = appData.initString;
740 second.initString = appData.secondInitString;
741 first.computerString = appData.firstComputerString;
742 second.computerString = appData.secondComputerString;
743 first.useSigint = second.useSigint = TRUE;
744 first.useSigterm = second.useSigterm = TRUE;
745 first.reuse = appData.reuseFirst;
746 second.reuse = appData.reuseSecond;
747 first.nps = appData.firstNPS; // [HGM] nps: copy nodes per second
748 second.nps = appData.secondNPS;
749 first.useSetboard = second.useSetboard = FALSE;
750 first.useSAN = second.useSAN = FALSE;
751 first.usePing = second.usePing = FALSE;
752 first.lastPing = second.lastPing = 0;
753 first.lastPong = second.lastPong = 0;
754 first.usePlayother = second.usePlayother = FALSE;
755 first.useColors = second.useColors = TRUE;
756 first.useUsermove = second.useUsermove = FALSE;
757 first.sendICS = second.sendICS = FALSE;
758 first.sendName = second.sendName = appData.icsActive;
759 first.sdKludge = second.sdKludge = FALSE;
760 first.stKludge = second.stKludge = FALSE;
761 TidyProgramName(first.program, first.host, first.tidy);
762 TidyProgramName(second.program, second.host, second.tidy);
763 first.matchWins = second.matchWins = 0;
764 strcpy(first.variants, appData.variant);
765 strcpy(second.variants, appData.variant);
766 first.analysisSupport = second.analysisSupport = 2; /* detect */
767 first.analyzing = second.analyzing = FALSE;
768 first.initDone = second.initDone = FALSE;
770 /* New features added by Tord: */
771 first.useFEN960 = FALSE; second.useFEN960 = FALSE;
772 first.useOOCastle = TRUE; second.useOOCastle = TRUE;
773 /* End of new features added by Tord. */
774 first.fenOverride = appData.fenOverride1;
775 second.fenOverride = appData.fenOverride2;
777 /* [HGM] time odds: set factor for each machine */
778 first.timeOdds = appData.firstTimeOdds;
779 second.timeOdds = appData.secondTimeOdds;
781 if(appData.timeOddsMode) {
782 norm = first.timeOdds;
783 if(norm > second.timeOdds) norm = second.timeOdds;
785 first.timeOdds /= norm;
786 second.timeOdds /= norm;
789 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
790 first.accumulateTC = appData.firstAccumulateTC;
791 second.accumulateTC = appData.secondAccumulateTC;
792 first.maxNrOfSessions = second.maxNrOfSessions = 1;
795 first.debug = second.debug = FALSE;
796 first.supportsNPS = second.supportsNPS = UNKNOWN;
799 first.optionSettings = appData.firstOptions;
800 second.optionSettings = appData.secondOptions;
802 first.scoreIsAbsolute = appData.firstScoreIsAbsolute; /* [AS] */
803 second.scoreIsAbsolute = appData.secondScoreIsAbsolute; /* [AS] */
804 first.isUCI = appData.firstIsUCI; /* [AS] */
805 second.isUCI = appData.secondIsUCI; /* [AS] */
806 first.hasOwnBookUCI = appData.firstHasOwnBookUCI; /* [AS] */
807 second.hasOwnBookUCI = appData.secondHasOwnBookUCI; /* [AS] */
809 if (appData.firstProtocolVersion > PROTOVER ||
810 appData.firstProtocolVersion < 1) {
812 sprintf(buf, _("protocol version %d not supported"),
813 appData.firstProtocolVersion);
814 DisplayFatalError(buf, 0, 2);
816 first.protocolVersion = appData.firstProtocolVersion;
819 if (appData.secondProtocolVersion > PROTOVER ||
820 appData.secondProtocolVersion < 1) {
822 sprintf(buf, _("protocol version %d not supported"),
823 appData.secondProtocolVersion);
824 DisplayFatalError(buf, 0, 2);
826 second.protocolVersion = appData.secondProtocolVersion;
829 if (appData.icsActive) {
830 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
831 // } else if (*appData.searchTime != NULLCHAR || appData.noChessProgram) {
832 } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
833 appData.clockMode = FALSE;
834 first.sendTime = second.sendTime = 0;
838 /* Override some settings from environment variables, for backward
839 compatibility. Unfortunately it's not feasible to have the env
840 vars just set defaults, at least in xboard. Ugh.
842 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
847 if (appData.noChessProgram) {
848 programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
849 sprintf(programVersion, "%s", PACKAGE_STRING);
851 /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
852 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
853 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
856 if (!appData.icsActive) {
858 /* Check for variants that are supported only in ICS mode,
859 or not at all. Some that are accepted here nevertheless
860 have bugs; see comments below.
862 VariantClass variant = StringToVariant(appData.variant);
864 case VariantBughouse: /* need four players and two boards */
865 case VariantKriegspiel: /* need to hide pieces and move details */
866 /* case VariantFischeRandom: (Fabien: moved below) */
867 sprintf(buf, _("Variant %s supported only in ICS mode"), appData.variant);
868 DisplayFatalError(buf, 0, 2);
872 case VariantLoadable:
882 sprintf(buf, _("Unknown variant name %s"), appData.variant);
883 DisplayFatalError(buf, 0, 2);
886 case VariantXiangqi: /* [HGM] repetition rules not implemented */
887 case VariantFairy: /* [HGM] TestLegality definitely off! */
888 case VariantGothic: /* [HGM] should work */
889 case VariantCapablanca: /* [HGM] should work */
890 case VariantCourier: /* [HGM] initial forced moves not implemented */
891 case VariantShogi: /* [HGM] drops not tested for legality */
892 case VariantKnightmate: /* [HGM] should work */
893 case VariantCylinder: /* [HGM] untested */
894 case VariantFalcon: /* [HGM] untested */
895 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
896 offboard interposition not understood */
897 case VariantNormal: /* definitely works! */
898 case VariantWildCastle: /* pieces not automatically shuffled */
899 case VariantNoCastle: /* pieces not automatically shuffled */
900 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
901 case VariantLosers: /* should work except for win condition,
902 and doesn't know captures are mandatory */
903 case VariantSuicide: /* should work except for win condition,
904 and doesn't know captures are mandatory */
905 case VariantGiveaway: /* should work except for win condition,
906 and doesn't know captures are mandatory */
907 case VariantTwoKings: /* should work */
908 case VariantAtomic: /* should work except for win condition */
909 case Variant3Check: /* should work except for win condition */
910 case VariantShatranj: /* should work except for all win conditions */
911 case VariantMakruk: /* should work except for daw countdown */
912 case VariantBerolina: /* might work if TestLegality is off */
913 case VariantCapaRandom: /* should work */
914 case VariantJanus: /* should work */
915 case VariantSuper: /* experimental */
916 case VariantGreat: /* experimental, requires legality testing to be off */
921 InitEngineUCI( installDir, &first ); // [HGM] moved here from winboard.c, to make available in xboard
922 InitEngineUCI( installDir, &second );
925 int NextIntegerFromString( char ** str, long * value )
930 while( *s == ' ' || *s == '\t' ) {
936 if( *s >= '0' && *s <= '9' ) {
937 while( *s >= '0' && *s <= '9' ) {
938 *value = *value * 10 + (*s - '0');
950 int NextTimeControlFromString( char ** str, long * value )
953 int result = NextIntegerFromString( str, &temp );
956 *value = temp * 60; /* Minutes */
959 result = NextIntegerFromString( str, &temp );
960 *value += temp; /* Seconds */
967 int NextSessionFromString( char ** str, int *moves, long * tc, long *inc)
968 { /* [HGM] routine added to read '+moves/time' for secondary time control */
969 int result = -1; long temp, temp2;
971 if(**str != '+') return -1; // old params remain in force!
973 if( NextTimeControlFromString( str, &temp ) ) return -1;
976 /* time only: incremental or sudden-death time control */
977 if(**str == '+') { /* increment follows; read it */
979 if(result = NextIntegerFromString( str, &temp2)) return -1;
982 *moves = 0; *tc = temp * 1000;
984 } else if(temp % 60 != 0) return -1; /* moves was given as min:sec */
986 (*str)++; /* classical time control */
987 result = NextTimeControlFromString( str, &temp2);
996 int GetTimeQuota(int movenr)
997 { /* [HGM] get time to add from the multi-session time-control string */
998 int moves=1; /* kludge to force reading of first session */
999 long time, increment;
1000 char *s = fullTimeControlString;
1002 if(appData.debugMode) fprintf(debugFP, "TC string = '%s'\n", fullTimeControlString);
1004 if(moves) NextSessionFromString(&s, &moves, &time, &increment);
1005 if(appData.debugMode) fprintf(debugFP, "mps=%d tc=%d inc=%d\n", moves, (int) time, (int) increment);
1006 if(movenr == -1) return time; /* last move before new session */
1007 if(!moves) return increment; /* current session is incremental */
1008 if(movenr >= 0) movenr -= moves; /* we already finished this session */
1009 } while(movenr >= -1); /* try again for next session */
1011 return 0; // no new time quota on this move
1015 ParseTimeControl(tc, ti, mps)
1024 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1027 sprintf(buf, "+%d/%s+%d", mps, tc, ti);
1028 else sprintf(buf, "+%s+%d", tc, ti);
1031 sprintf(buf, "+%d/%s", mps, tc);
1032 else sprintf(buf, "+%s", tc);
1034 fullTimeControlString = StrSave(buf);
1036 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1041 /* Parse second time control */
1044 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1052 timeControl_2 = tc2 * 1000;
1062 timeControl = tc1 * 1000;
1065 timeIncrement = ti * 1000; /* convert to ms */
1066 movesPerSession = 0;
1069 movesPerSession = mps;
1077 if (appData.debugMode) {
1078 fprintf(debugFP, "%s\n", programVersion);
1081 set_cont_sequence(appData.wrapContSeq);
1082 if (appData.matchGames > 0) {
1083 appData.matchMode = TRUE;
1084 } else if (appData.matchMode) {
1085 appData.matchGames = 1;
1087 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1088 appData.matchGames = appData.sameColorGames;
1089 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1090 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1091 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1094 if (appData.noChessProgram || first.protocolVersion == 1) {
1097 /* kludge: allow timeout for initial "feature" commands */
1099 DisplayMessage("", _("Starting chess program"));
1100 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1105 InitBackEnd3 P((void))
1107 GameMode initialMode;
1111 InitChessProgram(&first, startedFromSetupPosition);
1113 if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
1114 free(programVersion);
1115 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1116 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1119 if (appData.icsActive) {
1121 /* [DM] Make a console window if needed [HGM] merged ifs */
1126 if (*appData.icsCommPort != NULLCHAR) {
1127 sprintf(buf, _("Could not open comm port %s"),
1128 appData.icsCommPort);
1130 snprintf(buf, sizeof(buf), _("Could not connect to host %s, port %s"),
1131 appData.icsHost, appData.icsPort);
1133 DisplayFatalError(buf, err, 1);
1138 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1140 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1141 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1142 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1143 } else if (appData.noChessProgram) {
1149 if (*appData.cmailGameName != NULLCHAR) {
1151 OpenLoopback(&cmailPR);
1153 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1157 DisplayMessage("", "");
1158 if (StrCaseCmp(appData.initialMode, "") == 0) {
1159 initialMode = BeginningOfGame;
1160 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1161 initialMode = TwoMachinesPlay;
1162 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1163 initialMode = AnalyzeFile;
1164 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1165 initialMode = AnalyzeMode;
1166 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1167 initialMode = MachinePlaysWhite;
1168 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1169 initialMode = MachinePlaysBlack;
1170 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1171 initialMode = EditGame;
1172 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1173 initialMode = EditPosition;
1174 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1175 initialMode = Training;
1177 sprintf(buf, _("Unknown initialMode %s"), appData.initialMode);
1178 DisplayFatalError(buf, 0, 2);
1182 if (appData.matchMode) {
1183 /* Set up machine vs. machine match */
1184 if (appData.noChessProgram) {
1185 DisplayFatalError(_("Can't have a match with no chess programs"),
1191 if (*appData.loadGameFile != NULLCHAR) {
1192 int index = appData.loadGameIndex; // [HGM] autoinc
1193 if(index<0) lastIndex = index = 1;
1194 if (!LoadGameFromFile(appData.loadGameFile,
1196 appData.loadGameFile, FALSE)) {
1197 DisplayFatalError(_("Bad game file"), 0, 1);
1200 } else if (*appData.loadPositionFile != NULLCHAR) {
1201 int index = appData.loadPositionIndex; // [HGM] autoinc
1202 if(index<0) lastIndex = index = 1;
1203 if (!LoadPositionFromFile(appData.loadPositionFile,
1205 appData.loadPositionFile)) {
1206 DisplayFatalError(_("Bad position file"), 0, 1);
1211 } else if (*appData.cmailGameName != NULLCHAR) {
1212 /* Set up cmail mode */
1213 ReloadCmailMsgEvent(TRUE);
1215 /* Set up other modes */
1216 if (initialMode == AnalyzeFile) {
1217 if (*appData.loadGameFile == NULLCHAR) {
1218 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1222 if (*appData.loadGameFile != NULLCHAR) {
1223 (void) LoadGameFromFile(appData.loadGameFile,
1224 appData.loadGameIndex,
1225 appData.loadGameFile, TRUE);
1226 } else if (*appData.loadPositionFile != NULLCHAR) {
1227 (void) LoadPositionFromFile(appData.loadPositionFile,
1228 appData.loadPositionIndex,
1229 appData.loadPositionFile);
1230 /* [HGM] try to make self-starting even after FEN load */
1231 /* to allow automatic setup of fairy variants with wtm */
1232 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1233 gameMode = BeginningOfGame;
1234 setboardSpoiledMachineBlack = 1;
1236 /* [HGM] loadPos: make that every new game uses the setup */
1237 /* from file as long as we do not switch variant */
1238 if(!blackPlaysFirst) {
1239 startedFromPositionFile = TRUE;
1240 CopyBoard(filePosition, boards[0]);
1243 if (initialMode == AnalyzeMode) {
1244 if (appData.noChessProgram) {
1245 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1248 if (appData.icsActive) {
1249 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1253 } else if (initialMode == AnalyzeFile) {
1254 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1255 ShowThinkingEvent();
1257 AnalysisPeriodicEvent(1);
1258 } else if (initialMode == MachinePlaysWhite) {
1259 if (appData.noChessProgram) {
1260 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1264 if (appData.icsActive) {
1265 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1269 MachineWhiteEvent();
1270 } else if (initialMode == MachinePlaysBlack) {
1271 if (appData.noChessProgram) {
1272 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1276 if (appData.icsActive) {
1277 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1281 MachineBlackEvent();
1282 } else if (initialMode == TwoMachinesPlay) {
1283 if (appData.noChessProgram) {
1284 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1288 if (appData.icsActive) {
1289 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1294 } else if (initialMode == EditGame) {
1296 } else if (initialMode == EditPosition) {
1297 EditPositionEvent();
1298 } else if (initialMode == Training) {
1299 if (*appData.loadGameFile == NULLCHAR) {
1300 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1309 * Establish will establish a contact to a remote host.port.
1310 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1311 * used to talk to the host.
1312 * Returns 0 if okay, error code if not.
1319 if (*appData.icsCommPort != NULLCHAR) {
1320 /* Talk to the host through a serial comm port */
1321 return OpenCommPort(appData.icsCommPort, &icsPR);
1323 } else if (*appData.gateway != NULLCHAR) {
1324 if (*appData.remoteShell == NULLCHAR) {
1325 /* Use the rcmd protocol to run telnet program on a gateway host */
1326 snprintf(buf, sizeof(buf), "%s %s %s",
1327 appData.telnetProgram, appData.icsHost, appData.icsPort);
1328 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1331 /* Use the rsh program to run telnet program on a gateway host */
1332 if (*appData.remoteUser == NULLCHAR) {
1333 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1334 appData.gateway, appData.telnetProgram,
1335 appData.icsHost, appData.icsPort);
1337 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1338 appData.remoteShell, appData.gateway,
1339 appData.remoteUser, appData.telnetProgram,
1340 appData.icsHost, appData.icsPort);
1342 return StartChildProcess(buf, "", &icsPR);
1345 } else if (appData.useTelnet) {
1346 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1349 /* TCP socket interface differs somewhat between
1350 Unix and NT; handle details in the front end.
1352 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1356 void EscapeExpand(char *p, char *q)
1357 { // [HGM] initstring: routine to shape up string arguments
1358 while(*p++ = *q++) if(p[-1] == '\\')
1360 case 'n': p[-1] = '\n'; break;
1361 case 'r': p[-1] = '\r'; break;
1362 case 't': p[-1] = '\t'; break;
1363 case '\\': p[-1] = '\\'; break;
1364 case 0: *p = 0; return;
1365 default: p[-1] = q[-1]; break;
1370 show_bytes(fp, buf, count)
1376 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1377 fprintf(fp, "\\%03o", *buf & 0xff);
1386 /* Returns an errno value */
1388 OutputMaybeTelnet(pr, message, count, outError)
1394 char buf[8192], *p, *q, *buflim;
1395 int left, newcount, outcount;
1397 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1398 *appData.gateway != NULLCHAR) {
1399 if (appData.debugMode) {
1400 fprintf(debugFP, ">ICS: ");
1401 show_bytes(debugFP, message, count);
1402 fprintf(debugFP, "\n");
1404 return OutputToProcess(pr, message, count, outError);
1407 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1414 if (appData.debugMode) {
1415 fprintf(debugFP, ">ICS: ");
1416 show_bytes(debugFP, buf, newcount);
1417 fprintf(debugFP, "\n");
1419 outcount = OutputToProcess(pr, buf, newcount, outError);
1420 if (outcount < newcount) return -1; /* to be sure */
1427 } else if (((unsigned char) *p) == TN_IAC) {
1428 *q++ = (char) TN_IAC;
1435 if (appData.debugMode) {
1436 fprintf(debugFP, ">ICS: ");
1437 show_bytes(debugFP, buf, newcount);
1438 fprintf(debugFP, "\n");
1440 outcount = OutputToProcess(pr, buf, newcount, outError);
1441 if (outcount < newcount) return -1; /* to be sure */
1446 read_from_player(isr, closure, message, count, error)
1453 int outError, outCount;
1454 static int gotEof = 0;
1456 /* Pass data read from player on to ICS */
1459 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1460 if (outCount < count) {
1461 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1463 } else if (count < 0) {
1464 RemoveInputSource(isr);
1465 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1466 } else if (gotEof++ > 0) {
1467 RemoveInputSource(isr);
1468 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1474 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1475 if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
1476 connectionAlive = FALSE; // only sticks if no response to 'date' command.
1477 SendToICS("date\n");
1478 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1481 /* added routine for printf style output to ics */
1482 void ics_printf(char *format, ...)
1484 char buffer[MSG_SIZ];
1487 va_start(args, format);
1488 vsnprintf(buffer, sizeof(buffer), format, args);
1489 buffer[sizeof(buffer)-1] = '\0';
1498 int count, outCount, outError;
1500 if (icsPR == NULL) return;
1503 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1504 if (outCount < count) {
1505 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1509 /* This is used for sending logon scripts to the ICS. Sending
1510 without a delay causes problems when using timestamp on ICC
1511 (at least on my machine). */
1513 SendToICSDelayed(s,msdelay)
1517 int count, outCount, outError;
1519 if (icsPR == NULL) return;
1522 if (appData.debugMode) {
1523 fprintf(debugFP, ">ICS: ");
1524 show_bytes(debugFP, s, count);
1525 fprintf(debugFP, "\n");
1527 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1529 if (outCount < count) {
1530 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1535 /* Remove all highlighting escape sequences in s
1536 Also deletes any suffix starting with '('
1539 StripHighlightAndTitle(s)
1542 static char retbuf[MSG_SIZ];
1545 while (*s != NULLCHAR) {
1546 while (*s == '\033') {
1547 while (*s != NULLCHAR && !isalpha(*s)) s++;
1548 if (*s != NULLCHAR) s++;
1550 while (*s != NULLCHAR && *s != '\033') {
1551 if (*s == '(' || *s == '[') {
1562 /* Remove all highlighting escape sequences in s */
1567 static char retbuf[MSG_SIZ];
1570 while (*s != NULLCHAR) {
1571 while (*s == '\033') {
1572 while (*s != NULLCHAR && !isalpha(*s)) s++;
1573 if (*s != NULLCHAR) s++;
1575 while (*s != NULLCHAR && *s != '\033') {
1583 char *variantNames[] = VARIANT_NAMES;
1588 return variantNames[v];
1592 /* Identify a variant from the strings the chess servers use or the
1593 PGN Variant tag names we use. */
1600 VariantClass v = VariantNormal;
1601 int i, found = FALSE;
1606 /* [HGM] skip over optional board-size prefixes */
1607 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
1608 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
1609 while( *e++ != '_');
1612 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
1616 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1617 if (StrCaseStr(e, variantNames[i])) {
1618 v = (VariantClass) i;
1625 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
1626 || StrCaseStr(e, "wild/fr")
1627 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
1628 v = VariantFischeRandom;
1629 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
1630 (i = 1, p = StrCaseStr(e, "w"))) {
1632 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
1639 case 0: /* FICS only, actually */
1641 /* Castling legal even if K starts on d-file */
1642 v = VariantWildCastle;
1647 /* Castling illegal even if K & R happen to start in
1648 normal positions. */
1649 v = VariantNoCastle;
1662 /* Castling legal iff K & R start in normal positions */
1668 /* Special wilds for position setup; unclear what to do here */
1669 v = VariantLoadable;
1672 /* Bizarre ICC game */
1673 v = VariantTwoKings;
1676 v = VariantKriegspiel;
1682 v = VariantFischeRandom;
1685 v = VariantCrazyhouse;
1688 v = VariantBughouse;
1694 /* Not quite the same as FICS suicide! */
1695 v = VariantGiveaway;
1701 v = VariantShatranj;
1704 /* Temporary names for future ICC types. The name *will* change in
1705 the next xboard/WinBoard release after ICC defines it. */
1743 v = VariantCapablanca;
1746 v = VariantKnightmate;
1752 v = VariantCylinder;
1758 v = VariantCapaRandom;
1761 v = VariantBerolina;
1773 /* Found "wild" or "w" in the string but no number;
1774 must assume it's normal chess. */
1778 sprintf(buf, _("Unknown wild type %d"), wnum);
1779 DisplayError(buf, 0);
1785 if (appData.debugMode) {
1786 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
1787 e, wnum, VariantName(v));
1792 static int leftover_start = 0, leftover_len = 0;
1793 char star_match[STAR_MATCH_N][MSG_SIZ];
1795 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
1796 advance *index beyond it, and set leftover_start to the new value of
1797 *index; else return FALSE. If pattern contains the character '*', it
1798 matches any sequence of characters not containing '\r', '\n', or the
1799 character following the '*' (if any), and the matched sequence(s) are
1800 copied into star_match.
1803 looking_at(buf, index, pattern)
1808 char *bufp = &buf[*index], *patternp = pattern;
1810 char *matchp = star_match[0];
1813 if (*patternp == NULLCHAR) {
1814 *index = leftover_start = bufp - buf;
1818 if (*bufp == NULLCHAR) return FALSE;
1819 if (*patternp == '*') {
1820 if (*bufp == *(patternp + 1)) {
1822 matchp = star_match[++star_count];
1826 } else if (*bufp == '\n' || *bufp == '\r') {
1828 if (*patternp == NULLCHAR)
1833 *matchp++ = *bufp++;
1837 if (*patternp != *bufp) return FALSE;
1844 SendToPlayer(data, length)
1848 int error, outCount;
1849 outCount = OutputToProcess(NoProc, data, length, &error);
1850 if (outCount < length) {
1851 DisplayFatalError(_("Error writing to display"), error, 1);
1856 PackHolding(packed, holding)
1868 switch (runlength) {
1879 sprintf(q, "%d", runlength);
1891 /* Telnet protocol requests from the front end */
1893 TelnetRequest(ddww, option)
1894 unsigned char ddww, option;
1896 unsigned char msg[3];
1897 int outCount, outError;
1899 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
1901 if (appData.debugMode) {
1902 char buf1[8], buf2[8], *ddwwStr, *optionStr;
1918 sprintf(buf1, "%d", ddww);
1927 sprintf(buf2, "%d", option);
1930 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
1935 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
1937 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1944 if (!appData.icsActive) return;
1945 TelnetRequest(TN_DO, TN_ECHO);
1951 if (!appData.icsActive) return;
1952 TelnetRequest(TN_DONT, TN_ECHO);
1956 CopyHoldings(Board board, char *holdings, ChessSquare lowestPiece)
1958 /* put the holdings sent to us by the server on the board holdings area */
1959 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
1963 if(gameInfo.holdingsWidth < 2) return;
1964 if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
1965 return; // prevent overwriting by pre-board holdings
1967 if( (int)lowestPiece >= BlackPawn ) {
1970 holdingsStartRow = BOARD_HEIGHT-1;
1973 holdingsColumn = BOARD_WIDTH-1;
1974 countsColumn = BOARD_WIDTH-2;
1975 holdingsStartRow = 0;
1979 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
1980 board[i][holdingsColumn] = EmptySquare;
1981 board[i][countsColumn] = (ChessSquare) 0;
1983 while( (p=*holdings++) != NULLCHAR ) {
1984 piece = CharToPiece( ToUpper(p) );
1985 if(piece == EmptySquare) continue;
1986 /*j = (int) piece - (int) WhitePawn;*/
1987 j = PieceToNumber(piece);
1988 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
1989 if(j < 0) continue; /* should not happen */
1990 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
1991 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
1992 board[holdingsStartRow+j*direction][countsColumn]++;
1998 VariantSwitch(Board board, VariantClass newVariant)
2000 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2001 static Board oldBoard;
2003 startedFromPositionFile = FALSE;
2004 if(gameInfo.variant == newVariant) return;
2006 /* [HGM] This routine is called each time an assignment is made to
2007 * gameInfo.variant during a game, to make sure the board sizes
2008 * are set to match the new variant. If that means adding or deleting
2009 * holdings, we shift the playing board accordingly
2010 * This kludge is needed because in ICS observe mode, we get boards
2011 * of an ongoing game without knowing the variant, and learn about the
2012 * latter only later. This can be because of the move list we requested,
2013 * in which case the game history is refilled from the beginning anyway,
2014 * but also when receiving holdings of a crazyhouse game. In the latter
2015 * case we want to add those holdings to the already received position.
2019 if (appData.debugMode) {
2020 fprintf(debugFP, "Switch board from %s to %s\n",
2021 VariantName(gameInfo.variant), VariantName(newVariant));
2022 setbuf(debugFP, NULL);
2024 shuffleOpenings = 0; /* [HGM] shuffle */
2025 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2029 newWidth = 9; newHeight = 9;
2030 gameInfo.holdingsSize = 7;
2031 case VariantBughouse:
2032 case VariantCrazyhouse:
2033 newHoldingsWidth = 2; break;
2037 newHoldingsWidth = 2;
2038 gameInfo.holdingsSize = 8;
2041 case VariantCapablanca:
2042 case VariantCapaRandom:
2045 newHoldingsWidth = gameInfo.holdingsSize = 0;
2048 if(newWidth != gameInfo.boardWidth ||
2049 newHeight != gameInfo.boardHeight ||
2050 newHoldingsWidth != gameInfo.holdingsWidth ) {
2052 /* shift position to new playing area, if needed */
2053 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2054 for(i=0; i<BOARD_HEIGHT; i++)
2055 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2056 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2058 for(i=0; i<newHeight; i++) {
2059 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2060 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2062 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2063 for(i=0; i<BOARD_HEIGHT; i++)
2064 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2065 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2068 gameInfo.boardWidth = newWidth;
2069 gameInfo.boardHeight = newHeight;
2070 gameInfo.holdingsWidth = newHoldingsWidth;
2071 gameInfo.variant = newVariant;
2072 InitDrawingSizes(-2, 0);
2073 } else gameInfo.variant = newVariant;
2074 CopyBoard(oldBoard, board); // remember correctly formatted board
2075 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2076 DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2079 static int loggedOn = FALSE;
2081 /*-- Game start info cache: --*/
2083 char gs_kind[MSG_SIZ];
2084 static char player1Name[128] = "";
2085 static char player2Name[128] = "";
2086 static char cont_seq[] = "\n\\ ";
2087 static int player1Rating = -1;
2088 static int player2Rating = -1;
2089 /*----------------------------*/
2091 ColorClass curColor = ColorNormal;
2092 int suppressKibitz = 0;
2095 Boolean soughtPending = FALSE;
2096 Boolean seekGraphUp;
2097 #define MAX_SEEK_ADS 200
2099 char *seekAdList[MAX_SEEK_ADS];
2100 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2101 float tcList[MAX_SEEK_ADS];
2102 char colorList[MAX_SEEK_ADS];
2103 int nrOfSeekAds = 0;
2104 int minRating = 1010, maxRating = 2800;
2105 int hMargin = 10, vMargin = 20, h, w;
2106 extern int squareSize, lineGap;
2111 int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2112 xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2113 if(r < minRating+100 && r >=0 ) r = minRating+100;
2114 if(r > maxRating) r = maxRating;
2115 if(tc < 1.) tc = 1.;
2116 if(tc > 95.) tc = 95.;
2117 x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2118 y = ((double)r - minRating)/(maxRating - minRating)
2119 * (h-vMargin-squareSize/8-1) + vMargin;
2120 if(ratingList[i] < 0) y = vMargin + squareSize/4;
2121 if(strstr(seekAdList[i], " u ")) color = 1;
2122 if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2123 !strstr(seekAdList[i], "bullet") &&
2124 !strstr(seekAdList[i], "blitz") &&
2125 !strstr(seekAdList[i], "standard") ) color = 2;
2126 if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2127 DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2131 AddAd(char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
2133 char buf[MSG_SIZ], *ext = "";
2134 VariantClass v = StringToVariant(type);
2135 if(strstr(type, "wild")) {
2136 ext = type + 4; // append wild number
2137 if(v == VariantFischeRandom) type = "chess960"; else
2138 if(v == VariantLoadable) type = "setup"; else
2139 type = VariantName(v);
2141 sprintf(buf, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2142 if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2143 if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2144 ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2145 sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2146 tcList[nrOfSeekAds] = base + (2./3.)*inc;
2147 seekNrList[nrOfSeekAds] = nr;
2148 zList[nrOfSeekAds] = 0;
2149 seekAdList[nrOfSeekAds++] = StrSave(buf);
2150 if(plot) PlotSeekAd(nrOfSeekAds-1);
2157 int x = xList[i], y = yList[i], d=squareSize/4, k;
2158 DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2159 if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2160 // now replot every dot that overlapped
2161 for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2162 int xx = xList[k], yy = yList[k];
2163 if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2164 DrawSeekDot(xx, yy, colorList[k]);
2169 RemoveSeekAd(int nr)
2172 for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2174 if(seekAdList[i]) free(seekAdList[i]);
2175 seekAdList[i] = seekAdList[--nrOfSeekAds];
2176 seekNrList[i] = seekNrList[nrOfSeekAds];
2177 ratingList[i] = ratingList[nrOfSeekAds];
2178 colorList[i] = colorList[nrOfSeekAds];
2179 tcList[i] = tcList[nrOfSeekAds];
2180 xList[i] = xList[nrOfSeekAds];
2181 yList[i] = yList[nrOfSeekAds];
2182 zList[i] = zList[nrOfSeekAds];
2183 seekAdList[nrOfSeekAds] = NULL;
2189 MatchSoughtLine(char *line)
2191 char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2192 int nr, base, inc, u=0; char dummy;
2194 if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2195 sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2197 (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2198 sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
2199 // match: compact and save the line
2200 AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2210 if(!seekGraphUp) return FALSE;
2211 h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap;
2212 w = BOARD_WIDTH * (squareSize + lineGap) + lineGap;
2214 DrawSeekBackground(0, 0, w, h);
2215 DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2216 DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2217 for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2218 int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2220 DrawSeekAxis(hMargin+5*(i%500==0), yy, hMargin-5, yy); // rating ticks
2223 sprintf(buf, "%d", i);
2224 DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2227 DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2228 for(i=1; i<100; i+=(i<10?1:5)) {
2229 int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2230 DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2231 if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2233 sprintf(buf, "%d", i);
2234 DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2237 for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2241 int SeekGraphClick(ClickType click, int x, int y, int moving)
2243 static int lastDown = 0, displayed = 0, lastSecond;
2244 if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2245 if(click == Release || moving) return FALSE;
2247 soughtPending = TRUE;
2248 SendToICS(ics_prefix);
2249 SendToICS("sought\n"); // should this be "sought all"?
2250 } else { // issue challenge based on clicked ad
2251 int dist = 10000; int i, closest = 0, second = 0;
2252 for(i=0; i<nrOfSeekAds; i++) {
2253 int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
2254 if(d < dist) { dist = d; closest = i; }
2255 second += (d - zList[i] < 120); // count in-range ads
2256 if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2260 second = (second > 1);
2261 if(displayed != closest || second != lastSecond) {
2262 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2263 lastSecond = second; displayed = closest;
2265 if(click == Press) {
2266 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2269 } // on press 'hit', only show info
2270 if(moving == 2) return TRUE; // ignore right up-clicks on dot
2271 sprintf(buf, "play %d\n", seekNrList[closest]);
2272 SendToICS(ics_prefix);
2274 return TRUE; // let incoming board of started game pop down the graph
2275 } else if(click == Release) { // release 'miss' is ignored
2276 zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2277 if(moving == 2) { // right up-click
2278 nrOfSeekAds = 0; // refresh graph
2279 soughtPending = TRUE;
2280 SendToICS(ics_prefix);
2281 SendToICS("sought\n"); // should this be "sought all"?
2284 } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2285 // press miss or release hit 'pop down' seek graph
2286 seekGraphUp = FALSE;
2287 DrawPosition(TRUE, NULL);
2293 read_from_ics(isr, closure, data, count, error)
2300 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2301 #define STARTED_NONE 0
2302 #define STARTED_MOVES 1
2303 #define STARTED_BOARD 2
2304 #define STARTED_OBSERVE 3
2305 #define STARTED_HOLDINGS 4
2306 #define STARTED_CHATTER 5
2307 #define STARTED_COMMENT 6
2308 #define STARTED_MOVES_NOHIDE 7
2310 static int started = STARTED_NONE;
2311 static char parse[20000];
2312 static int parse_pos = 0;
2313 static char buf[BUF_SIZE + 1];
2314 static int firstTime = TRUE, intfSet = FALSE;
2315 static ColorClass prevColor = ColorNormal;
2316 static int savingComment = FALSE;
2317 static int cmatch = 0; // continuation sequence match
2324 int backup; /* [DM] For zippy color lines */
2326 char talker[MSG_SIZ]; // [HGM] chat
2329 connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2331 if (appData.debugMode) {
2333 fprintf(debugFP, "<ICS: ");
2334 show_bytes(debugFP, data, count);
2335 fprintf(debugFP, "\n");
2339 if (appData.debugMode) { int f = forwardMostMove;
2340 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2341 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2342 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2345 /* If last read ended with a partial line that we couldn't parse,
2346 prepend it to the new read and try again. */
2347 if (leftover_len > 0) {
2348 for (i=0; i<leftover_len; i++)
2349 buf[i] = buf[leftover_start + i];
2352 /* copy new characters into the buffer */
2353 bp = buf + leftover_len;
2354 buf_len=leftover_len;
2355 for (i=0; i<count; i++)
2358 if (data[i] == '\r')
2361 // join lines split by ICS?
2362 if (!appData.noJoin)
2365 Joining just consists of finding matches against the
2366 continuation sequence, and discarding that sequence
2367 if found instead of copying it. So, until a match
2368 fails, there's nothing to do since it might be the
2369 complete sequence, and thus, something we don't want
2372 if (data[i] == cont_seq[cmatch])
2375 if (cmatch == strlen(cont_seq))
2377 cmatch = 0; // complete match. just reset the counter
2380 it's possible for the ICS to not include the space
2381 at the end of the last word, making our [correct]
2382 join operation fuse two separate words. the server
2383 does this when the space occurs at the width setting.
2385 if (!buf_len || buf[buf_len-1] != ' ')
2396 match failed, so we have to copy what matched before
2397 falling through and copying this character. In reality,
2398 this will only ever be just the newline character, but
2399 it doesn't hurt to be precise.
2401 strncpy(bp, cont_seq, cmatch);
2413 buf[buf_len] = NULLCHAR;
2414 // next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2419 while (i < buf_len) {
2420 /* Deal with part of the TELNET option negotiation
2421 protocol. We refuse to do anything beyond the
2422 defaults, except that we allow the WILL ECHO option,
2423 which ICS uses to turn off password echoing when we are
2424 directly connected to it. We reject this option
2425 if localLineEditing mode is on (always on in xboard)
2426 and we are talking to port 23, which might be a real
2427 telnet server that will try to keep WILL ECHO on permanently.
2429 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2430 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2431 unsigned char option;
2433 switch ((unsigned char) buf[++i]) {
2435 if (appData.debugMode)
2436 fprintf(debugFP, "\n<WILL ");
2437 switch (option = (unsigned char) buf[++i]) {
2439 if (appData.debugMode)
2440 fprintf(debugFP, "ECHO ");
2441 /* Reply only if this is a change, according
2442 to the protocol rules. */
2443 if (remoteEchoOption) break;
2444 if (appData.localLineEditing &&
2445 atoi(appData.icsPort) == TN_PORT) {
2446 TelnetRequest(TN_DONT, TN_ECHO);
2449 TelnetRequest(TN_DO, TN_ECHO);
2450 remoteEchoOption = TRUE;
2454 if (appData.debugMode)
2455 fprintf(debugFP, "%d ", option);
2456 /* Whatever this is, we don't want it. */
2457 TelnetRequest(TN_DONT, option);
2462 if (appData.debugMode)
2463 fprintf(debugFP, "\n<WONT ");
2464 switch (option = (unsigned char) buf[++i]) {
2466 if (appData.debugMode)
2467 fprintf(debugFP, "ECHO ");
2468 /* Reply only if this is a change, according
2469 to the protocol rules. */
2470 if (!remoteEchoOption) break;
2472 TelnetRequest(TN_DONT, TN_ECHO);
2473 remoteEchoOption = FALSE;
2476 if (appData.debugMode)
2477 fprintf(debugFP, "%d ", (unsigned char) option);
2478 /* Whatever this is, it must already be turned
2479 off, because we never agree to turn on
2480 anything non-default, so according to the
2481 protocol rules, we don't reply. */
2486 if (appData.debugMode)
2487 fprintf(debugFP, "\n<DO ");
2488 switch (option = (unsigned char) buf[++i]) {
2490 /* Whatever this is, we refuse to do it. */
2491 if (appData.debugMode)
2492 fprintf(debugFP, "%d ", option);
2493 TelnetRequest(TN_WONT, option);
2498 if (appData.debugMode)
2499 fprintf(debugFP, "\n<DONT ");
2500 switch (option = (unsigned char) buf[++i]) {
2502 if (appData.debugMode)
2503 fprintf(debugFP, "%d ", option);
2504 /* Whatever this is, we are already not doing
2505 it, because we never agree to do anything
2506 non-default, so according to the protocol
2507 rules, we don't reply. */
2512 if (appData.debugMode)
2513 fprintf(debugFP, "\n<IAC ");
2514 /* Doubled IAC; pass it through */
2518 if (appData.debugMode)
2519 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2520 /* Drop all other telnet commands on the floor */
2523 if (oldi > next_out)
2524 SendToPlayer(&buf[next_out], oldi - next_out);
2530 /* OK, this at least will *usually* work */
2531 if (!loggedOn && looking_at(buf, &i, "ics%")) {
2535 if (loggedOn && !intfSet) {
2536 if (ics_type == ICS_ICC) {
2538 "/set-quietly interface %s\n/set-quietly style 12\n",
2540 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2541 strcat(str, "/set-2 51 1\n/set seek 1\n");
2542 } else if (ics_type == ICS_CHESSNET) {
2543 sprintf(str, "/style 12\n");
2545 strcpy(str, "alias $ @\n$set interface ");
2546 strcat(str, programVersion);
2547 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2548 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2549 strcat(str, "$iset seekremove 1\n$set seek 1\n");
2551 strcat(str, "$iset nohighlight 1\n");
2553 strcat(str, "$iset lock 1\n$style 12\n");
2556 NotifyFrontendLogin();
2560 if (started == STARTED_COMMENT) {
2561 /* Accumulate characters in comment */
2562 parse[parse_pos++] = buf[i];
2563 if (buf[i] == '\n') {
2564 parse[parse_pos] = NULLCHAR;
2565 if(chattingPartner>=0) {
2567 sprintf(mess, "%s%s", talker, parse);
2568 OutputChatMessage(chattingPartner, mess);
2569 chattingPartner = -1;
2570 next_out = i+1; // [HGM] suppress printing in ICS window
2572 if(!suppressKibitz) // [HGM] kibitz
2573 AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
2574 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2575 int nrDigit = 0, nrAlph = 0, j;
2576 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2577 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2578 parse[parse_pos] = NULLCHAR;
2579 // try to be smart: if it does not look like search info, it should go to
2580 // ICS interaction window after all, not to engine-output window.
2581 for(j=0; j<parse_pos; j++) { // count letters and digits
2582 nrDigit += (parse[j] >= '0' && parse[j] <= '9');
2583 nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
2584 nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
2586 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
2587 int depth=0; float score;
2588 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
2589 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
2590 pvInfoList[forwardMostMove-1].depth = depth;
2591 pvInfoList[forwardMostMove-1].score = 100*score;
2593 OutputKibitz(suppressKibitz, parse);
2596 sprintf(tmp, _("your opponent kibitzes: %s"), parse);
2597 SendToPlayer(tmp, strlen(tmp));
2599 next_out = i+1; // [HGM] suppress printing in ICS window
2601 started = STARTED_NONE;
2603 /* Don't match patterns against characters in comment */
2608 if (started == STARTED_CHATTER) {
2609 if (buf[i] != '\n') {
2610 /* Don't match patterns against characters in chatter */
2614 started = STARTED_NONE;
2615 if(suppressKibitz) next_out = i+1;
2618 /* Kludge to deal with rcmd protocol */
2619 if (firstTime && looking_at(buf, &i, "\001*")) {
2620 DisplayFatalError(&buf[1], 0, 1);
2626 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
2629 if (appData.debugMode)
2630 fprintf(debugFP, "ics_type %d\n", ics_type);
2633 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
2634 ics_type = ICS_FICS;
2636 if (appData.debugMode)
2637 fprintf(debugFP, "ics_type %d\n", ics_type);
2640 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
2641 ics_type = ICS_CHESSNET;
2643 if (appData.debugMode)
2644 fprintf(debugFP, "ics_type %d\n", ics_type);
2649 (looking_at(buf, &i, "\"*\" is *a registered name") ||
2650 looking_at(buf, &i, "Logging you in as \"*\"") ||
2651 looking_at(buf, &i, "will be \"*\""))) {
2652 strcpy(ics_handle, star_match[0]);
2656 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
2658 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
2659 DisplayIcsInteractionTitle(buf);
2660 have_set_title = TRUE;
2663 /* skip finger notes */
2664 if (started == STARTED_NONE &&
2665 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
2666 (buf[i] == '1' && buf[i+1] == '0')) &&
2667 buf[i+2] == ':' && buf[i+3] == ' ') {
2668 started = STARTED_CHATTER;
2674 // [HGM] seekgraph: recognize sought lines and end-of-sought message
2675 if(appData.seekGraph) {
2676 if(soughtPending && MatchSoughtLine(buf+i)) {
2677 i = strstr(buf+i, "rated") - buf;
2678 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2679 next_out = leftover_start = i;
2680 started = STARTED_CHATTER;
2681 suppressKibitz = TRUE;
2684 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
2685 && looking_at(buf, &i, "* ads displayed")) {
2686 soughtPending = FALSE;
2691 if(appData.autoRefresh) {
2692 if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
2693 int s = (ics_type == ICS_ICC); // ICC format differs
2695 AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
2696 star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
2697 looking_at(buf, &i, "*% "); // eat prompt
2698 if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
2699 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2700 next_out = i; // suppress
2703 if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
2704 char *p = star_match[0];
2706 if(seekGraphUp) RemoveSeekAd(atoi(p));
2707 while(*p && *p++ != ' '); // next
2709 looking_at(buf, &i, "*% "); // eat prompt
2710 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2717 /* skip formula vars */
2718 if (started == STARTED_NONE &&
2719 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
2720 started = STARTED_CHATTER;
2725 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
2726 if (appData.autoKibitz && started == STARTED_NONE &&
2727 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
2728 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
2729 if((looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
2730 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
2731 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
2732 suppressKibitz = TRUE;
2733 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2735 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
2736 && (gameMode == IcsPlayingWhite)) ||
2737 (StrStr(star_match[0], gameInfo.black) == star_match[0]
2738 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
2739 started = STARTED_CHATTER; // own kibitz we simply discard
2741 started = STARTED_COMMENT; // make sure it will be collected in parse[]
2742 parse_pos = 0; parse[0] = NULLCHAR;
2743 savingComment = TRUE;
2744 suppressKibitz = gameMode != IcsObserving ? 2 :
2745 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
2749 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
2750 looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
2751 && atoi(star_match[0])) {
2752 // suppress the acknowledgements of our own autoKibitz
2754 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2755 if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
2756 SendToPlayer(star_match[0], strlen(star_match[0]));
2757 if(looking_at(buf, &i, "*% ")) // eat prompt
2758 suppressKibitz = FALSE;
2762 } // [HGM] kibitz: end of patch
2764 // [HGM] chat: intercept tells by users for which we have an open chat window
2766 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
2767 looking_at(buf, &i, "* whispers:") ||
2768 looking_at(buf, &i, "* kibitzes:") ||
2769 looking_at(buf, &i, "* shouts:") ||
2770 looking_at(buf, &i, "* c-shouts:") ||
2771 looking_at(buf, &i, "--> * ") ||
2772 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
2773 looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
2774 looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
2775 looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
2777 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
2778 chattingPartner = -1;
2780 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
2781 for(p=0; p<MAX_CHAT; p++) {
2782 if(channel == atoi(chatPartner[p])) {
2783 talker[0] = '['; strcat(talker, "] ");
2784 Colorize(channel == 1 ? ColorChannel1 : ColorChannel, FALSE);
2785 chattingPartner = p; break;
2788 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
2789 for(p=0; p<MAX_CHAT; p++) {
2790 if(!strcmp("kibitzes", chatPartner[p])) {
2791 talker[0] = '['; strcat(talker, "] ");
2792 chattingPartner = p; break;
2795 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
2796 for(p=0; p<MAX_CHAT; p++) {
2797 if(!strcmp("whispers", chatPartner[p])) {
2798 talker[0] = '['; strcat(talker, "] ");
2799 chattingPartner = p; break;
2802 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
2803 if(buf[i-8] == '-' && buf[i-3] == 't')
2804 for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
2805 if(!strcmp("c-shouts", chatPartner[p])) {
2806 talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
2807 chattingPartner = p; break;
2810 if(chattingPartner < 0)
2811 for(p=0; p<MAX_CHAT; p++) {
2812 if(!strcmp("shouts", chatPartner[p])) {
2813 if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
2814 else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
2815 else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
2816 chattingPartner = p; break;
2820 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
2821 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
2822 talker[0] = 0; Colorize(ColorTell, FALSE);
2823 chattingPartner = p; break;
2825 if(chattingPartner<0) i = oldi; else {
2826 Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
2827 if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
2828 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2829 started = STARTED_COMMENT;
2830 parse_pos = 0; parse[0] = NULLCHAR;
2831 savingComment = 3 + chattingPartner; // counts as TRUE
2832 suppressKibitz = TRUE;
2835 } // [HGM] chat: end of patch
2837 if (appData.zippyTalk || appData.zippyPlay) {
2838 /* [DM] Backup address for color zippy lines */
2841 if (loggedOn == TRUE)
2842 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
2843 (appData.zippyPlay && ZippyMatch(buf, &backup)));
2845 } // [DM] 'else { ' deleted
2847 /* Regular tells and says */
2848 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
2849 looking_at(buf, &i, "* (your partner) tells you: ") ||
2850 looking_at(buf, &i, "* says: ") ||
2851 /* Don't color "message" or "messages" output */
2852 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
2853 looking_at(buf, &i, "*. * at *:*: ") ||
2854 looking_at(buf, &i, "--* (*:*): ") ||
2855 /* Message notifications (same color as tells) */
2856 looking_at(buf, &i, "* has left a message ") ||
2857 looking_at(buf, &i, "* just sent you a message:\n") ||
2858 /* Whispers and kibitzes */
2859 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
2860 looking_at(buf, &i, "* kibitzes: ") ||
2862 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
2864 if (tkind == 1 && strchr(star_match[0], ':')) {
2865 /* Avoid "tells you:" spoofs in channels */
2868 if (star_match[0][0] == NULLCHAR ||
2869 strchr(star_match[0], ' ') ||
2870 (tkind == 3 && strchr(star_match[1], ' '))) {
2871 /* Reject bogus matches */
2874 if (appData.colorize) {
2875 if (oldi > next_out) {
2876 SendToPlayer(&buf[next_out], oldi - next_out);
2881 Colorize(ColorTell, FALSE);
2882 curColor = ColorTell;
2885 Colorize(ColorKibitz, FALSE);
2886 curColor = ColorKibitz;
2889 p = strrchr(star_match[1], '(');
2896 Colorize(ColorChannel1, FALSE);
2897 curColor = ColorChannel1;
2899 Colorize(ColorChannel, FALSE);
2900 curColor = ColorChannel;
2904 curColor = ColorNormal;
2908 if (started == STARTED_NONE && appData.autoComment &&
2909 (gameMode == IcsObserving ||
2910 gameMode == IcsPlayingWhite ||
2911 gameMode == IcsPlayingBlack)) {
2912 parse_pos = i - oldi;
2913 memcpy(parse, &buf[oldi], parse_pos);
2914 parse[parse_pos] = NULLCHAR;
2915 started = STARTED_COMMENT;
2916 savingComment = TRUE;
2918 started = STARTED_CHATTER;
2919 savingComment = FALSE;
2926 if (looking_at(buf, &i, "* s-shouts: ") ||
2927 looking_at(buf, &i, "* c-shouts: ")) {
2928 if (appData.colorize) {
2929 if (oldi > next_out) {
2930 SendToPlayer(&buf[next_out], oldi - next_out);
2933 Colorize(ColorSShout, FALSE);
2934 curColor = ColorSShout;
2937 started = STARTED_CHATTER;
2941 if (looking_at(buf, &i, "--->")) {
2946 if (looking_at(buf, &i, "* shouts: ") ||
2947 looking_at(buf, &i, "--> ")) {
2948 if (appData.colorize) {
2949 if (oldi > next_out) {
2950 SendToPlayer(&buf[next_out], oldi - next_out);
2953 Colorize(ColorShout, FALSE);
2954 curColor = ColorShout;
2957 started = STARTED_CHATTER;
2961 if (looking_at( buf, &i, "Challenge:")) {
2962 if (appData.colorize) {
2963 if (oldi > next_out) {
2964 SendToPlayer(&buf[next_out], oldi - next_out);
2967 Colorize(ColorChallenge, FALSE);
2968 curColor = ColorChallenge;
2974 if (looking_at(buf, &i, "* offers you") ||
2975 looking_at(buf, &i, "* offers to be") ||
2976 looking_at(buf, &i, "* would like to") ||
2977 looking_at(buf, &i, "* requests to") ||
2978 looking_at(buf, &i, "Your opponent offers") ||
2979 looking_at(buf, &i, "Your opponent requests")) {
2981 if (appData.colorize) {
2982 if (oldi > next_out) {
2983 SendToPlayer(&buf[next_out], oldi - next_out);
2986 Colorize(ColorRequest, FALSE);
2987 curColor = ColorRequest;
2992 if (looking_at(buf, &i, "* (*) seeking")) {
2993 if (appData.colorize) {
2994 if (oldi > next_out) {
2995 SendToPlayer(&buf[next_out], oldi - next_out);
2998 Colorize(ColorSeek, FALSE);
2999 curColor = ColorSeek;
3004 if (looking_at(buf, &i, "\\ ")) {
3005 if (prevColor != ColorNormal) {
3006 if (oldi > next_out) {
3007 SendToPlayer(&buf[next_out], oldi - next_out);
3010 Colorize(prevColor, TRUE);
3011 curColor = prevColor;
3013 if (savingComment) {
3014 parse_pos = i - oldi;
3015 memcpy(parse, &buf[oldi], parse_pos);
3016 parse[parse_pos] = NULLCHAR;
3017 started = STARTED_COMMENT;
3018 if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3019 chattingPartner = savingComment - 3; // kludge to remember the box
3021 started = STARTED_CHATTER;
3026 if (looking_at(buf, &i, "Black Strength :") ||
3027 looking_at(buf, &i, "<<< style 10 board >>>") ||
3028 looking_at(buf, &i, "<10>") ||
3029 looking_at(buf, &i, "#@#")) {
3030 /* Wrong board style */
3032 SendToICS(ics_prefix);
3033 SendToICS("set style 12\n");
3034 SendToICS(ics_prefix);
3035 SendToICS("refresh\n");
3039 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
3041 have_sent_ICS_logon = 1;
3045 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3046 (looking_at(buf, &i, "\n<12> ") ||
3047 looking_at(buf, &i, "<12> "))) {
3049 if (oldi > next_out) {
3050 SendToPlayer(&buf[next_out], oldi - next_out);
3053 started = STARTED_BOARD;
3058 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3059 looking_at(buf, &i, "<b1> ")) {
3060 if (oldi > next_out) {
3061 SendToPlayer(&buf[next_out], oldi - next_out);
3064 started = STARTED_HOLDINGS;
3069 if (looking_at(buf, &i, "* *vs. * *--- *")) {
3071 /* Header for a move list -- first line */
3073 switch (ics_getting_history) {
3077 case BeginningOfGame:
3078 /* User typed "moves" or "oldmoves" while we
3079 were idle. Pretend we asked for these
3080 moves and soak them up so user can step
3081 through them and/or save them.
3084 gameMode = IcsObserving;
3087 ics_getting_history = H_GOT_UNREQ_HEADER;
3089 case EditGame: /*?*/
3090 case EditPosition: /*?*/
3091 /* Should above feature work in these modes too? */
3092 /* For now it doesn't */
3093 ics_getting_history = H_GOT_UNWANTED_HEADER;
3096 ics_getting_history = H_GOT_UNWANTED_HEADER;
3101 /* Is this the right one? */
3102 if (gameInfo.white && gameInfo.black &&
3103 strcmp(gameInfo.white, star_match[0]) == 0 &&
3104 strcmp(gameInfo.black, star_match[2]) == 0) {
3106 ics_getting_history = H_GOT_REQ_HEADER;
3109 case H_GOT_REQ_HEADER:
3110 case H_GOT_UNREQ_HEADER:
3111 case H_GOT_UNWANTED_HEADER:
3112 case H_GETTING_MOVES:
3113 /* Should not happen */
3114 DisplayError(_("Error gathering move list: two headers"), 0);
3115 ics_getting_history = H_FALSE;
3119 /* Save player ratings into gameInfo if needed */
3120 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3121 ics_getting_history == H_GOT_UNREQ_HEADER) &&
3122 (gameInfo.whiteRating == -1 ||
3123 gameInfo.blackRating == -1)) {
3125 gameInfo.whiteRating = string_to_rating(star_match[1]);
3126 gameInfo.blackRating = string_to_rating(star_match[3]);
3127 if (appData.debugMode)
3128 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
3129 gameInfo.whiteRating, gameInfo.blackRating);
3134 if (looking_at(buf, &i,
3135 "* * match, initial time: * minute*, increment: * second")) {
3136 /* Header for a move list -- second line */
3137 /* Initial board will follow if this is a wild game */
3138 if (gameInfo.event != NULL) free(gameInfo.event);
3139 sprintf(str, "ICS %s %s match", star_match[0], star_match[1]);
3140 gameInfo.event = StrSave(str);
3141 /* [HGM] we switched variant. Translate boards if needed. */
3142 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3146 if (looking_at(buf, &i, "Move ")) {
3147 /* Beginning of a move list */
3148 switch (ics_getting_history) {
3150 /* Normally should not happen */
3151 /* Maybe user hit reset while we were parsing */
3154 /* Happens if we are ignoring a move list that is not
3155 * the one we just requested. Common if the user
3156 * tries to observe two games without turning off
3159 case H_GETTING_MOVES:
3160 /* Should not happen */
3161 DisplayError(_("Error gathering move list: nested"), 0);
3162 ics_getting_history = H_FALSE;
3164 case H_GOT_REQ_HEADER:
3165 ics_getting_history = H_GETTING_MOVES;
3166 started = STARTED_MOVES;
3168 if (oldi > next_out) {
3169 SendToPlayer(&buf[next_out], oldi - next_out);
3172 case H_GOT_UNREQ_HEADER:
3173 ics_getting_history = H_GETTING_MOVES;
3174 started = STARTED_MOVES_NOHIDE;
3177 case H_GOT_UNWANTED_HEADER:
3178 ics_getting_history = H_FALSE;
3184 if (looking_at(buf, &i, "% ") ||
3185 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3186 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3187 if(ics_type == ICS_ICC && soughtPending) { // [HGM] seekgraph: on ICC sought-list has no termination line
3188 soughtPending = FALSE;
3192 if(suppressKibitz) next_out = i;
3193 savingComment = FALSE;
3197 case STARTED_MOVES_NOHIDE:
3198 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3199 parse[parse_pos + i - oldi] = NULLCHAR;
3200 ParseGameHistory(parse);
3202 if (appData.zippyPlay && first.initDone) {
3203 FeedMovesToProgram(&first, forwardMostMove);
3204 if (gameMode == IcsPlayingWhite) {
3205 if (WhiteOnMove(forwardMostMove)) {
3206 if (first.sendTime) {
3207 if (first.useColors) {
3208 SendToProgram("black\n", &first);
3210 SendTimeRemaining(&first, TRUE);
3212 if (first.useColors) {
3213 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3215 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3216 first.maybeThinking = TRUE;
3218 if (first.usePlayother) {
3219 if (first.sendTime) {
3220 SendTimeRemaining(&first, TRUE);
3222 SendToProgram("playother\n", &first);
3228 } else if (gameMode == IcsPlayingBlack) {
3229 if (!WhiteOnMove(forwardMostMove)) {
3230 if (first.sendTime) {
3231 if (first.useColors) {
3232 SendToProgram("white\n", &first);
3234 SendTimeRemaining(&first, FALSE);
3236 if (first.useColors) {
3237 SendToProgram("black\n", &first);
3239 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3240 first.maybeThinking = TRUE;
3242 if (first.usePlayother) {
3243 if (first.sendTime) {
3244 SendTimeRemaining(&first, FALSE);
3246 SendToProgram("playother\n", &first);
3255 if (gameMode == IcsObserving && ics_gamenum == -1) {
3256 /* Moves came from oldmoves or moves command
3257 while we weren't doing anything else.
3259 currentMove = forwardMostMove;
3260 ClearHighlights();/*!!could figure this out*/
3261 flipView = appData.flipView;
3262 DrawPosition(TRUE, boards[currentMove]);
3263 DisplayBothClocks();
3264 sprintf(str, "%s vs. %s",
3265 gameInfo.white, gameInfo.black);
3269 /* Moves were history of an active game */
3270 if (gameInfo.resultDetails != NULL) {
3271 free(gameInfo.resultDetails);
3272 gameInfo.resultDetails = NULL;
3275 HistorySet(parseList, backwardMostMove,
3276 forwardMostMove, currentMove-1);
3277 DisplayMove(currentMove - 1);
3278 if (started == STARTED_MOVES) next_out = i;
3279 started = STARTED_NONE;
3280 ics_getting_history = H_FALSE;
3283 case STARTED_OBSERVE:
3284 started = STARTED_NONE;
3285 SendToICS(ics_prefix);
3286 SendToICS("refresh\n");
3292 if(bookHit) { // [HGM] book: simulate book reply
3293 static char bookMove[MSG_SIZ]; // a bit generous?
3295 programStats.nodes = programStats.depth = programStats.time =
3296 programStats.score = programStats.got_only_move = 0;
3297 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3299 strcpy(bookMove, "move ");
3300 strcat(bookMove, bookHit);
3301 HandleMachineMove(bookMove, &first);
3306 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3307 started == STARTED_HOLDINGS ||
3308 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3309 /* Accumulate characters in move list or board */
3310 parse[parse_pos++] = buf[i];
3313 /* Start of game messages. Mostly we detect start of game
3314 when the first board image arrives. On some versions
3315 of the ICS, though, we need to do a "refresh" after starting
3316 to observe in order to get the current board right away. */
3317 if (looking_at(buf, &i, "Adding game * to observation list")) {
3318 started = STARTED_OBSERVE;
3322 /* Handle auto-observe */
3323 if (appData.autoObserve &&
3324 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3325 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3327 /* Choose the player that was highlighted, if any. */
3328 if (star_match[0][0] == '\033' ||
3329 star_match[1][0] != '\033') {
3330 player = star_match[0];
3332 player = star_match[2];
3334 sprintf(str, "%sobserve %s\n",
3335 ics_prefix, StripHighlightAndTitle(player));
3338 /* Save ratings from notify string */
3339 strcpy(player1Name, star_match[0]);
3340 player1Rating = string_to_rating(star_match[1]);
3341 strcpy(player2Name, star_match[2]);
3342 player2Rating = string_to_rating(star_match[3]);
3344 if (appData.debugMode)
3346 "Ratings from 'Game notification:' %s %d, %s %d\n",
3347 player1Name, player1Rating,
3348 player2Name, player2Rating);
3353 /* Deal with automatic examine mode after a game,
3354 and with IcsObserving -> IcsExamining transition */
3355 if (looking_at(buf, &i, "Entering examine mode for game *") ||
3356 looking_at(buf, &i, "has made you an examiner of game *")) {
3358 int gamenum = atoi(star_match[0]);
3359 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3360 gamenum == ics_gamenum) {
3361 /* We were already playing or observing this game;
3362 no need to refetch history */
3363 gameMode = IcsExamining;
3365 pauseExamForwardMostMove = forwardMostMove;
3366 } else if (currentMove < forwardMostMove) {
3367 ForwardInner(forwardMostMove);
3370 /* I don't think this case really can happen */
3371 SendToICS(ics_prefix);
3372 SendToICS("refresh\n");
3377 /* Error messages */
3378 // if (ics_user_moved) {
3379 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3380 if (looking_at(buf, &i, "Illegal move") ||
3381 looking_at(buf, &i, "Not a legal move") ||
3382 looking_at(buf, &i, "Your king is in check") ||
3383 looking_at(buf, &i, "It isn't your turn") ||
3384 looking_at(buf, &i, "It is not your move")) {
3386 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3387 currentMove = forwardMostMove-1;
3388 DisplayMove(currentMove - 1); /* before DMError */
3389 DrawPosition(FALSE, boards[currentMove]);
3390 SwitchClocks(forwardMostMove-1); // [HGM] race
3391 DisplayBothClocks();
3393 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3399 if (looking_at(buf, &i, "still have time") ||
3400 looking_at(buf, &i, "not out of time") ||
3401 looking_at(buf, &i, "either player is out of time") ||
3402 looking_at(buf, &i, "has timeseal; checking")) {
3403 /* We must have called his flag a little too soon */
3404 whiteFlag = blackFlag = FALSE;
3408 if (looking_at(buf, &i, "added * seconds to") ||
3409 looking_at(buf, &i, "seconds were added to")) {
3410 /* Update the clocks */
3411 SendToICS(ics_prefix);
3412 SendToICS("refresh\n");
3416 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3417 ics_clock_paused = TRUE;
3422 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3423 ics_clock_paused = FALSE;
3428 /* Grab player ratings from the Creating: message.
3429 Note we have to check for the special case when
3430 the ICS inserts things like [white] or [black]. */
3431 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3432 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3434 0 player 1 name (not necessarily white)
3436 2 empty, white, or black (IGNORED)
3437 3 player 2 name (not necessarily black)
3440 The names/ratings are sorted out when the game
3441 actually starts (below).
3443 strcpy(player1Name, StripHighlightAndTitle(star_match[0]));
3444 player1Rating = string_to_rating(star_match[1]);
3445 strcpy(player2Name, StripHighlightAndTitle(star_match[3]));
3446 player2Rating = string_to_rating(star_match[4]);
3448 if (appData.debugMode)
3450 "Ratings from 'Creating:' %s %d, %s %d\n",
3451 player1Name, player1Rating,
3452 player2Name, player2Rating);
3457 /* Improved generic start/end-of-game messages */
3458 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3459 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3460 /* If tkind == 0: */
3461 /* star_match[0] is the game number */
3462 /* [1] is the white player's name */
3463 /* [2] is the black player's name */
3464 /* For end-of-game: */
3465 /* [3] is the reason for the game end */
3466 /* [4] is a PGN end game-token, preceded by " " */
3467 /* For start-of-game: */
3468 /* [3] begins with "Creating" or "Continuing" */
3469 /* [4] is " *" or empty (don't care). */
3470 int gamenum = atoi(star_match[0]);
3471 char *whitename, *blackname, *why, *endtoken;
3472 ChessMove endtype = (ChessMove) 0;
3475 whitename = star_match[1];
3476 blackname = star_match[2];
3477 why = star_match[3];
3478 endtoken = star_match[4];
3480 whitename = star_match[1];
3481 blackname = star_match[3];
3482 why = star_match[5];
3483 endtoken = star_match[6];
3486 /* Game start messages */
3487 if (strncmp(why, "Creating ", 9) == 0 ||
3488 strncmp(why, "Continuing ", 11) == 0) {
3489 gs_gamenum = gamenum;
3490 strcpy(gs_kind, strchr(why, ' ') + 1);
3491 VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
3493 if (appData.zippyPlay) {
3494 ZippyGameStart(whitename, blackname);
3497 partnerBoardValid = FALSE; // [HGM] bughouse
3501 /* Game end messages */
3502 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3503 ics_gamenum != gamenum) {
3506 while (endtoken[0] == ' ') endtoken++;
3507 switch (endtoken[0]) {
3510 endtype = GameUnfinished;
3513 endtype = BlackWins;
3516 if (endtoken[1] == '/')
3517 endtype = GameIsDrawn;
3519 endtype = WhiteWins;
3522 GameEnds(endtype, why, GE_ICS);
3524 if (appData.zippyPlay && first.initDone) {
3525 ZippyGameEnd(endtype, why);
3526 if (first.pr == NULL) {
3527 /* Start the next process early so that we'll
3528 be ready for the next challenge */
3529 StartChessProgram(&first);
3531 /* Send "new" early, in case this command takes
3532 a long time to finish, so that we'll be ready
3533 for the next challenge. */
3534 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3538 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
3542 if (looking_at(buf, &i, "Removing game * from observation") ||
3543 looking_at(buf, &i, "no longer observing game *") ||
3544 looking_at(buf, &i, "Game * (*) has no examiners")) {
3545 if (gameMode == IcsObserving &&
3546 atoi(star_match[0]) == ics_gamenum)
3548 /* icsEngineAnalyze */
3549 if (appData.icsEngineAnalyze) {
3556 ics_user_moved = FALSE;
3561 if (looking_at(buf, &i, "no longer examining game *")) {
3562 if (gameMode == IcsExamining &&
3563 atoi(star_match[0]) == ics_gamenum)
3567 ics_user_moved = FALSE;
3572 /* Advance leftover_start past any newlines we find,
3573 so only partial lines can get reparsed */
3574 if (looking_at(buf, &i, "\n")) {
3575 prevColor = curColor;
3576 if (curColor != ColorNormal) {
3577 if (oldi > next_out) {
3578 SendToPlayer(&buf[next_out], oldi - next_out);
3581 Colorize(ColorNormal, FALSE);
3582 curColor = ColorNormal;
3584 if (started == STARTED_BOARD) {
3585 started = STARTED_NONE;
3586 parse[parse_pos] = NULLCHAR;
3587 ParseBoard12(parse);
3590 /* Send premove here */
3591 if (appData.premove) {
3593 if (currentMove == 0 &&
3594 gameMode == IcsPlayingWhite &&
3595 appData.premoveWhite) {
3596 sprintf(str, "%s\n", appData.premoveWhiteText);
3597 if (appData.debugMode)
3598 fprintf(debugFP, "Sending premove:\n");
3600 } else if (currentMove == 1 &&
3601 gameMode == IcsPlayingBlack &&
3602 appData.premoveBlack) {
3603 sprintf(str, "%s\n", appData.premoveBlackText);
3604 if (appData.debugMode)
3605 fprintf(debugFP, "Sending premove:\n");
3607 } else if (gotPremove) {
3609 ClearPremoveHighlights();
3610 if (appData.debugMode)
3611 fprintf(debugFP, "Sending premove:\n");
3612 UserMoveEvent(premoveFromX, premoveFromY,
3613 premoveToX, premoveToY,
3618 /* Usually suppress following prompt */
3619 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
3620 while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
3621 if (looking_at(buf, &i, "*% ")) {
3622 savingComment = FALSE;
3627 } else if (started == STARTED_HOLDINGS) {
3629 char new_piece[MSG_SIZ];
3630 started = STARTED_NONE;
3631 parse[parse_pos] = NULLCHAR;
3632 if (appData.debugMode)
3633 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
3634 parse, currentMove);
3635 if (sscanf(parse, " game %d", &gamenum) == 1) {
3636 if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
3637 if (gameInfo.variant == VariantNormal) {
3638 /* [HGM] We seem to switch variant during a game!
3639 * Presumably no holdings were displayed, so we have
3640 * to move the position two files to the right to
3641 * create room for them!
3643 VariantClass newVariant;
3644 switch(gameInfo.boardWidth) { // base guess on board width
3645 case 9: newVariant = VariantShogi; break;
3646 case 10: newVariant = VariantGreat; break;
3647 default: newVariant = VariantCrazyhouse; break;
3649 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
3650 /* Get a move list just to see the header, which
3651 will tell us whether this is really bug or zh */
3652 if (ics_getting_history == H_FALSE) {
3653 ics_getting_history = H_REQUESTED;
3654 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
3658 new_piece[0] = NULLCHAR;
3659 sscanf(parse, "game %d white [%s black [%s <- %s",
3660 &gamenum, white_holding, black_holding,
3662 white_holding[strlen(white_holding)-1] = NULLCHAR;
3663 black_holding[strlen(black_holding)-1] = NULLCHAR;
3664 /* [HGM] copy holdings to board holdings area */
3665 CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
3666 CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
3667 boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
3669 if (appData.zippyPlay && first.initDone) {
3670 ZippyHoldings(white_holding, black_holding,
3674 if (tinyLayout || smallLayout) {
3675 char wh[16], bh[16];
3676 PackHolding(wh, white_holding);
3677 PackHolding(bh, black_holding);
3678 sprintf(str, "[%s-%s] %s-%s", wh, bh,
3679 gameInfo.white, gameInfo.black);
3681 sprintf(str, "%s [%s] vs. %s [%s]",
3682 gameInfo.white, white_holding,
3683 gameInfo.black, black_holding);
3685 if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
3686 DrawPosition(FALSE, boards[currentMove]);
3688 } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
3689 sscanf(parse, "game %d white [%s black [%s <- %s",
3690 &gamenum, white_holding, black_holding,
3692 white_holding[strlen(white_holding)-1] = NULLCHAR;
3693 black_holding[strlen(black_holding)-1] = NULLCHAR;
3694 /* [HGM] copy holdings to partner-board holdings area */
3695 CopyHoldings(partnerBoard, white_holding, WhitePawn);
3696 CopyHoldings(partnerBoard, black_holding, BlackPawn);
3697 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
3698 if(partnerUp) DrawPosition(FALSE, partnerBoard);
3699 if(twoBoards) { partnerUp = 0; flipView = !flipView; }
3702 /* Suppress following prompt */
3703 if (looking_at(buf, &i, "*% ")) {
3704 if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
3705 savingComment = FALSE;
3713 i++; /* skip unparsed character and loop back */
3716 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
3717 // started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
3718 // SendToPlayer(&buf[next_out], i - next_out);
3719 started != STARTED_HOLDINGS && leftover_start > next_out) {
3720 SendToPlayer(&buf[next_out], leftover_start - next_out);
3724 leftover_len = buf_len - leftover_start;
3725 /* if buffer ends with something we couldn't parse,
3726 reparse it after appending the next read */
3728 } else if (count == 0) {
3729 RemoveInputSource(isr);
3730 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
3732 DisplayFatalError(_("Error reading from ICS"), error, 1);
3737 /* Board style 12 looks like this:
3739 <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
3741 * The "<12> " is stripped before it gets to this routine. The two
3742 * trailing 0's (flip state and clock ticking) are later addition, and
3743 * some chess servers may not have them, or may have only the first.
3744 * Additional trailing fields may be added in the future.
3747 #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"
3749 #define RELATION_OBSERVING_PLAYED 0
3750 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
3751 #define RELATION_PLAYING_MYMOVE 1
3752 #define RELATION_PLAYING_NOTMYMOVE -1
3753 #define RELATION_EXAMINING 2
3754 #define RELATION_ISOLATED_BOARD -3
3755 #define RELATION_STARTING_POSITION -4 /* FICS only */
3758 ParseBoard12(string)
3761 GameMode newGameMode;
3762 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0, i;
3763 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time, takeback;
3764 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
3765 char to_play, board_chars[200];
3766 char move_str[500], str[500], elapsed_time[500];
3767 char black[32], white[32];
3769 int prevMove = currentMove;
3772 int fromX, fromY, toX, toY;
3774 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
3775 char *bookHit = NULL; // [HGM] book
3776 Boolean weird = FALSE, reqFlag = FALSE;
3778 fromX = fromY = toX = toY = -1;
3782 if (appData.debugMode)
3783 fprintf(debugFP, _("Parsing board: %s\n"), string);
3785 move_str[0] = NULLCHAR;
3786 elapsed_time[0] = NULLCHAR;
3787 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
3789 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
3790 if(string[i] == ' ') { ranks++; files = 0; }
3792 if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
3795 for(j = 0; j <i; j++) board_chars[j] = string[j];
3796 board_chars[i] = '\0';
3799 n = sscanf(string, PATTERN, &to_play, &double_push,
3800 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
3801 &gamenum, white, black, &relation, &basetime, &increment,
3802 &white_stren, &black_stren, &white_time, &black_time,
3803 &moveNum, str, elapsed_time, move_str, &ics_flip,
3807 snprintf(str, sizeof(str), _("Failed to parse board string:\n\"%s\""), string);
3808 DisplayError(str, 0);
3812 /* Convert the move number to internal form */
3813 moveNum = (moveNum - 1) * 2;
3814 if (to_play == 'B') moveNum++;
3815 if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
3816 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
3822 case RELATION_OBSERVING_PLAYED:
3823 case RELATION_OBSERVING_STATIC:
3824 if (gamenum == -1) {
3825 /* Old ICC buglet */
3826 relation = RELATION_OBSERVING_STATIC;
3828 newGameMode = IcsObserving;
3830 case RELATION_PLAYING_MYMOVE:
3831 case RELATION_PLAYING_NOTMYMOVE:
3833 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
3834 IcsPlayingWhite : IcsPlayingBlack;
3836 case RELATION_EXAMINING:
3837 newGameMode = IcsExamining;
3839 case RELATION_ISOLATED_BOARD:
3841 /* Just display this board. If user was doing something else,
3842 we will forget about it until the next board comes. */
3843 newGameMode = IcsIdle;
3845 case RELATION_STARTING_POSITION:
3846 newGameMode = gameMode;
3850 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
3851 && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
3852 // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
3854 for (k = 0; k < ranks; k++) {
3855 for (j = 0; j < files; j++)
3856 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
3857 if(gameInfo.holdingsWidth > 1) {
3858 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
3859 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
3862 CopyBoard(partnerBoard, board);
3863 if(toSqr = strchr(str, '/')) { // extract highlights from long move
3864 partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
3865 partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
3866 } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
3867 if(toSqr = strchr(str, '-')) {
3868 partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
3869 partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
3870 } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
3871 if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
3872 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
3873 if(partnerUp) DrawPosition(FALSE, partnerBoard);
3874 if(twoBoards) { partnerUp = 0; flipView = !flipView; } // [HGM] dual
3875 sprintf(partnerStatus, "W: %d:%02d B: %d:%02d (%d-%d) %c", white_time/60000, (white_time%60000)/1000,
3876 (black_time/60000), (black_time%60000)/1000, white_stren, black_stren, to_play);
3877 DisplayMessage(partnerStatus, "");
3878 partnerBoardValid = TRUE;
3882 /* Modify behavior for initial board display on move listing
3885 switch (ics_getting_history) {
3889 case H_GOT_REQ_HEADER:
3890 case H_GOT_UNREQ_HEADER:
3891 /* This is the initial position of the current game */
3892 gamenum = ics_gamenum;
3893 moveNum = 0; /* old ICS bug workaround */
3894 if (to_play == 'B') {
3895 startedFromSetupPosition = TRUE;
3896 blackPlaysFirst = TRUE;
3898 if (forwardMostMove == 0) forwardMostMove = 1;
3899 if (backwardMostMove == 0) backwardMostMove = 1;
3900 if (currentMove == 0) currentMove = 1;
3902 newGameMode = gameMode;
3903 relation = RELATION_STARTING_POSITION; /* ICC needs this */
3905 case H_GOT_UNWANTED_HEADER:
3906 /* This is an initial board that we don't want */
3908 case H_GETTING_MOVES:
3909 /* Should not happen */
3910 DisplayError(_("Error gathering move list: extra board"), 0);
3911 ics_getting_history = H_FALSE;
3915 if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
3916 weird && (int)gameInfo.variant <= (int)VariantShogi) {
3917 /* [HGM] We seem to have switched variant unexpectedly
3918 * Try to guess new variant from board size
3920 VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
3921 if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
3922 if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
3923 if(ranks == 8 && files == 12) newVariant = VariantCourier; else
3924 if(ranks == 9 && files == 9) newVariant = VariantShogi; else
3925 if(!weird) newVariant = VariantNormal;
3926 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
3927 /* Get a move list just to see the header, which
3928 will tell us whether this is really bug or zh */
3929 if (ics_getting_history == H_FALSE) {
3930 ics_getting_history = H_REQUESTED; reqFlag = TRUE;
3931 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
3936 /* Take action if this is the first board of a new game, or of a
3937 different game than is currently being displayed. */
3938 if (gamenum != ics_gamenum || newGameMode != gameMode ||
3939 relation == RELATION_ISOLATED_BOARD) {
3941 /* Forget the old game and get the history (if any) of the new one */
3942 if (gameMode != BeginningOfGame) {
3946 if (appData.autoRaiseBoard) BoardToTop();
3948 if (gamenum == -1) {
3949 newGameMode = IcsIdle;
3950 } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
3951 appData.getMoveList && !reqFlag) {
3952 /* Need to get game history */
3953 ics_getting_history = H_REQUESTED;
3954 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
3958 /* Initially flip the board to have black on the bottom if playing
3959 black or if the ICS flip flag is set, but let the user change
3960 it with the Flip View button. */
3961 flipView = appData.autoFlipView ?
3962 (newGameMode == IcsPlayingBlack) || ics_flip :
3965 /* Done with values from previous mode; copy in new ones */
3966 gameMode = newGameMode;
3968 ics_gamenum = gamenum;
3969 if (gamenum == gs_gamenum) {
3970 int klen = strlen(gs_kind);
3971 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
3972 sprintf(str, "ICS %s", gs_kind);
3973 gameInfo.event = StrSave(str);
3975 gameInfo.event = StrSave("ICS game");
3977 gameInfo.site = StrSave(appData.icsHost);
3978 gameInfo.date = PGNDate();
3979 gameInfo.round = StrSave("-");
3980 gameInfo.white = StrSave(white);
3981 gameInfo.black = StrSave(black);
3982 timeControl = basetime * 60 * 1000;
3984 timeIncrement = increment * 1000;
3985 movesPerSession = 0;
3986 gameInfo.timeControl = TimeControlTagValue();
3987 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
3988 if (appData.debugMode) {
3989 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
3990 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
3991 setbuf(debugFP, NULL);
3994 gameInfo.outOfBook = NULL;
3996 /* Do we have the ratings? */
3997 if (strcmp(player1Name, white) == 0 &&
3998 strcmp(player2Name, black) == 0) {
3999 if (appData.debugMode)
4000 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4001 player1Rating, player2Rating);
4002 gameInfo.whiteRating = player1Rating;
4003 gameInfo.blackRating = player2Rating;
4004 } else if (strcmp(player2Name, white) == 0 &&
4005 strcmp(player1Name, black) == 0) {
4006 if (appData.debugMode)
4007 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4008 player2Rating, player1Rating);
4009 gameInfo.whiteRating = player2Rating;
4010 gameInfo.blackRating = player1Rating;
4012 player1Name[0] = player2Name[0] = NULLCHAR;
4014 /* Silence shouts if requested */
4015 if (appData.quietPlay &&
4016 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4017 SendToICS(ics_prefix);
4018 SendToICS("set shout 0\n");
4022 /* Deal with midgame name changes */
4024 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4025 if (gameInfo.white) free(gameInfo.white);
4026 gameInfo.white = StrSave(white);
4028 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4029 if (gameInfo.black) free(gameInfo.black);
4030 gameInfo.black = StrSave(black);
4034 /* Throw away game result if anything actually changes in examine mode */
4035 if (gameMode == IcsExamining && !newGame) {
4036 gameInfo.result = GameUnfinished;
4037 if (gameInfo.resultDetails != NULL) {
4038 free(gameInfo.resultDetails);
4039 gameInfo.resultDetails = NULL;
4043 /* In pausing && IcsExamining mode, we ignore boards coming
4044 in if they are in a different variation than we are. */
4045 if (pauseExamInvalid) return;
4046 if (pausing && gameMode == IcsExamining) {
4047 if (moveNum <= pauseExamForwardMostMove) {
4048 pauseExamInvalid = TRUE;
4049 forwardMostMove = pauseExamForwardMostMove;
4054 if (appData.debugMode) {
4055 fprintf(debugFP, "load %dx%d board\n", files, ranks);
4057 /* Parse the board */
4058 for (k = 0; k < ranks; k++) {
4059 for (j = 0; j < files; j++)
4060 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4061 if(gameInfo.holdingsWidth > 1) {
4062 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4063 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4066 CopyBoard(boards[moveNum], board);
4067 boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4069 startedFromSetupPosition =
4070 !CompareBoards(board, initialPosition);
4071 if(startedFromSetupPosition)
4072 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4075 /* [HGM] Set castling rights. Take the outermost Rooks,
4076 to make it also work for FRC opening positions. Note that board12
4077 is really defective for later FRC positions, as it has no way to
4078 indicate which Rook can castle if they are on the same side of King.
4079 For the initial position we grant rights to the outermost Rooks,
4080 and remember thos rights, and we then copy them on positions
4081 later in an FRC game. This means WB might not recognize castlings with
4082 Rooks that have moved back to their original position as illegal,
4083 but in ICS mode that is not its job anyway.
4085 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4086 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4088 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4089 if(board[0][i] == WhiteRook) j = i;
4090 initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4091 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4092 if(board[0][i] == WhiteRook) j = i;
4093 initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4094 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4095 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4096 initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4097 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4098 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4099 initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4101 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4102 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4103 if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4104 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4105 if(board[BOARD_HEIGHT-1][k] == bKing)
4106 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4107 if(gameInfo.variant == VariantTwoKings) {
4108 // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4109 if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4110 if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4113 r = boards[moveNum][CASTLING][0] = initialRights[0];
4114 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4115 r = boards[moveNum][CASTLING][1] = initialRights[1];
4116 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4117 r = boards[moveNum][CASTLING][3] = initialRights[3];
4118 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4119 r = boards[moveNum][CASTLING][4] = initialRights[4];
4120 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4121 /* wildcastle kludge: always assume King has rights */
4122 r = boards[moveNum][CASTLING][2] = initialRights[2];
4123 r = boards[moveNum][CASTLING][5] = initialRights[5];
4125 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4126 boards[moveNum][EP_STATUS] = double_push == -1 ? EP_NONE : double_push + BOARD_LEFT;
4129 if (ics_getting_history == H_GOT_REQ_HEADER ||
4130 ics_getting_history == H_GOT_UNREQ_HEADER) {
4131 /* This was an initial position from a move list, not
4132 the current position */
4136 /* Update currentMove and known move number limits */
4137 newMove = newGame || moveNum > forwardMostMove;
4140 forwardMostMove = backwardMostMove = currentMove = moveNum;
4141 if (gameMode == IcsExamining && moveNum == 0) {
4142 /* Workaround for ICS limitation: we are not told the wild
4143 type when starting to examine a game. But if we ask for
4144 the move list, the move list header will tell us */
4145 ics_getting_history = H_REQUESTED;
4146 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
4149 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4150 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4152 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4153 /* [HGM] applied this also to an engine that is silently watching */
4154 if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4155 (gameMode == IcsObserving || gameMode == IcsExamining) &&
4156 gameInfo.variant == currentlyInitializedVariant) {
4157 takeback = forwardMostMove - moveNum;
4158 for (i = 0; i < takeback; i++) {
4159 if (appData.debugMode) fprintf(debugFP, "take back move\n");
4160 SendToProgram("undo\n", &first);
4165 forwardMostMove = moveNum;
4166 if (!pausing || currentMove > forwardMostMove)
4167 currentMove = forwardMostMove;
4169 /* New part of history that is not contiguous with old part */
4170 if (pausing && gameMode == IcsExamining) {
4171 pauseExamInvalid = TRUE;
4172 forwardMostMove = pauseExamForwardMostMove;
4175 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4177 if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4178 // [HGM] when we will receive the move list we now request, it will be
4179 // fed to the engine from the first move on. So if the engine is not
4180 // in the initial position now, bring it there.
4181 InitChessProgram(&first, 0);
4184 ics_getting_history = H_REQUESTED;
4185 sprintf(str, "%smoves %d\n", ics_prefix, gamenum);
4188 forwardMostMove = backwardMostMove = currentMove = moveNum;
4191 /* Update the clocks */
4192 if (strchr(elapsed_time, '.')) {
4194 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4195 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4197 /* Time is in seconds */
4198 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4199 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4204 if (appData.zippyPlay && newGame &&
4205 gameMode != IcsObserving && gameMode != IcsIdle &&
4206 gameMode != IcsExamining)
4207 ZippyFirstBoard(moveNum, basetime, increment);
4210 /* Put the move on the move list, first converting
4211 to canonical algebraic form. */
4213 if (appData.debugMode) {
4214 if (appData.debugMode) { int f = forwardMostMove;
4215 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4216 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4217 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4219 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4220 fprintf(debugFP, "moveNum = %d\n", moveNum);
4221 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4222 setbuf(debugFP, NULL);
4224 if (moveNum <= backwardMostMove) {
4225 /* We don't know what the board looked like before
4227 strcpy(parseList[moveNum - 1], move_str);
4228 strcat(parseList[moveNum - 1], " ");
4229 strcat(parseList[moveNum - 1], elapsed_time);
4230 moveList[moveNum - 1][0] = NULLCHAR;
4231 } else if (strcmp(move_str, "none") == 0) {
4232 // [HGM] long SAN: swapped order; test for 'none' before parsing move
4233 /* Again, we don't know what the board looked like;
4234 this is really the start of the game. */
4235 parseList[moveNum - 1][0] = NULLCHAR;
4236 moveList[moveNum - 1][0] = NULLCHAR;
4237 backwardMostMove = moveNum;
4238 startedFromSetupPosition = TRUE;
4239 fromX = fromY = toX = toY = -1;
4241 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4242 // So we parse the long-algebraic move string in stead of the SAN move
4243 int valid; char buf[MSG_SIZ], *prom;
4245 // str looks something like "Q/a1-a2"; kill the slash
4247 sprintf(buf, "%c%s", str[0], str+2);
4248 else strcpy(buf, str); // might be castling
4249 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4250 strcat(buf, prom); // long move lacks promo specification!
4251 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4252 if(appData.debugMode)
4253 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4254 strcpy(move_str, buf);
4256 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4257 &fromX, &fromY, &toX, &toY, &promoChar)
4258 || ParseOneMove(buf, moveNum - 1, &moveType,
4259 &fromX, &fromY, &toX, &toY, &promoChar);
4260 // end of long SAN patch
4262 (void) CoordsToAlgebraic(boards[moveNum - 1],
4263 PosFlags(moveNum - 1),
4264 fromY, fromX, toY, toX, promoChar,
4265 parseList[moveNum-1]);
4266 switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4272 if(gameInfo.variant != VariantShogi)
4273 strcat(parseList[moveNum - 1], "+");
4276 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4277 strcat(parseList[moveNum - 1], "#");
4280 strcat(parseList[moveNum - 1], " ");
4281 strcat(parseList[moveNum - 1], elapsed_time);
4282 /* currentMoveString is set as a side-effect of ParseOneMove */
4283 strcpy(moveList[moveNum - 1], currentMoveString);
4284 strcat(moveList[moveNum - 1], "\n");
4286 /* Move from ICS was illegal!? Punt. */
4287 if (appData.debugMode) {
4288 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4289 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4291 strcpy(parseList[moveNum - 1], move_str);
4292 strcat(parseList[moveNum - 1], " ");
4293 strcat(parseList[moveNum - 1], elapsed_time);
4294 moveList[moveNum - 1][0] = NULLCHAR;
4295 fromX = fromY = toX = toY = -1;
4298 if (appData.debugMode) {
4299 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4300 setbuf(debugFP, NULL);
4304 /* Send move to chess program (BEFORE animating it). */
4305 if (appData.zippyPlay && !newGame && newMove &&
4306 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4308 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4309 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4310 if (moveList[moveNum - 1][0] == NULLCHAR) {
4311 sprintf(str, _("Couldn't parse move \"%s\" from ICS"),
4313 DisplayError(str, 0);
4315 if (first.sendTime) {
4316 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4318 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4319 if (firstMove && !bookHit) {
4321 if (first.useColors) {
4322 SendToProgram(gameMode == IcsPlayingWhite ?
4324 "black\ngo\n", &first);
4326 SendToProgram("go\n", &first);
4328 first.maybeThinking = TRUE;
4331 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4332 if (moveList[moveNum - 1][0] == NULLCHAR) {
4333 sprintf(str, _("Couldn't parse move \"%s\" from ICS"), move_str);
4334 DisplayError(str, 0);
4336 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4337 SendMoveToProgram(moveNum - 1, &first);
4344 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
4345 /* If move comes from a remote source, animate it. If it
4346 isn't remote, it will have already been animated. */
4347 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
4348 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
4350 if (!pausing && appData.highlightLastMove) {
4351 SetHighlights(fromX, fromY, toX, toY);
4355 /* Start the clocks */
4356 whiteFlag = blackFlag = FALSE;
4357 appData.clockMode = !(basetime == 0 && increment == 0);
4359 ics_clock_paused = TRUE;
4361 } else if (ticking == 1) {
4362 ics_clock_paused = FALSE;
4364 if (gameMode == IcsIdle ||
4365 relation == RELATION_OBSERVING_STATIC ||
4366 relation == RELATION_EXAMINING ||
4368 DisplayBothClocks();
4372 /* Display opponents and material strengths */
4373 if (gameInfo.variant != VariantBughouse &&
4374 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
4375 if (tinyLayout || smallLayout) {
4376 if(gameInfo.variant == VariantNormal)
4377 sprintf(str, "%s(%d) %s(%d) {%d %d}",
4378 gameInfo.white, white_stren, gameInfo.black, black_stren,
4379 basetime, increment);
4381 sprintf(str, "%s(%d) %s(%d) {%d %d w%d}",
4382 gameInfo.white, white_stren, gameInfo.black, black_stren,
4383 basetime, increment, (int) gameInfo.variant);
4385 if(gameInfo.variant == VariantNormal)
4386 sprintf(str, "%s (%d) vs. %s (%d) {%d %d}",
4387 gameInfo.white, white_stren, gameInfo.black, black_stren,
4388 basetime, increment);
4390 sprintf(str, "%s (%d) vs. %s (%d) {%d %d %s}",
4391 gameInfo.white, white_stren, gameInfo.black, black_stren,
4392 basetime, increment, VariantName(gameInfo.variant));
4395 if (appData.debugMode) {
4396 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
4401 /* Display the board */
4402 if (!pausing && !appData.noGUI) {
4404 if (appData.premove)
4406 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
4407 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
4408 ClearPremoveHighlights();
4410 j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
4411 if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
4412 DrawPosition(j, boards[currentMove]);
4414 DisplayMove(moveNum - 1);
4415 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
4416 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
4417 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
4418 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
4422 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
4424 if(bookHit) { // [HGM] book: simulate book reply
4425 static char bookMove[MSG_SIZ]; // a bit generous?
4427 programStats.nodes = programStats.depth = programStats.time =
4428 programStats.score = programStats.got_only_move = 0;
4429 sprintf(programStats.movelist, "%s (xbook)", bookHit);
4431 strcpy(bookMove, "move ");
4432 strcat(bookMove, bookHit);
4433 HandleMachineMove(bookMove, &first);
4442 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
4443 ics_getting_history = H_REQUESTED;
4444 sprintf(buf, "%smoves %d\n", ics_prefix, ics_gamenum);
4450 AnalysisPeriodicEvent(force)
4453 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
4454 && !force) || !appData.periodicUpdates)
4457 /* Send . command to Crafty to collect stats */
4458 SendToProgram(".\n", &first);
4460 /* Don't send another until we get a response (this makes
4461 us stop sending to old Crafty's which don't understand
4462 the "." command (sending illegal cmds resets node count & time,
4463 which looks bad)) */
4464 programStats.ok_to_send = 0;
4467 void ics_update_width(new_width)
4470 ics_printf("set width %d\n", new_width);
4474 SendMoveToProgram(moveNum, cps)
4476 ChessProgramState *cps;
4480 if (cps->useUsermove) {
4481 SendToProgram("usermove ", cps);
4485 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
4486 int len = space - parseList[moveNum];
4487 memcpy(buf, parseList[moveNum], len);
4489 buf[len] = NULLCHAR;
4491 sprintf(buf, "%s\n", parseList[moveNum]);
4493 SendToProgram(buf, cps);
4495 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
4496 AlphaRank(moveList[moveNum], 4);
4497 SendToProgram(moveList[moveNum], cps);
4498 AlphaRank(moveList[moveNum], 4); // and back
4500 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
4501 * the engine. It would be nice to have a better way to identify castle
4503 if((gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom)
4504 && cps->useOOCastle) {
4505 int fromX = moveList[moveNum][0] - AAA;
4506 int fromY = moveList[moveNum][1] - ONE;
4507 int toX = moveList[moveNum][2] - AAA;
4508 int toY = moveList[moveNum][3] - ONE;
4509 if((boards[moveNum][fromY][fromX] == WhiteKing
4510 && boards[moveNum][toY][toX] == WhiteRook)
4511 || (boards[moveNum][fromY][fromX] == BlackKing
4512 && boards[moveNum][toY][toX] == BlackRook)) {
4513 if(toX > fromX) SendToProgram("O-O\n", cps);
4514 else SendToProgram("O-O-O\n", cps);
4516 else SendToProgram(moveList[moveNum], cps);
4518 else SendToProgram(moveList[moveNum], cps);
4519 /* End of additions by Tord */
4522 /* [HGM] setting up the opening has brought engine in force mode! */
4523 /* Send 'go' if we are in a mode where machine should play. */
4524 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
4525 (gameMode == TwoMachinesPlay ||
4527 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
4529 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
4530 SendToProgram("go\n", cps);
4531 if (appData.debugMode) {
4532 fprintf(debugFP, "(extra)\n");
4535 setboardSpoiledMachineBlack = 0;
4539 SendMoveToICS(moveType, fromX, fromY, toX, toY)
4541 int fromX, fromY, toX, toY;
4543 char user_move[MSG_SIZ];
4547 sprintf(user_move, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
4548 (int)moveType, fromX, fromY, toX, toY);
4549 DisplayError(user_move + strlen("say "), 0);
4551 case WhiteKingSideCastle:
4552 case BlackKingSideCastle:
4553 case WhiteQueenSideCastleWild:
4554 case BlackQueenSideCastleWild:
4556 case WhiteHSideCastleFR:
4557 case BlackHSideCastleFR:
4559 sprintf(user_move, "o-o\n");
4561 case WhiteQueenSideCastle:
4562 case BlackQueenSideCastle:
4563 case WhiteKingSideCastleWild:
4564 case BlackKingSideCastleWild:
4566 case WhiteASideCastleFR:
4567 case BlackASideCastleFR:
4569 sprintf(user_move, "o-o-o\n");
4571 case WhitePromotionQueen:
4572 case BlackPromotionQueen:
4573 case WhitePromotionRook:
4574 case BlackPromotionRook:
4575 case WhitePromotionBishop:
4576 case BlackPromotionBishop:
4577 case WhitePromotionKnight:
4578 case BlackPromotionKnight:
4579 case WhitePromotionKing:
4580 case BlackPromotionKing:
4581 case WhitePromotionChancellor:
4582 case BlackPromotionChancellor:
4583 case WhitePromotionArchbishop:
4584 case BlackPromotionArchbishop:
4585 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
4586 sprintf(user_move, "%c%c%c%c=%c\n",
4587 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4588 PieceToChar(WhiteFerz));
4589 else if(gameInfo.variant == VariantGreat)
4590 sprintf(user_move, "%c%c%c%c=%c\n",
4591 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4592 PieceToChar(WhiteMan));
4594 sprintf(user_move, "%c%c%c%c=%c\n",
4595 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4596 PieceToChar(PromoPiece(moveType)));
4600 sprintf(user_move, "%c@%c%c\n",
4601 ToUpper(PieceToChar((ChessSquare) fromX)),
4602 AAA + toX, ONE + toY);
4605 case WhiteCapturesEnPassant:
4606 case BlackCapturesEnPassant:
4607 case IllegalMove: /* could be a variant we don't quite understand */
4608 sprintf(user_move, "%c%c%c%c\n",
4609 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4612 SendToICS(user_move);
4613 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
4614 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
4619 { // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
4620 int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
4621 static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
4622 if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
4623 DisplayError("You cannot do this while you are playing or observing", 0);
4626 if(gameMode != IcsExamining) { // is this ever not the case?
4627 char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
4629 if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
4630 sprintf(command, "match %s", ics_handle);
4631 } else { // on FICS we must first go to general examine mode
4632 strcpy(command, "examine\nbsetup"); // and specify variant within it with bsetups
4634 if(gameInfo.variant != VariantNormal) {
4635 // try figure out wild number, as xboard names are not always valid on ICS
4636 for(i=1; i<=36; i++) {
4637 sprintf(buf, "wild/%d", i);
4638 if(StringToVariant(buf) == gameInfo.variant) break;
4640 if(i<=36 && ics_type == ICS_ICC) sprintf(buf, "%s w%d\n", command, i);
4641 else if(i == 22) sprintf(buf, "%s fr\n", command);
4642 else sprintf(buf, "%s %s\n", command, VariantName(gameInfo.variant));
4643 } else sprintf(buf, "%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
4644 SendToICS(ics_prefix);
4646 if(startedFromSetupPosition || backwardMostMove != 0) {
4647 fen = PositionToFEN(backwardMostMove, NULL);
4648 if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
4649 sprintf(buf, "loadfen %s\n", fen);
4651 } else { // FICS: everything has to set by separate bsetup commands
4652 p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
4653 sprintf(buf, "bsetup fen %s\n", fen);
4655 if(!WhiteOnMove(backwardMostMove)) {
4656 SendToICS("bsetup tomove black\n");
4658 i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
4659 sprintf(buf, "bsetup wcastle %s\n", castlingStrings[i]);
4661 i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
4662 sprintf(buf, "bsetup bcastle %s\n", castlingStrings[i]);
4664 i = boards[backwardMostMove][EP_STATUS];
4665 if(i >= 0) { // set e.p.
4666 sprintf(buf, "bsetup eppos %c\n", i+AAA);
4672 if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
4673 SendToICS("bsetup done\n"); // switch to normal examining.
4675 for(i = backwardMostMove; i<last; i++) {
4677 sprintf(buf, "%s\n", parseList[i]);
4680 SendToICS(ics_prefix);
4681 SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
4685 CoordsToComputerAlgebraic(rf, ff, rt, ft, promoChar, move)
4690 if (rf == DROP_RANK) {
4691 sprintf(move, "%c@%c%c\n",
4692 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
4694 if (promoChar == 'x' || promoChar == NULLCHAR) {
4695 sprintf(move, "%c%c%c%c\n",
4696 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
4698 sprintf(move, "%c%c%c%c%c\n",
4699 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
4705 ProcessICSInitScript(f)
4710 while (fgets(buf, MSG_SIZ, f)) {
4711 SendToICSDelayed(buf,(long)appData.msLoginDelay);
4718 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
4720 AlphaRank(char *move, int n)
4722 // char *p = move, c; int x, y;
4724 if (appData.debugMode) {
4725 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
4729 move[2]>='0' && move[2]<='9' &&
4730 move[3]>='a' && move[3]<='x' ) {
4732 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4733 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4735 if(move[0]>='0' && move[0]<='9' &&
4736 move[1]>='a' && move[1]<='x' &&
4737 move[2]>='0' && move[2]<='9' &&
4738 move[3]>='a' && move[3]<='x' ) {
4739 /* input move, Shogi -> normal */
4740 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
4741 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
4742 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4743 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4746 move[3]>='0' && move[3]<='9' &&
4747 move[2]>='a' && move[2]<='x' ) {
4749 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4750 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4753 move[0]>='a' && move[0]<='x' &&
4754 move[3]>='0' && move[3]<='9' &&
4755 move[2]>='a' && move[2]<='x' ) {
4756 /* output move, normal -> Shogi */
4757 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
4758 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
4759 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4760 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4761 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
4763 if (appData.debugMode) {
4764 fprintf(debugFP, " out = '%s'\n", move);
4768 char yy_textstr[8000];
4770 /* Parser for moves from gnuchess, ICS, or user typein box */
4772 ParseOneMove(move, moveNum, moveType, fromX, fromY, toX, toY, promoChar)
4775 ChessMove *moveType;
4776 int *fromX, *fromY, *toX, *toY;
4779 if (appData.debugMode) {
4780 fprintf(debugFP, "move to parse: %s\n", move);
4782 *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
4784 switch (*moveType) {
4785 case WhitePromotionChancellor:
4786 case BlackPromotionChancellor:
4787 case WhitePromotionArchbishop:
4788 case BlackPromotionArchbishop:
4789 case WhitePromotionQueen:
4790 case BlackPromotionQueen:
4791 case WhitePromotionRook:
4792 case BlackPromotionRook:
4793 case WhitePromotionBishop:
4794 case BlackPromotionBishop:
4795 case WhitePromotionKnight:
4796 case BlackPromotionKnight:
4797 case WhitePromotionKing:
4798 case BlackPromotionKing:
4800 case WhiteCapturesEnPassant:
4801 case BlackCapturesEnPassant:
4802 case WhiteKingSideCastle:
4803 case WhiteQueenSideCastle:
4804 case BlackKingSideCastle:
4805 case BlackQueenSideCastle:
4806 case WhiteKingSideCastleWild:
4807 case WhiteQueenSideCastleWild:
4808 case BlackKingSideCastleWild:
4809 case BlackQueenSideCastleWild:
4810 /* Code added by Tord: */
4811 case WhiteHSideCastleFR:
4812 case WhiteASideCastleFR:
4813 case BlackHSideCastleFR:
4814 case BlackASideCastleFR:
4815 /* End of code added by Tord */
4816 case IllegalMove: /* bug or odd chess variant */
4817 *fromX = currentMoveString[0] - AAA;
4818 *fromY = currentMoveString[1] - ONE;
4819 *toX = currentMoveString[2] - AAA;
4820 *toY = currentMoveString[3] - ONE;
4821 *promoChar = currentMoveString[4];
4822 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
4823 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
4824 if (appData.debugMode) {
4825 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
4827 *fromX = *fromY = *toX = *toY = 0;
4830 if (appData.testLegality) {
4831 return (*moveType != IllegalMove);
4833 return !(*fromX == *toX && *fromY == *toY) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
4834 WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
4839 *fromX = *moveType == WhiteDrop ?
4840 (int) CharToPiece(ToUpper(currentMoveString[0])) :
4841 (int) CharToPiece(ToLower(currentMoveString[0]));
4843 *toX = currentMoveString[2] - AAA;
4844 *toY = currentMoveString[3] - ONE;
4845 *promoChar = NULLCHAR;
4849 case ImpossibleMove:
4850 case (ChessMove) 0: /* end of file */
4859 if (appData.debugMode) {
4860 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
4863 *fromX = *fromY = *toX = *toY = 0;
4864 *promoChar = NULLCHAR;
4871 ParsePV(char *pv, Boolean storeComments)
4872 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
4873 int fromX, fromY, toX, toY; char promoChar;
4878 endPV = forwardMostMove;
4880 while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
4881 if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
4882 valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
4883 if(appData.debugMode){
4884 fprintf(debugFP,"parsePV: %d %c%c%c%c yy='%s'\nPV = '%s'\n", valid, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, yy_textstr, pv);
4886 if(!valid && nr == 0 &&
4887 ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
4888 nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
4889 // Hande case where played move is different from leading PV move
4890 CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
4891 CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
4892 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
4893 if(!CompareBoards(boards[endPV], boards[endPV+2])) {
4894 endPV += 2; // if position different, keep this
4895 moveList[endPV-1][0] = fromX + AAA;
4896 moveList[endPV-1][1] = fromY + ONE;
4897 moveList[endPV-1][2] = toX + AAA;
4898 moveList[endPV-1][3] = toY + ONE;
4899 parseList[endPV-1][0] = NULLCHAR;
4900 strcpy(moveList[endPV-2], "_0_0"); // suppress premove highlight on takeback move
4903 pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
4904 if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
4905 if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
4906 if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
4907 valid++; // allow comments in PV
4911 if(endPV+1 > framePtr) break; // no space, truncate
4914 CopyBoard(boards[endPV], boards[endPV-1]);
4915 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
4916 moveList[endPV-1][0] = fromX + AAA;
4917 moveList[endPV-1][1] = fromY + ONE;
4918 moveList[endPV-1][2] = toX + AAA;
4919 moveList[endPV-1][3] = toY + ONE;
4921 CoordsToAlgebraic(boards[endPV - 1],
4922 PosFlags(endPV - 1),
4923 fromY, fromX, toY, toX, promoChar,
4924 parseList[endPV - 1]);
4926 parseList[endPV-1][0] = NULLCHAR;
4928 currentMove = endPV;
4929 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
4930 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
4931 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
4932 DrawPosition(TRUE, boards[currentMove]);
4935 static int lastX, lastY;
4938 LoadMultiPV(int x, int y, char *buf, int index, int *start, int *end)
4943 if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
4944 lastX = x; lastY = y;
4945 while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
4947 while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
4948 if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
4950 do{ while(buf[index] && buf[index] != '\n') index++;
4951 } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
4953 ParsePV(buf+startPV, FALSE);
4954 *start = startPV; *end = index-1;
4959 LoadPV(int x, int y)
4960 { // called on right mouse click to load PV
4961 int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
4962 lastX = x; lastY = y;
4963 ParsePV(lastPV[which], FALSE); // load the PV of the thinking engine in the boards array.
4970 if(endPV < 0) return;
4972 currentMove = forwardMostMove;
4973 ClearPremoveHighlights();
4974 DrawPosition(TRUE, boards[currentMove]);
4978 MovePV(int x, int y, int h)
4979 { // step through PV based on mouse coordinates (called on mouse move)
4980 int margin = h>>3, step = 0;
4982 if(endPV < 0) return;
4983 // we must somehow check if right button is still down (might be released off board!)
4984 if(y < margin && (abs(x - lastX) > 6 || abs(y - lastY) > 6)) step = 1; else
4985 if(y > h - margin && (abs(x - lastX) > 6 || abs(y - lastY) > 6)) step = -1; else
4986 if( y > lastY + 6 ) step = -1; else if(y < lastY - 6) step = 1;
4988 lastX = x; lastY = y;
4989 if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
4990 currentMove += step;
4991 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
4992 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
4993 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
4994 DrawPosition(FALSE, boards[currentMove]);
4998 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
4999 // All positions will have equal probability, but the current method will not provide a unique
5000 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5006 int piecesLeft[(int)BlackPawn];
5007 int seed, nrOfShuffles;
5009 void GetPositionNumber()
5010 { // sets global variable seed
5013 seed = appData.defaultFrcPosition;
5014 if(seed < 0) { // randomize based on time for negative FRC position numbers
5015 for(i=0; i<50; i++) seed += random();
5016 seed = random() ^ random() >> 8 ^ random() << 8;
5017 if(seed<0) seed = -seed;
5021 int put(Board board, int pieceType, int rank, int n, int shade)
5022 // put the piece on the (n-1)-th empty squares of the given shade
5026 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5027 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5028 board[rank][i] = (ChessSquare) pieceType;
5029 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5031 piecesLeft[pieceType]--;
5039 void AddOnePiece(Board board, int pieceType, int rank, int shade)
5040 // calculate where the next piece goes, (any empty square), and put it there
5044 i = seed % squaresLeft[shade];
5045 nrOfShuffles *= squaresLeft[shade];
5046 seed /= squaresLeft[shade];
5047 put(board, pieceType, rank, i, shade);
5050 void AddTwoPieces(Board board, int pieceType, int rank)
5051 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5053 int i, n=squaresLeft[ANY], j=n-1, k;
5055 k = n*(n-1)/2; // nr of possibilities, not counting permutations
5056 i = seed % k; // pick one
5059 while(i >= j) i -= j--;
5060 j = n - 1 - j; i += j;
5061 put(board, pieceType, rank, j, ANY);
5062 put(board, pieceType, rank, i, ANY);
5065 void SetUpShuffle(Board board, int number)
5069 GetPositionNumber(); nrOfShuffles = 1;
5071 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5072 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
5073 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5075 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5077 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5078 p = (int) board[0][i];
5079 if(p < (int) BlackPawn) piecesLeft[p] ++;
5080 board[0][i] = EmptySquare;
5083 if(PosFlags(0) & F_ALL_CASTLE_OK) {
5084 // shuffles restricted to allow normal castling put KRR first
5085 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5086 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5087 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5088 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5089 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5090 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5091 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
5092 put(board, WhiteRook, 0, 0, ANY);
5093 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
5096 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
5097 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
5098 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
5099 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
5100 while(piecesLeft[p] >= 2) {
5101 AddOnePiece(board, p, 0, LITE);
5102 AddOnePiece(board, p, 0, DARK);
5104 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
5107 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
5108 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
5109 // but we leave King and Rooks for last, to possibly obey FRC restriction
5110 if(p == (int)WhiteRook) continue;
5111 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
5112 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
5115 // now everything is placed, except perhaps King (Unicorn) and Rooks
5117 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
5118 // Last King gets castling rights
5119 while(piecesLeft[(int)WhiteUnicorn]) {
5120 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5121 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5124 while(piecesLeft[(int)WhiteKing]) {
5125 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5126 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5131 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
5132 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
5135 // Only Rooks can be left; simply place them all
5136 while(piecesLeft[(int)WhiteRook]) {
5137 i = put(board, WhiteRook, 0, 0, ANY);
5138 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
5141 initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
5143 initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
5146 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
5147 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
5150 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
5153 int SetCharTable( char *table, const char * map )
5154 /* [HGM] moved here from winboard.c because of its general usefulness */
5155 /* Basically a safe strcpy that uses the last character as King */
5157 int result = FALSE; int NrPieces;
5159 if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
5160 && NrPieces >= 12 && !(NrPieces&1)) {
5161 int i; /* [HGM] Accept even length from 12 to 34 */
5163 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
5164 for( i=0; i<NrPieces/2-1; i++ ) {
5166 table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
5168 table[(int) WhiteKing] = map[NrPieces/2-1];
5169 table[(int) BlackKing] = map[NrPieces-1];
5177 void Prelude(Board board)
5178 { // [HGM] superchess: random selection of exo-pieces
5179 int i, j, k; ChessSquare p;
5180 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
5182 GetPositionNumber(); // use FRC position number
5184 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
5185 SetCharTable(pieceToChar, appData.pieceToCharTable);
5186 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
5187 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
5190 j = seed%4; seed /= 4;
5191 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5192 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5193 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5194 j = seed%3 + (seed%3 >= j); seed /= 3;
5195 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5196 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5197 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5198 j = seed%3; seed /= 3;
5199 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5200 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5201 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5202 j = seed%2 + (seed%2 >= j); seed /= 2;
5203 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5204 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5205 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5206 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
5207 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
5208 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
5209 put(board, exoPieces[0], 0, 0, ANY);
5210 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
5214 InitPosition(redraw)
5217 ChessSquare (* pieces)[BOARD_FILES];
5218 int i, j, pawnRow, overrule,
5219 oldx = gameInfo.boardWidth,
5220 oldy = gameInfo.boardHeight,
5221 oldh = gameInfo.holdingsWidth,
5222 oldv = gameInfo.variant;
5224 if(appData.icsActive) shuffleOpenings = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
5226 /* [AS] Initialize pv info list [HGM] and game status */
5228 for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
5229 pvInfoList[i].depth = 0;
5230 boards[i][EP_STATUS] = EP_NONE;
5231 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
5234 initialRulePlies = 0; /* 50-move counter start */
5236 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
5237 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
5241 /* [HGM] logic here is completely changed. In stead of full positions */
5242 /* the initialized data only consist of the two backranks. The switch */
5243 /* selects which one we will use, which is than copied to the Board */
5244 /* initialPosition, which for the rest is initialized by Pawns and */
5245 /* empty squares. This initial position is then copied to boards[0], */
5246 /* possibly after shuffling, so that it remains available. */
5248 gameInfo.holdingsWidth = 0; /* default board sizes */
5249 gameInfo.boardWidth = 8;
5250 gameInfo.boardHeight = 8;
5251 gameInfo.holdingsSize = 0;
5252 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
5253 for(i=0; i<BOARD_FILES-2; i++)
5254 initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
5255 initialPosition[EP_STATUS] = EP_NONE;
5256 SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
5257 if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
5258 SetCharTable(pieceNickName, appData.pieceNickNames);
5259 else SetCharTable(pieceNickName, "............");
5261 switch (gameInfo.variant) {
5262 case VariantFischeRandom:
5263 shuffleOpenings = TRUE;
5267 case VariantShatranj:
5268 pieces = ShatranjArray;
5269 nrCastlingRights = 0;
5270 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
5273 pieces = makrukArray;
5274 nrCastlingRights = 0;
5275 startedFromSetupPosition = TRUE;
5276 SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
5278 case VariantTwoKings:
5279 pieces = twoKingsArray;
5281 case VariantCapaRandom:
5282 shuffleOpenings = TRUE;
5283 case VariantCapablanca:
5284 pieces = CapablancaArray;
5285 gameInfo.boardWidth = 10;
5286 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5289 pieces = GothicArray;
5290 gameInfo.boardWidth = 10;
5291 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5294 pieces = JanusArray;
5295 gameInfo.boardWidth = 10;
5296 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
5297 nrCastlingRights = 6;
5298 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5299 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5300 initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
5301 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5302 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5303 initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
5306 pieces = FalconArray;
5307 gameInfo.boardWidth = 10;
5308 SetCharTable(pieceToChar, "PNBRQ.............FKpnbrq.............fk");
5310 case VariantXiangqi:
5311 pieces = XiangqiArray;
5312 gameInfo.boardWidth = 9;
5313 gameInfo.boardHeight = 10;
5314 nrCastlingRights = 0;
5315 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
5318 pieces = ShogiArray;
5319 gameInfo.boardWidth = 9;
5320 gameInfo.boardHeight = 9;
5321 gameInfo.holdingsSize = 7;
5322 nrCastlingRights = 0;
5323 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
5325 case VariantCourier:
5326 pieces = CourierArray;
5327 gameInfo.boardWidth = 12;
5328 nrCastlingRights = 0;
5329 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
5331 case VariantKnightmate:
5332 pieces = KnightmateArray;
5333 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
5336 pieces = fairyArray;
5337 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
5340 pieces = GreatArray;
5341 gameInfo.boardWidth = 10;
5342 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
5343 gameInfo.holdingsSize = 8;
5347 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
5348 gameInfo.holdingsSize = 8;
5349 startedFromSetupPosition = TRUE;
5351 case VariantCrazyhouse:
5352 case VariantBughouse:
5354 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
5355 gameInfo.holdingsSize = 5;
5357 case VariantWildCastle:
5359 /* !!?shuffle with kings guaranteed to be on d or e file */
5360 shuffleOpenings = 1;
5362 case VariantNoCastle:
5364 nrCastlingRights = 0;
5365 /* !!?unconstrained back-rank shuffle */
5366 shuffleOpenings = 1;
5371 if(appData.NrFiles >= 0) {
5372 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
5373 gameInfo.boardWidth = appData.NrFiles;
5375 if(appData.NrRanks >= 0) {
5376 gameInfo.boardHeight = appData.NrRanks;
5378 if(appData.holdingsSize >= 0) {
5379 i = appData.holdingsSize;
5380 if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
5381 gameInfo.holdingsSize = i;
5383 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
5384 if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
5385 DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
5387 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
5388 if(pawnRow < 1) pawnRow = 1;
5389 if(gameInfo.variant == VariantMakruk) pawnRow = 2;
5391 /* User pieceToChar list overrules defaults */
5392 if(appData.pieceToCharTable != NULL)
5393 SetCharTable(pieceToChar, appData.pieceToCharTable);
5395 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
5397 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
5398 s = (ChessSquare) 0; /* account holding counts in guard band */
5399 for( i=0; i<BOARD_HEIGHT; i++ )
5400 initialPosition[i][j] = s;
5402 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
5403 initialPosition[0][j] = pieces[0][j-gameInfo.holdingsWidth];
5404 initialPosition[pawnRow][j] = WhitePawn;
5405 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = BlackPawn;
5406 if(gameInfo.variant == VariantXiangqi) {
5408 initialPosition[pawnRow][j] =
5409 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
5410 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
5411 initialPosition[2][j] = WhiteCannon;
5412 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
5416 initialPosition[BOARD_HEIGHT-1][j] = pieces[1][j-gameInfo.holdingsWidth];
5418 if( (gameInfo.variant == VariantShogi) && !overrule ) {
5421 initialPosition[1][j] = WhiteBishop;
5422 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
5424 initialPosition[1][j] = WhiteRook;
5425 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
5428 if( nrCastlingRights == -1) {
5429 /* [HGM] Build normal castling rights (must be done after board sizing!) */
5430 /* This sets default castling rights from none to normal corners */
5431 /* Variants with other castling rights must set them themselves above */
5432 nrCastlingRights = 6;
5434 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5435 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5436 initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
5437 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5438 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5439 initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
5442 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
5443 if(gameInfo.variant == VariantGreat) { // promotion commoners
5444 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
5445 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
5446 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
5447 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
5449 if (appData.debugMode) {
5450 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
5452 if(shuffleOpenings) {
5453 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
5454 startedFromSetupPosition = TRUE;
5456 if(startedFromPositionFile) {
5457 /* [HGM] loadPos: use PositionFile for every new game */
5458 CopyBoard(initialPosition, filePosition);
5459 for(i=0; i<nrCastlingRights; i++)
5460 initialRights[i] = filePosition[CASTLING][i];
5461 startedFromSetupPosition = TRUE;
5464 CopyBoard(boards[0], initialPosition);
5466 if(oldx != gameInfo.boardWidth ||
5467 oldy != gameInfo.boardHeight ||
5468 oldh != gameInfo.holdingsWidth
5470 || oldv == VariantGothic || // For licensing popups
5471 gameInfo.variant == VariantGothic
5474 || oldv == VariantFalcon ||
5475 gameInfo.variant == VariantFalcon
5478 InitDrawingSizes(-2 ,0);
5481 DrawPosition(TRUE, boards[currentMove]);
5485 SendBoard(cps, moveNum)
5486 ChessProgramState *cps;
5489 char message[MSG_SIZ];
5491 if (cps->useSetboard) {
5492 char* fen = PositionToFEN(moveNum, cps->fenOverride);
5493 sprintf(message, "setboard %s\n", fen);
5494 SendToProgram(message, cps);
5500 /* Kludge to set black to move, avoiding the troublesome and now
5501 * deprecated "black" command.
5503 if (!WhiteOnMove(moveNum)) SendToProgram("a2a3\n", cps);
5505 SendToProgram("edit\n", cps);
5506 SendToProgram("#\n", cps);
5507 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
5508 bp = &boards[moveNum][i][BOARD_LEFT];
5509 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
5510 if ((int) *bp < (int) BlackPawn) {
5511 sprintf(message, "%c%c%c\n", PieceToChar(*bp),
5513 if(message[0] == '+' || message[0] == '~') {
5514 sprintf(message, "%c%c%c+\n",
5515 PieceToChar((ChessSquare)(DEMOTED *bp)),
5518 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
5519 message[1] = BOARD_RGHT - 1 - j + '1';
5520 message[2] = BOARD_HEIGHT - 1 - i + 'a';
5522 SendToProgram(message, cps);
5527 SendToProgram("c\n", cps);
5528 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
5529 bp = &boards[moveNum][i][BOARD_LEFT];
5530 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
5531 if (((int) *bp != (int) EmptySquare)
5532 && ((int) *bp >= (int) BlackPawn)) {
5533 sprintf(message, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
5535 if(message[0] == '+' || message[0] == '~') {
5536 sprintf(message, "%c%c%c+\n",
5537 PieceToChar((ChessSquare)(DEMOTED *bp)),
5540 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
5541 message[1] = BOARD_RGHT - 1 - j + '1';
5542 message[2] = BOARD_HEIGHT - 1 - i + 'a';
5544 SendToProgram(message, cps);
5549 SendToProgram(".\n", cps);
5551 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
5554 static int autoQueen; // [HGM] oneclick
5557 HasPromotionChoice(int fromX, int fromY, int toX, int toY, char *promoChoice)
5559 /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
5560 /* [HGM] add Shogi promotions */
5561 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
5566 if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
5567 if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
5569 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
5570 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
5573 piece = boards[currentMove][fromY][fromX];
5574 if(gameInfo.variant == VariantShogi) {
5575 promotionZoneSize = 3;
5576 highestPromotingPiece = (int)WhiteFerz;
5577 } else if(gameInfo.variant == VariantMakruk) {
5578 promotionZoneSize = 3;
5581 // next weed out all moves that do not touch the promotion zone at all
5582 if((int)piece >= BlackPawn) {
5583 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
5585 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
5587 if( toY < BOARD_HEIGHT - promotionZoneSize &&
5588 fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
5591 if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
5593 // weed out mandatory Shogi promotions
5594 if(gameInfo.variant == VariantShogi) {
5595 if(piece >= BlackPawn) {
5596 if(toY == 0 && piece == BlackPawn ||
5597 toY == 0 && piece == BlackQueen ||
5598 toY <= 1 && piece == BlackKnight) {
5603 if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
5604 toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
5605 toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
5612 // weed out obviously illegal Pawn moves
5613 if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
5614 if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
5615 if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
5616 if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
5617 if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
5618 // note we are not allowed to test for valid (non-)capture, due to premove
5621 // we either have a choice what to promote to, or (in Shogi) whether to promote
5622 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk) {
5623 *promoChoice = PieceToChar(BlackFerz); // no choice
5626 if(autoQueen) { // predetermined
5627 if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantLosers)
5628 *promoChoice = PieceToChar(BlackKing); // in Suicide Q is the last thing we want
5629 else *promoChoice = PieceToChar(BlackQueen);
5633 // suppress promotion popup on illegal moves that are not premoves
5634 premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
5635 gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
5636 if(appData.testLegality && !premove) {
5637 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
5638 fromY, fromX, toY, toX, NULLCHAR);
5639 if(moveType != WhitePromotionQueen && moveType != BlackPromotionQueen &&
5640 moveType != WhitePromotionKnight && moveType != BlackPromotionKnight)
5648 InPalace(row, column)
5650 { /* [HGM] for Xiangqi */
5651 if( (row < 3 || row > BOARD_HEIGHT-4) &&
5652 column < (BOARD_WIDTH + 4)/2 &&
5653 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
5658 PieceForSquare (x, y)
5662 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
5665 return boards[currentMove][y][x];
5669 OKToStartUserMove(x, y)
5672 ChessSquare from_piece;
5675 if (matchMode) return FALSE;
5676 if (gameMode == EditPosition) return TRUE;
5678 if (x >= 0 && y >= 0)
5679 from_piece = boards[currentMove][y][x];
5681 from_piece = EmptySquare;
5683 if (from_piece == EmptySquare) return FALSE;
5685 white_piece = (int)from_piece >= (int)WhitePawn &&
5686 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
5689 case PlayFromGameFile:
5691 case TwoMachinesPlay:
5699 case MachinePlaysWhite:
5700 case IcsPlayingBlack:
5701 if (appData.zippyPlay) return FALSE;
5703 DisplayMoveError(_("You are playing Black"));
5708 case MachinePlaysBlack:
5709 case IcsPlayingWhite:
5710 if (appData.zippyPlay) return FALSE;
5712 DisplayMoveError(_("You are playing White"));
5718 if (!white_piece && WhiteOnMove(currentMove)) {
5719 DisplayMoveError(_("It is White's turn"));
5722 if (white_piece && !WhiteOnMove(currentMove)) {
5723 DisplayMoveError(_("It is Black's turn"));
5726 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
5727 /* Editing correspondence game history */
5728 /* Could disallow this or prompt for confirmation */
5733 case BeginningOfGame:
5734 if (appData.icsActive) return FALSE;
5735 if (!appData.noChessProgram) {
5737 DisplayMoveError(_("You are playing White"));
5744 if (!white_piece && WhiteOnMove(currentMove)) {
5745 DisplayMoveError(_("It is White's turn"));
5748 if (white_piece && !WhiteOnMove(currentMove)) {
5749 DisplayMoveError(_("It is Black's turn"));
5758 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
5759 && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
5760 && gameMode != AnalyzeFile && gameMode != Training) {
5761 DisplayMoveError(_("Displayed position is not current"));
5768 OnlyMove(int *x, int *y, Boolean captures) {
5769 DisambiguateClosure cl;
5770 if (appData.zippyPlay) return FALSE;
5772 case MachinePlaysBlack:
5773 case IcsPlayingWhite:
5774 case BeginningOfGame:
5775 if(!WhiteOnMove(currentMove)) return FALSE;
5777 case MachinePlaysWhite:
5778 case IcsPlayingBlack:
5779 if(WhiteOnMove(currentMove)) return FALSE;
5784 cl.pieceIn = EmptySquare;
5789 cl.promoCharIn = NULLCHAR;
5790 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
5791 if( cl.kind == NormalMove ||
5792 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
5793 cl.kind == WhitePromotionQueen || cl.kind == BlackPromotionQueen ||
5794 cl.kind == WhitePromotionKnight || cl.kind == BlackPromotionKnight ||
5795 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
5802 if(cl.kind != ImpossibleMove) return FALSE;
5803 cl.pieceIn = EmptySquare;
5808 cl.promoCharIn = NULLCHAR;
5809 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
5810 if( cl.kind == NormalMove ||
5811 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
5812 cl.kind == WhitePromotionQueen || cl.kind == BlackPromotionQueen ||
5813 cl.kind == WhitePromotionKnight || cl.kind == BlackPromotionKnight ||
5814 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
5819 autoQueen = TRUE; // act as if autoQueen on when we click to-square
5825 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
5826 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
5827 int lastLoadGameUseList = FALSE;
5828 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
5829 ChessMove lastLoadGameStart = (ChessMove) 0;
5832 UserMoveTest(fromX, fromY, toX, toY, promoChar, captureOwn)
5833 int fromX, fromY, toX, toY;
5838 ChessSquare pdown, pup;
5840 /* Check if the user is playing in turn. This is complicated because we
5841 let the user "pick up" a piece before it is his turn. So the piece he
5842 tried to pick up may have been captured by the time he puts it down!
5843 Therefore we use the color the user is supposed to be playing in this
5844 test, not the color of the piece that is currently on the starting
5845 square---except in EditGame mode, where the user is playing both
5846 sides; fortunately there the capture race can't happen. (It can
5847 now happen in IcsExamining mode, but that's just too bad. The user
5848 will get a somewhat confusing message in that case.)
5852 case PlayFromGameFile:
5854 case TwoMachinesPlay:
5858 /* We switched into a game mode where moves are not accepted,
5859 perhaps while the mouse button was down. */
5860 return ImpossibleMove;
5862 case MachinePlaysWhite:
5863 /* User is moving for Black */
5864 if (WhiteOnMove(currentMove)) {
5865 DisplayMoveError(_("It is White's turn"));
5866 return ImpossibleMove;
5870 case MachinePlaysBlack:
5871 /* User is moving for White */
5872 if (!WhiteOnMove(currentMove)) {
5873 DisplayMoveError(_("It is Black's turn"));
5874 return ImpossibleMove;
5880 case BeginningOfGame:
5883 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
5884 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
5885 /* User is moving for Black */
5886 if (WhiteOnMove(currentMove)) {
5887 DisplayMoveError(_("It is White's turn"));
5888 return ImpossibleMove;
5891 /* User is moving for White */
5892 if (!WhiteOnMove(currentMove)) {
5893 DisplayMoveError(_("It is Black's turn"));
5894 return ImpossibleMove;
5899 case IcsPlayingBlack:
5900 /* User is moving for Black */
5901 if (WhiteOnMove(currentMove)) {
5902 if (!appData.premove) {
5903 DisplayMoveError(_("It is White's turn"));
5904 } else if (toX >= 0 && toY >= 0) {
5907 premoveFromX = fromX;
5908 premoveFromY = fromY;
5909 premovePromoChar = promoChar;
5911 if (appData.debugMode)
5912 fprintf(debugFP, "Got premove: fromX %d,"
5913 "fromY %d, toX %d, toY %d\n",
5914 fromX, fromY, toX, toY);
5916 return ImpossibleMove;
5920 case IcsPlayingWhite:
5921 /* User is moving for White */
5922 if (!WhiteOnMove(currentMove)) {
5923 if (!appData.premove) {
5924 DisplayMoveError(_("It is Black's turn"));
5925 } else if (toX >= 0 && toY >= 0) {
5928 premoveFromX = fromX;
5929 premoveFromY = fromY;
5930 premovePromoChar = promoChar;
5932 if (appData.debugMode)
5933 fprintf(debugFP, "Got premove: fromX %d,"
5934 "fromY %d, toX %d, toY %d\n",
5935 fromX, fromY, toX, toY);
5937 return ImpossibleMove;
5945 /* EditPosition, empty square, or different color piece;
5946 click-click move is possible */
5947 if (toX == -2 || toY == -2) {
5948 boards[0][fromY][fromX] = EmptySquare;
5949 return AmbiguousMove;
5950 } else if (toX >= 0 && toY >= 0) {
5951 boards[0][toY][toX] = boards[0][fromY][fromX];
5952 if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
5953 if(boards[0][fromY][0] != EmptySquare) {
5954 if(boards[0][fromY][1]) boards[0][fromY][1]--;
5955 if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
5958 if(fromX == BOARD_RGHT+1) {
5959 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
5960 if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
5961 if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
5964 boards[0][fromY][fromX] = EmptySquare;
5965 return AmbiguousMove;
5967 return ImpossibleMove;
5970 if(toX < 0 || toY < 0) return ImpossibleMove;
5971 pdown = boards[currentMove][fromY][fromX];
5972 pup = boards[currentMove][toY][toX];
5974 /* [HGM] If move started in holdings, it means a drop */
5975 if( fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) {
5976 if( pup != EmptySquare ) return ImpossibleMove;
5977 if(appData.testLegality) {
5978 /* it would be more logical if LegalityTest() also figured out
5979 * which drops are legal. For now we forbid pawns on back rank.
5980 * Shogi is on its own here...
5982 if( (pdown == WhitePawn || pdown == BlackPawn) &&
5983 (toY == 0 || toY == BOARD_HEIGHT -1 ) )
5984 return(ImpossibleMove); /* no pawn drops on 1st/8th */
5986 return WhiteDrop; /* Not needed to specify white or black yet */
5989 /* [HGM] always test for legality, to get promotion info */
5990 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
5991 fromY, fromX, toY, toX, promoChar);
5992 /* [HGM] but possibly ignore an IllegalMove result */
5993 if (appData.testLegality) {
5994 if (moveType == IllegalMove || moveType == ImpossibleMove) {
5995 DisplayMoveError(_("Illegal move"));
5996 return ImpossibleMove;
6001 /* [HGM] <popupFix> in stead of calling FinishMove directly, this
6002 function is made into one that returns an OK move type if FinishMove
6003 should be called. This to give the calling driver routine the
6004 opportunity to finish the userMove input with a promotion popup,
6005 without bothering the user with this for invalid or illegal moves */
6007 /* FinishMove(moveType, fromX, fromY, toX, toY, promoChar); */
6010 /* Common tail of UserMoveEvent and DropMenuEvent */
6012 FinishMove(moveType, fromX, fromY, toX, toY, promoChar)
6014 int fromX, fromY, toX, toY;
6015 /*char*/int promoChar;
6019 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) && promoChar != NULLCHAR) {
6020 // [HGM] superchess: suppress promotions to non-available piece
6021 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
6022 if(WhiteOnMove(currentMove)) {
6023 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
6025 if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
6029 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
6030 move type in caller when we know the move is a legal promotion */
6031 if(moveType == NormalMove && promoChar)
6032 moveType = PromoCharToMoveType(WhiteOnMove(currentMove), promoChar);
6034 /* [HGM] convert drag-and-drop piece drops to standard form */
6035 if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ){
6036 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
6037 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
6038 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
6039 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
6040 if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
6041 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
6042 while(PieceToChar(fromX) == '.' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
6046 /* [HGM] <popupFix> The following if has been moved here from
6047 UserMoveEvent(). Because it seemed to belong here (why not allow
6048 piece drops in training games?), and because it can only be
6049 performed after it is known to what we promote. */
6050 if (gameMode == Training) {
6051 /* compare the move played on the board to the next move in the
6052 * game. If they match, display the move and the opponent's response.
6053 * If they don't match, display an error message.
6057 CopyBoard(testBoard, boards[currentMove]);
6058 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
6060 if (CompareBoards(testBoard, boards[currentMove+1])) {
6061 ForwardInner(currentMove+1);
6063 /* Autoplay the opponent's response.
6064 * if appData.animate was TRUE when Training mode was entered,
6065 * the response will be animated.
6067 saveAnimate = appData.animate;
6068 appData.animate = animateTraining;
6069 ForwardInner(currentMove+1);
6070 appData.animate = saveAnimate;
6072 /* check for the end of the game */
6073 if (currentMove >= forwardMostMove) {
6074 gameMode = PlayFromGameFile;
6076 SetTrainingModeOff();
6077 DisplayInformation(_("End of game"));
6080 DisplayError(_("Incorrect move"), 0);
6085 /* Ok, now we know that the move is good, so we can kill
6086 the previous line in Analysis Mode */
6087 if ((gameMode == AnalyzeMode || gameMode == EditGame)
6088 && currentMove < forwardMostMove) {
6089 PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
6092 /* If we need the chess program but it's dead, restart it */
6093 ResurrectChessProgram();
6095 /* A user move restarts a paused game*/
6099 thinkOutput[0] = NULLCHAR;
6101 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
6103 if(Adjudicate(NULL)) return 1; // [HGM] adjudicate: take care of automtic game end
6105 if (gameMode == BeginningOfGame) {
6106 if (appData.noChessProgram) {
6107 gameMode = EditGame;
6111 gameMode = MachinePlaysBlack;
6114 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
6116 if (first.sendName) {
6117 sprintf(buf, "name %s\n", gameInfo.white);
6118 SendToProgram(buf, &first);
6125 /* Relay move to ICS or chess engine */
6126 if (appData.icsActive) {
6127 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
6128 gameMode == IcsExamining) {
6129 if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
6130 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
6132 SendMoveToICS(moveType, fromX, fromY, toX, toY);
6134 // also send plain move, in case ICS does not understand atomic claims
6135 SendMoveToICS(moveType, fromX, fromY, toX, toY);
6139 if (first.sendTime && (gameMode == BeginningOfGame ||
6140 gameMode == MachinePlaysWhite ||
6141 gameMode == MachinePlaysBlack)) {
6142 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
6144 if (gameMode != EditGame && gameMode != PlayFromGameFile) {
6145 // [HGM] book: if program might be playing, let it use book
6146 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
6147 first.maybeThinking = TRUE;
6148 } else SendMoveToProgram(forwardMostMove-1, &first);
6149 if (currentMove == cmailOldMove + 1) {
6150 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
6154 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6158 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
6164 if (WhiteOnMove(currentMove)) {
6165 GameEnds(BlackWins, "Black mates", GE_PLAYER);
6167 GameEnds(WhiteWins, "White mates", GE_PLAYER);
6171 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
6176 case MachinePlaysBlack:
6177 case MachinePlaysWhite:
6178 /* disable certain menu options while machine is thinking */
6179 SetMachineThinkingEnables();
6186 userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
6188 if(bookHit) { // [HGM] book: simulate book reply
6189 static char bookMove[MSG_SIZ]; // a bit generous?
6191 programStats.nodes = programStats.depth = programStats.time =
6192 programStats.score = programStats.got_only_move = 0;
6193 sprintf(programStats.movelist, "%s (xbook)", bookHit);
6195 strcpy(bookMove, "move ");
6196 strcat(bookMove, bookHit);
6197 HandleMachineMove(bookMove, &first);
6203 UserMoveEvent(fromX, fromY, toX, toY, promoChar)
6204 int fromX, fromY, toX, toY;
6207 /* [HGM] This routine was added to allow calling of its two logical
6208 parts from other modules in the old way. Before, UserMoveEvent()
6209 automatically called FinishMove() if the move was OK, and returned
6210 otherwise. I separated the two, in order to make it possible to
6211 slip a promotion popup in between. But that it always needs two
6212 calls, to the first part, (now called UserMoveTest() ), and to
6213 FinishMove if the first part succeeded. Calls that do not need
6214 to do anything in between, can call this routine the old way.
6216 ChessMove moveType = UserMoveTest(fromX, fromY, toX, toY, promoChar, FALSE);
6217 if(appData.debugMode) fprintf(debugFP, "moveType 4 = %d, promochar = %x\n", moveType, promoChar);
6218 if(moveType == AmbiguousMove)
6219 DrawPosition(FALSE, boards[currentMove]);
6220 else if(moveType != ImpossibleMove && moveType != Comment)
6221 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
6225 Mark(board, flags, kind, rf, ff, rt, ft, closure)
6232 typedef char Markers[BOARD_RANKS][BOARD_FILES];
6233 Markers *m = (Markers *) closure;
6234 if(rf == fromY && ff == fromX)
6235 (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
6236 || kind == WhiteCapturesEnPassant
6237 || kind == BlackCapturesEnPassant);
6238 else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3;
6242 MarkTargetSquares(int clear)
6245 if(!appData.markers || !appData.highlightDragging ||
6246 !appData.testLegality || gameMode == EditPosition) return;
6248 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) marker[y][x] = 0;
6251 GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker);
6252 if(PosFlags(0) & F_MANDATORY_CAPTURE) {
6253 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
6255 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
6258 DrawPosition(TRUE, NULL);
6261 void LeftClick(ClickType clickType, int xPix, int yPix)
6264 Boolean saveAnimate;
6265 static int second = 0, promotionChoice = 0, dragging = 0;
6266 char promoChoice = NULLCHAR;
6268 if(appData.seekGraph && appData.icsActive && loggedOn &&
6269 (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
6270 SeekGraphClick(clickType, xPix, yPix, 0);
6274 if (clickType == Press) ErrorPopDown();
6275 MarkTargetSquares(1);
6277 x = EventToSquare(xPix, BOARD_WIDTH);
6278 y = EventToSquare(yPix, BOARD_HEIGHT);
6279 if (!flipView && y >= 0) {
6280 y = BOARD_HEIGHT - 1 - y;
6282 if (flipView && x >= 0) {
6283 x = BOARD_WIDTH - 1 - x;
6286 if(promotionChoice) { // we are waiting for a click to indicate promotion piece
6287 if(clickType == Release) return; // ignore upclick of click-click destination
6288 promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
6289 if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
6290 if(gameInfo.holdingsWidth &&
6291 (WhiteOnMove(currentMove)
6292 ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y > 0
6293 : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT-1) ) {
6294 // click in right holdings, for determining promotion piece
6295 ChessSquare p = boards[currentMove][y][x];
6296 if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
6297 if(p != EmptySquare) {
6298 FinishMove(NormalMove, fromX, fromY, toX, toY, ToLower(PieceToChar(p)));
6303 DrawPosition(FALSE, boards[currentMove]);
6307 /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
6308 if(clickType == Press
6309 && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
6310 || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
6311 || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
6314 autoQueen = appData.alwaysPromoteToQueen;
6317 if(!appData.oneClick || !OnlyMove(&x, &y, FALSE)) {
6318 if (clickType == Press) {
6320 if (OKToStartUserMove(x, y)) {
6324 MarkTargetSquares(0);
6325 DragPieceBegin(xPix, yPix); dragging = 1;
6326 if (appData.highlightDragging) {
6327 SetHighlights(x, y, -1, -1);
6330 } else if(dragging) { // [HGM] from-square must have been reset due to game end since last press
6331 DragPieceEnd(xPix, yPix); dragging = 0;
6332 DrawPosition(FALSE, NULL);
6339 if (clickType == Press && gameMode != EditPosition) {
6344 // ignore off-board to clicks
6345 if(y < 0 || x < 0) return;
6347 /* Check if clicking again on the same color piece */
6348 fromP = boards[currentMove][fromY][fromX];
6349 toP = boards[currentMove][y][x];
6350 frc = gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom;
6351 if ((WhitePawn <= fromP && fromP <= WhiteKing &&
6352 WhitePawn <= toP && toP <= WhiteKing &&
6353 !(fromP == WhiteKing && toP == WhiteRook && frc) &&
6354 !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
6355 (BlackPawn <= fromP && fromP <= BlackKing &&
6356 BlackPawn <= toP && toP <= BlackKing &&
6357 !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
6358 !(fromP == BlackKing && toP == BlackRook && frc))) {
6359 /* Clicked again on same color piece -- changed his mind */
6360 second = (x == fromX && y == fromY);
6361 if(!second || appData.oneClick && !OnlyMove(&x, &y, TRUE)) {
6362 if (appData.highlightDragging) {
6363 SetHighlights(x, y, -1, -1);
6367 if (OKToStartUserMove(x, y)) {
6369 fromY = y; dragging = 1;
6370 MarkTargetSquares(0);
6371 DragPieceBegin(xPix, yPix);
6376 // ignore clicks on holdings
6377 if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
6380 if (clickType == Release && x == fromX && y == fromY) {
6381 DragPieceEnd(xPix, yPix); dragging = 0;
6382 if (appData.animateDragging) {
6383 /* Undo animation damage if any */
6384 DrawPosition(FALSE, NULL);
6387 /* Second up/down in same square; just abort move */
6392 ClearPremoveHighlights();
6394 /* First upclick in same square; start click-click mode */
6395 SetHighlights(x, y, -1, -1);
6400 /* we now have a different from- and (possibly off-board) to-square */
6401 /* Completed move */
6404 saveAnimate = appData.animate;
6405 if (clickType == Press) {
6406 /* Finish clickclick move */
6407 if (appData.animate || appData.highlightLastMove) {
6408 SetHighlights(fromX, fromY, toX, toY);
6413 /* Finish drag move */
6414 if (appData.highlightLastMove) {
6415 SetHighlights(fromX, fromY, toX, toY);
6419 DragPieceEnd(xPix, yPix); dragging = 0;
6420 /* Don't animate move and drag both */
6421 appData.animate = FALSE;
6424 // moves into holding are invalid for now (except in EditPosition, adapting to-square)
6425 if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
6426 ChessSquare piece = boards[currentMove][fromY][fromX];
6427 if(gameMode == EditPosition && piece != EmptySquare &&
6428 fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
6431 if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
6432 n = PieceToNumber(piece - (int)BlackPawn);
6433 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
6434 boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
6435 boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
6437 if(x == BOARD_RGHT+1 && piece < BlackPawn) {
6438 n = PieceToNumber(piece);
6439 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
6440 boards[currentMove][n][BOARD_WIDTH-1] = piece;
6441 boards[currentMove][n][BOARD_WIDTH-2]++;
6443 boards[currentMove][fromY][fromX] = EmptySquare;
6447 DrawPosition(TRUE, boards[currentMove]);
6451 // off-board moves should not be highlighted
6452 if(x < 0 || x < 0) ClearHighlights();
6454 if (HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice)) {
6455 SetHighlights(fromX, fromY, toX, toY);
6456 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
6457 // [HGM] super: promotion to captured piece selected from holdings
6458 ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
6459 promotionChoice = TRUE;
6460 // kludge follows to temporarily execute move on display, without promoting yet
6461 boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
6462 boards[currentMove][toY][toX] = p;
6463 DrawPosition(FALSE, boards[currentMove]);
6464 boards[currentMove][fromY][fromX] = p; // take back, but display stays
6465 boards[currentMove][toY][toX] = q;
6466 DisplayMessage("Click in holdings to choose piece", "");
6471 UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
6472 if (!appData.highlightLastMove || gotPremove) ClearHighlights();
6473 if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
6476 appData.animate = saveAnimate;
6477 if (appData.animate || appData.animateDragging) {
6478 /* Undo animation damage if needed */
6479 DrawPosition(FALSE, NULL);
6483 int RightClick(ClickType action, int x, int y, int *fromX, int *fromY)
6484 { // front-end-free part taken out of PieceMenuPopup
6485 int whichMenu; int xSqr, ySqr;
6487 if(seekGraphUp) { // [HGM] seekgraph
6488 if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
6489 if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
6493 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
6494 && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
6495 if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
6496 if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
6497 if(action == Press) {
6498 originalFlip = flipView;
6499 flipView = !flipView; // temporarily flip board to see game from partners perspective
6500 DrawPosition(TRUE, partnerBoard);
6501 DisplayMessage(partnerStatus, "");
6503 } else if(action == Release) {
6504 flipView = originalFlip;
6505 DrawPosition(TRUE, boards[currentMove]);
6511 xSqr = EventToSquare(x, BOARD_WIDTH);
6512 ySqr = EventToSquare(y, BOARD_HEIGHT);
6513 if (action == Release) UnLoadPV(); // [HGM] pv
6514 if (action != Press) return -2; // return code to be ignored
6517 if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
\r
6519 if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
\r
6520 if (xSqr < 0 || ySqr < 0) return -1;
\r
6521 whichMenu = 0; // edit-position menu
6524 if(!appData.icsEngineAnalyze) return -1;
6525 case IcsPlayingWhite:
6526 case IcsPlayingBlack:
6527 if(!appData.zippyPlay) goto noZip;
6530 case MachinePlaysWhite:
6531 case MachinePlaysBlack:
6532 case TwoMachinesPlay: // [HGM] pv: use for showing PV
6533 if (!appData.dropMenu) {
6535 return 2; // flag front-end to grab mouse events
6537 if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
6538 gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
6541 if (xSqr < 0 || ySqr < 0) return -1;
6542 if (!appData.dropMenu || appData.testLegality &&
6543 gameInfo.variant != VariantBughouse &&
6544 gameInfo.variant != VariantCrazyhouse) return -1;
6545 whichMenu = 1; // drop menu
6551 if (((*fromX = xSqr) < 0) ||
6552 ((*fromY = ySqr) < 0)) {
6553 *fromX = *fromY = -1;
6557 *fromX = BOARD_WIDTH - 1 - *fromX;
6559 *fromY = BOARD_HEIGHT - 1 - *fromY;
6564 void SendProgramStatsToFrontend( ChessProgramState * cps, ChessProgramStats * cpstats )
6566 // char * hint = lastHint;
6567 FrontEndProgramStats stats;
6569 stats.which = cps == &first ? 0 : 1;
6570 stats.depth = cpstats->depth;
6571 stats.nodes = cpstats->nodes;
6572 stats.score = cpstats->score;
6573 stats.time = cpstats->time;
6574 stats.pv = cpstats->movelist;
6575 stats.hint = lastHint;
6576 stats.an_move_index = 0;
6577 stats.an_move_count = 0;
6579 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
6580 stats.hint = cpstats->move_name;
6581 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
6582 stats.an_move_count = cpstats->nr_moves;
6585 if(stats.pv && stats.pv[0]) strcpy(lastPV[stats.which], stats.pv); // [HGM] pv: remember last PV of each
6587 SetProgramStats( &stats );
6591 Count(Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
6592 { // count all piece types
6594 *nB = *nW = *wStale = *bStale = *bishopColor = 0;
6595 for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
6596 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
6598 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
6599 if(p == BlackPawn && r == 0) (*bStale)++; else pCnt[p]++; // count last-Rank Pawns (XQ) separately
6600 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
6601 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
6602 p == BlackBishop || p == BlackFerz || p == BlackAlfil )
6603 *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
6608 MatingPotential(int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
6610 VariantClass v = gameInfo.variant;
6612 if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
6613 if(v == VariantShatranj) return TRUE; // always winnable through baring
6614 if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
6615 if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
6617 if(v == VariantXiangqi) {
6618 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
6620 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
6621 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
6622 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
6623 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
6624 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
6625 if(stale) // we have at least one last-rank P plus perhaps C
6626 return majors // KPKX
6627 || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
6629 return pCnt[WhiteFerz+side] // KCAK
6630 || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
6631 || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
6632 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
6634 } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
6635 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
6637 if(nMine == 1) return FALSE; // bare King
6638 if(nBishops && bisColor == 3) return TRUE; // There must be a second B/A/F, which can either block (his) or attack (mine) the escape square
6639 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
6640 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
6641 // by now we have King + 1 piece (or multiple Bishops on the same color)
6642 if(pCnt[WhiteKnight+side])
6643 return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
6644 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
6645 || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
6647 return (pCnt[BlackKnight-side]); // KBKN, KFKN
6648 if(pCnt[WhiteAlfil+side])
6649 return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
6650 if(pCnt[WhiteWazir+side])
6651 return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
6658 Adjudicate(ChessProgramState *cps)
6659 { // [HGM] some adjudications useful with buggy engines
6660 // [HGM] adjudicate: made into separate routine, which now can be called after every move
6661 // In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
6662 // Actually ending the game is now based on the additional internal condition canAdjudicate.
6663 // Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
6664 int k, count = 0; static int bare = 1;
6665 ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
6666 Boolean canAdjudicate = !appData.icsActive;
6668 // most tests only when we understand the game, i.e. legality-checking on, and (for the time being) no piece drops
6669 if(gameInfo.holdingsSize == 0 || gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
6670 if( appData.testLegality )
6671 { /* [HGM] Some more adjudications for obstinate engines */
6672 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+1], i;
6673 static int moveCount = 6;
6675 char *reason = NULL;
6677 /* Count what is on board. */
6678 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
6680 /* Some material-based adjudications that have to be made before stalemate test */
6681 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
6682 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
6683 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
6684 if(canAdjudicate && appData.checkMates) {
6686 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
6687 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6688 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
6689 "Xboard adjudication: King destroyed", GE_XBOARD );
6694 /* Bare King in Shatranj (loses) or Losers (wins) */
6695 if( nrW == 1 || nrB == 1) {
6696 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
6697 boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
6698 if(canAdjudicate && appData.checkMates) {
6700 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
6701 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6702 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
6703 "Xboard adjudication: Bare king", GE_XBOARD );
6707 if( gameInfo.variant == VariantShatranj && --bare < 0)
6709 boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
6710 if(canAdjudicate && appData.checkMates) {
6711 /* but only adjudicate if adjudication enabled */
6713 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
6714 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6715 GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
6716 "Xboard adjudication: Bare king", GE_XBOARD );
6723 // don't wait for engine to announce game end if we can judge ourselves
6724 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
6726 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
6727 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
6728 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
6729 if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
6732 reason = "Xboard adjudication: 3rd check";
6733 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
6743 reason = "Xboard adjudication: Stalemate";
6744 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
6745 boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
6746 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
6747 boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
6748 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
6749 boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
6750 ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
6751 EP_CHECKMATE : EP_WINS);
6752 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi)
6753 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
6757 reason = "Xboard adjudication: Checkmate";
6758 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
6762 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
6764 result = GameIsDrawn; break;
6766 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
6768 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
6770 result = (ChessMove) 0;
6772 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
6774 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
6775 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6776 GameEnds( result, reason, GE_XBOARD );
6780 /* Next absolutely insufficient mating material. */
6781 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
6782 !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
6783 { /* includes KBK, KNK, KK of KBKB with like Bishops */
6785 /* always flag draws, for judging claims */
6786 boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
6788 if(canAdjudicate && appData.materialDraws) {
6789 /* but only adjudicate them if adjudication enabled */
6790 if(engineOpponent) {
6791 SendToProgram("force\n", engineOpponent); // suppress reply
6792 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
6794 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6795 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
6800 /* Then some trivial draws (only adjudicate, cannot be claimed) */
6801 if(nrW + nrB == 4 &&
6802 ( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
6803 || nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
6804 || nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
6805 || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
6807 if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
6808 { /* if the first 3 moves do not show a tactical win, declare draw */
6809 if(engineOpponent) {
6810 SendToProgram("force\n", engineOpponent); // suppress reply
6811 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
6813 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6814 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
6817 } else moveCount = 6;
6821 if (appData.debugMode) { int i;
6822 fprintf(debugFP, "repeat test fmm=%d bmm=%d ep=%d, reps=%d\n",
6823 forwardMostMove, backwardMostMove, boards[backwardMostMove][EP_STATUS],
6824 appData.drawRepeats);
6825 for( i=forwardMostMove; i>=backwardMostMove; i-- )
6826 fprintf(debugFP, "%d ep=%d\n", i, (signed char)boards[i][EP_STATUS]);
6830 // Repetition draws and 50-move rule can be applied independently of legality testing
6832 /* Check for rep-draws */
6834 for(k = forwardMostMove-2;
6835 k>=backwardMostMove && k>=forwardMostMove-100 &&
6836 (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
6837 (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE;
6840 if(CompareBoards(boards[k], boards[forwardMostMove])) {
6841 /* compare castling rights */
6842 if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
6843 (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
6844 rights++; /* King lost rights, while rook still had them */
6845 if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
6846 if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
6847 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
6848 rights++; /* but at least one rook lost them */
6850 if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
6851 (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
6853 if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
6854 if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
6855 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
6858 if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
6859 && appData.drawRepeats > 1) {
6860 /* adjudicate after user-specified nr of repeats */
6861 int result = GameIsDrawn;
6862 char *details = "XBoard adjudication: repetition draw";
6863 if(gameInfo.variant == VariantXiangqi && appData.testLegality) {
6864 // [HGM] xiangqi: check for forbidden perpetuals
6865 int m, ourPerpetual = 1, hisPerpetual = 1;
6866 for(m=forwardMostMove; m>k; m-=2) {
6867 if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
6868 ourPerpetual = 0; // the current mover did not always check
6869 if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
6870 hisPerpetual = 0; // the opponent did not always check
6872 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
6873 ourPerpetual, hisPerpetual);
6874 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
6875 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
6876 details = "Xboard adjudication: perpetual checking";
6878 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
6879 break; // (or we would have caught him before). Abort repetition-checking loop.
6881 // Now check for perpetual chases
6882 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
6883 hisPerpetual = PerpetualChase(k, forwardMostMove);
6884 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
6885 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
6886 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
6887 details = "Xboard adjudication: perpetual chasing";
6889 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
6890 break; // Abort repetition-checking loop.
6892 // if neither of us is checking or chasing all the time, or both are, it is draw
6894 if(engineOpponent) {
6895 SendToProgram("force\n", engineOpponent); // suppress reply
6896 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
6898 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6899 GameEnds( result, details, GE_XBOARD );
6902 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
6903 boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
6907 /* Now we test for 50-move draws. Determine ply count */
6908 count = forwardMostMove;
6909 /* look for last irreversble move */
6910 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
6912 /* if we hit starting position, add initial plies */
6913 if( count == backwardMostMove )
6914 count -= initialRulePlies;
6915 count = forwardMostMove - count;
6916 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
6917 // adjust reversible move counter for checks in Xiangqi
6918 int i = forwardMostMove - count, inCheck = 0, lastCheck;
6919 if(i < backwardMostMove) i = backwardMostMove;
6920 while(i <= forwardMostMove) {
6921 lastCheck = inCheck; // check evasion does not count
6922 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
6923 if(inCheck || lastCheck) count--; // check does not count
6928 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
6929 /* this is used to judge if draw claims are legal */
6930 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
6931 if(engineOpponent) {
6932 SendToProgram("force\n", engineOpponent); // suppress reply
6933 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
6935 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6936 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
6940 /* if draw offer is pending, treat it as a draw claim
6941 * when draw condition present, to allow engines a way to
6942 * claim draws before making their move to avoid a race
6943 * condition occurring after their move
6945 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
6947 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
6948 p = "Draw claim: 50-move rule";
6949 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
6950 p = "Draw claim: 3-fold repetition";
6951 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
6952 p = "Draw claim: insufficient mating material";
6953 if( p != NULL && canAdjudicate) {
6954 if(engineOpponent) {
6955 SendToProgram("force\n", engineOpponent); // suppress reply
6956 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
6958 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6959 GameEnds( GameIsDrawn, p, GE_XBOARD );
6964 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
6965 if(engineOpponent) {
6966 SendToProgram("force\n", engineOpponent); // suppress reply
6967 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
6969 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6970 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
6976 char *SendMoveToBookUser(int moveNr, ChessProgramState *cps, int initial)
6977 { // [HGM] book: this routine intercepts moves to simulate book replies
6978 char *bookHit = NULL;
6980 //first determine if the incoming move brings opponent into his book
6981 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
6982 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
6983 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
6984 if(bookHit != NULL && !cps->bookSuspend) {
6985 // make sure opponent is not going to reply after receiving move to book position
6986 SendToProgram("force\n", cps);
6987 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
6989 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
6990 // now arrange restart after book miss
6992 // after a book hit we never send 'go', and the code after the call to this routine
6993 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
6995 sprintf(buf, "%s%s\n", (cps->useUsermove ? "usermove " : ""), bookHit); // force book move into program supposed to play it
6996 SendToProgram(buf, cps);
6997 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
6998 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
6999 SendToProgram("go\n", cps);
7000 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
7001 } else { // 'go' might be sent based on 'firstMove' after this routine returns
7002 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
7003 SendToProgram("go\n", cps);
7004 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
7006 return bookHit; // notify caller of hit, so it can take action to send move to opponent
7010 ChessProgramState *savedState;
7011 void DeferredBookMove(void)
7013 if(savedState->lastPing != savedState->lastPong)
7014 ScheduleDelayedEvent(DeferredBookMove, 10);
7016 HandleMachineMove(savedMessage, savedState);
7020 HandleMachineMove(message, cps)
7022 ChessProgramState *cps;
7024 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
7025 char realname[MSG_SIZ];
7026 int fromX, fromY, toX, toY;
7035 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
7037 * Kludge to ignore BEL characters
7039 while (*message == '\007') message++;
7042 * [HGM] engine debug message: ignore lines starting with '#' character
7044 if(cps->debug && *message == '#') return;
7047 * Look for book output
7049 if (cps == &first && bookRequested) {
7050 if (message[0] == '\t' || message[0] == ' ') {
7051 /* Part of the book output is here; append it */
7052 strcat(bookOutput, message);
7053 strcat(bookOutput, " \n");
7055 } else if (bookOutput[0] != NULLCHAR) {
7056 /* All of book output has arrived; display it */
7057 char *p = bookOutput;
7058 while (*p != NULLCHAR) {
7059 if (*p == '\t') *p = ' ';
7062 DisplayInformation(bookOutput);
7063 bookRequested = FALSE;
7064 /* Fall through to parse the current output */
7069 * Look for machine move.
7071 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
7072 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
7074 /* This method is only useful on engines that support ping */
7075 if (cps->lastPing != cps->lastPong) {
7076 if (gameMode == BeginningOfGame) {
7077 /* Extra move from before last new; ignore */
7078 if (appData.debugMode) {
7079 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7082 if (appData.debugMode) {
7083 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7084 cps->which, gameMode);
7087 SendToProgram("undo\n", cps);
7093 case BeginningOfGame:
7094 /* Extra move from before last reset; ignore */
7095 if (appData.debugMode) {
7096 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7103 /* Extra move after we tried to stop. The mode test is
7104 not a reliable way of detecting this problem, but it's
7105 the best we can do on engines that don't support ping.
7107 if (appData.debugMode) {
7108 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7109 cps->which, gameMode);
7111 SendToProgram("undo\n", cps);
7114 case MachinePlaysWhite:
7115 case IcsPlayingWhite:
7116 machineWhite = TRUE;
7119 case MachinePlaysBlack:
7120 case IcsPlayingBlack:
7121 machineWhite = FALSE;
7124 case TwoMachinesPlay:
7125 machineWhite = (cps->twoMachinesColor[0] == 'w');
7128 if (WhiteOnMove(forwardMostMove) != machineWhite) {
7129 if (appData.debugMode) {
7131 "Ignoring move out of turn by %s, gameMode %d"
7132 ", forwardMost %d\n",
7133 cps->which, gameMode, forwardMostMove);
7138 if (appData.debugMode) { int f = forwardMostMove;
7139 fprintf(debugFP, "machine move %d, castling = %d %d %d %d %d %d\n", f,
7140 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
7141 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
7143 if(cps->alphaRank) AlphaRank(machineMove, 4);
7144 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
7145 &fromX, &fromY, &toX, &toY, &promoChar)) {
7146 /* Machine move could not be parsed; ignore it. */
7147 sprintf(buf1, _("Illegal move \"%s\" from %s machine"),
7148 machineMove, cps->which);
7149 DisplayError(buf1, 0);
7150 sprintf(buf1, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
7151 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType);
7152 if (gameMode == TwoMachinesPlay) {
7153 GameEnds(machineWhite ? BlackWins : WhiteWins,
7159 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
7160 /* So we have to redo legality test with true e.p. status here, */
7161 /* to make sure an illegal e.p. capture does not slip through, */
7162 /* to cause a forfeit on a justified illegal-move complaint */
7163 /* of the opponent. */
7164 if( gameMode==TwoMachinesPlay && appData.testLegality
7165 && fromY != DROP_RANK /* [HGM] temporary; should still add legality test for drops */
7168 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
7169 fromY, fromX, toY, toX, promoChar);
7170 if (appData.debugMode) {
7172 for(i=0; i< nrCastlingRights; i++) fprintf(debugFP, "(%d,%d) ",
7173 boards[forwardMostMove][CASTLING][i], castlingRank[i]);
7174 fprintf(debugFP, "castling rights\n");
7176 if(moveType == IllegalMove) {
7177 sprintf(buf1, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
7178 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
7179 GameEnds(machineWhite ? BlackWins : WhiteWins,
7182 } else if(gameInfo.variant != VariantFischeRandom && gameInfo.variant != VariantCapaRandom)
7183 /* [HGM] Kludge to handle engines that send FRC-style castling
7184 when they shouldn't (like TSCP-Gothic) */
7186 case WhiteASideCastleFR:
7187 case BlackASideCastleFR:
7189 currentMoveString[2]++;
7191 case WhiteHSideCastleFR:
7192 case BlackHSideCastleFR:
7194 currentMoveString[2]--;
7196 default: ; // nothing to do, but suppresses warning of pedantic compilers
7199 hintRequested = FALSE;
7200 lastHint[0] = NULLCHAR;
7201 bookRequested = FALSE;
7202 /* Program may be pondering now */
7203 cps->maybeThinking = TRUE;
7204 if (cps->sendTime == 2) cps->sendTime = 1;
7205 if (cps->offeredDraw) cps->offeredDraw--;
7207 /* currentMoveString is set as a side-effect of ParseOneMove */
7208 strcpy(machineMove, currentMoveString);
7209 strcat(machineMove, "\n");
7210 strcpy(moveList[forwardMostMove], machineMove);
7212 /* [AS] Save move info*/
7213 pvInfoList[ forwardMostMove ].score = programStats.score;
7214 pvInfoList[ forwardMostMove ].depth = programStats.depth;
7215 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
7217 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
7219 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
7220 if( gameMode == TwoMachinesPlay && adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
7223 while( count < adjudicateLossPlies ) {
7224 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
7227 score = -score; /* Flip score for winning side */
7230 if( score > adjudicateLossThreshold ) {
7237 if( count >= adjudicateLossPlies ) {
7238 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7240 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7241 "Xboard adjudication",
7248 if(Adjudicate(cps)) return; // [HGM] adjudicate: for all automatic game ends
7251 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
7253 if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
7254 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
7256 SendMoveToICS(moveType, fromX, fromY, toX, toY);
7258 SendMoveToICS(moveType, fromX, fromY, toX, toY);
7260 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
7261 char buf[3*MSG_SIZ];
7263 sprintf(buf, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
7264 programStats.score / 100.,
7266 programStats.time / 100.,
7267 (unsigned int)programStats.nodes,
7268 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
7269 programStats.movelist);
7271 if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.nodes, programStats.nodes);
7276 /* [AS] Clear stats for next move */
7277 ClearProgramStats();
7278 thinkOutput[0] = NULLCHAR;
7279 hiddenThinkOutputState = 0;
7282 if (gameMode == TwoMachinesPlay) {
7283 /* [HGM] relaying draw offers moved to after reception of move */
7284 /* and interpreting offer as claim if it brings draw condition */
7285 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
7286 SendToProgram("draw\n", cps->other);
7288 if (cps->other->sendTime) {
7289 SendTimeRemaining(cps->other,
7290 cps->other->twoMachinesColor[0] == 'w');
7292 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
7293 if (firstMove && !bookHit) {
7295 if (cps->other->useColors) {
7296 SendToProgram(cps->other->twoMachinesColor, cps->other);
7298 SendToProgram("go\n", cps->other);
7300 cps->other->maybeThinking = TRUE;
7303 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7305 if (!pausing && appData.ringBellAfterMoves) {
7310 * Reenable menu items that were disabled while
7311 * machine was thinking
7313 if (gameMode != TwoMachinesPlay)
7314 SetUserThinkingEnables();
7316 // [HGM] book: after book hit opponent has received move and is now in force mode
7317 // force the book reply into it, and then fake that it outputted this move by jumping
7318 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
7320 static char bookMove[MSG_SIZ]; // a bit generous?
7322 strcpy(bookMove, "move ");
7323 strcat(bookMove, bookHit);
7326 programStats.nodes = programStats.depth = programStats.time =
7327 programStats.score = programStats.got_only_move = 0;
7328 sprintf(programStats.movelist, "%s (xbook)", bookHit);
7330 if(cps->lastPing != cps->lastPong) {
7331 savedMessage = message; // args for deferred call
7333 ScheduleDelayedEvent(DeferredBookMove, 10);
7342 /* Set special modes for chess engines. Later something general
7343 * could be added here; for now there is just one kludge feature,
7344 * needed because Crafty 15.10 and earlier don't ignore SIGINT
7345 * when "xboard" is given as an interactive command.
7347 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
7348 cps->useSigint = FALSE;
7349 cps->useSigterm = FALSE;
7351 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
7352 ParseFeatures(message+8, cps);
7353 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
7356 /* [HGM] Allow engine to set up a position. Don't ask me why one would
7357 * want this, I was asked to put it in, and obliged.
7359 if (!strncmp(message, "setboard ", 9)) {
7360 Board initial_position;
7362 GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
7364 if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9)) {
7365 DisplayError(_("Bad FEN received from engine"), 0);
7369 CopyBoard(boards[0], initial_position);
7370 initialRulePlies = FENrulePlies;
7371 if(blackPlaysFirst) gameMode = MachinePlaysWhite;
7372 else gameMode = MachinePlaysBlack;
7373 DrawPosition(FALSE, boards[currentMove]);
7379 * Look for communication commands
7381 if (!strncmp(message, "telluser ", 9)) {
7382 EscapeExpand(message+9, message+9); // [HGM] esc: allow escape sequences in popup box
7383 DisplayNote(message + 9);
7386 if (!strncmp(message, "tellusererror ", 14)) {
7388 EscapeExpand(message+14, message+14); // [HGM] esc: allow escape sequences in popup box
7389 DisplayError(message + 14, 0);
7392 if (!strncmp(message, "tellopponent ", 13)) {
7393 if (appData.icsActive) {
7395 snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
7399 DisplayNote(message + 13);
7403 if (!strncmp(message, "tellothers ", 11)) {
7404 if (appData.icsActive) {
7406 snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
7412 if (!strncmp(message, "tellall ", 8)) {
7413 if (appData.icsActive) {
7415 snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
7419 DisplayNote(message + 8);
7423 if (strncmp(message, "warning", 7) == 0) {
7424 /* Undocumented feature, use tellusererror in new code */
7425 DisplayError(message, 0);
7428 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
7429 strcpy(realname, cps->tidy);
7430 strcat(realname, " query");
7431 AskQuestion(realname, buf2, buf1, cps->pr);
7434 /* Commands from the engine directly to ICS. We don't allow these to be
7435 * sent until we are logged on. Crafty kibitzes have been known to
7436 * interfere with the login process.
7439 if (!strncmp(message, "tellics ", 8)) {
7440 SendToICS(message + 8);
7444 if (!strncmp(message, "tellicsnoalias ", 15)) {
7445 SendToICS(ics_prefix);
7446 SendToICS(message + 15);
7450 /* The following are for backward compatibility only */
7451 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
7452 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
7453 SendToICS(ics_prefix);
7459 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
7463 * If the move is illegal, cancel it and redraw the board.
7464 * Also deal with other error cases. Matching is rather loose
7465 * here to accommodate engines written before the spec.
7467 if (strncmp(message + 1, "llegal move", 11) == 0 ||
7468 strncmp(message, "Error", 5) == 0) {
7469 if (StrStr(message, "name") ||
7470 StrStr(message, "rating") || StrStr(message, "?") ||
7471 StrStr(message, "result") || StrStr(message, "board") ||
7472 StrStr(message, "bk") || StrStr(message, "computer") ||
7473 StrStr(message, "variant") || StrStr(message, "hint") ||
7474 StrStr(message, "random") || StrStr(message, "depth") ||
7475 StrStr(message, "accepted")) {
7478 if (StrStr(message, "protover")) {
7479 /* Program is responding to input, so it's apparently done
7480 initializing, and this error message indicates it is
7481 protocol version 1. So we don't need to wait any longer
7482 for it to initialize and send feature commands. */
7483 FeatureDone(cps, 1);
7484 cps->protocolVersion = 1;
7487 cps->maybeThinking = FALSE;
7489 if (StrStr(message, "draw")) {
7490 /* Program doesn't have "draw" command */
7491 cps->sendDrawOffers = 0;
7494 if (cps->sendTime != 1 &&
7495 (StrStr(message, "time") || StrStr(message, "otim"))) {
7496 /* Program apparently doesn't have "time" or "otim" command */
7500 if (StrStr(message, "analyze")) {
7501 cps->analysisSupport = FALSE;
7502 cps->analyzing = FALSE;
7504 sprintf(buf2, _("%s does not support analysis"), cps->tidy);
7505 DisplayError(buf2, 0);
7508 if (StrStr(message, "(no matching move)st")) {
7509 /* Special kludge for GNU Chess 4 only */
7510 cps->stKludge = TRUE;
7511 SendTimeControl(cps, movesPerSession, timeControl,
7512 timeIncrement, appData.searchDepth,
7516 if (StrStr(message, "(no matching move)sd")) {
7517 /* Special kludge for GNU Chess 4 only */
7518 cps->sdKludge = TRUE;
7519 SendTimeControl(cps, movesPerSession, timeControl,
7520 timeIncrement, appData.searchDepth,
7524 if (!StrStr(message, "llegal")) {
7527 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
7528 gameMode == IcsIdle) return;
7529 if (forwardMostMove <= backwardMostMove) return;
7530 if (pausing) PauseEvent();
7531 if(appData.forceIllegal) {
7532 // [HGM] illegal: machine refused move; force position after move into it
7533 SendToProgram("force\n", cps);
7534 if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
7535 // we have a real problem now, as SendBoard will use the a2a3 kludge
7536 // when black is to move, while there might be nothing on a2 or black
7537 // might already have the move. So send the board as if white has the move.
7538 // But first we must change the stm of the engine, as it refused the last move
7539 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
7540 if(WhiteOnMove(forwardMostMove)) {
7541 SendToProgram("a7a6\n", cps); // for the engine black still had the move
7542 SendBoard(cps, forwardMostMove); // kludgeless board
7544 SendToProgram("a2a3\n", cps); // for the engine white still had the move
7545 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
7546 SendBoard(cps, forwardMostMove+1); // kludgeless board
7548 } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
7549 if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
7550 gameMode == TwoMachinesPlay)
7551 SendToProgram("go\n", cps);
7554 if (gameMode == PlayFromGameFile) {
7555 /* Stop reading this game file */
7556 gameMode = EditGame;
7559 currentMove = forwardMostMove-1;
7560 DisplayMove(currentMove-1); /* before DisplayMoveError */
7561 SwitchClocks(forwardMostMove-1); // [HGM] race
7562 DisplayBothClocks();
7563 sprintf(buf1, _("Illegal move \"%s\" (rejected by %s chess program)"),
7564 parseList[currentMove], cps->which);
7565 DisplayMoveError(buf1);
7566 DrawPosition(FALSE, boards[currentMove]);
7568 /* [HGM] illegal-move claim should forfeit game when Xboard */
7569 /* only passes fully legal moves */
7570 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
7571 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
7572 "False illegal-move claim", GE_XBOARD );
7576 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
7577 /* Program has a broken "time" command that
7578 outputs a string not ending in newline.
7584 * If chess program startup fails, exit with an error message.
7585 * Attempts to recover here are futile.
7587 if ((StrStr(message, "unknown host") != NULL)
7588 || (StrStr(message, "No remote directory") != NULL)
7589 || (StrStr(message, "not found") != NULL)
7590 || (StrStr(message, "No such file") != NULL)
7591 || (StrStr(message, "can't alloc") != NULL)
7592 || (StrStr(message, "Permission denied") != NULL)) {
7594 cps->maybeThinking = FALSE;
7595 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
7596 cps->which, cps->program, cps->host, message);
7597 RemoveInputSource(cps->isr);
7598 DisplayFatalError(buf1, 0, 1);
7603 * Look for hint output
7605 if (sscanf(message, "Hint: %s", buf1) == 1) {
7606 if (cps == &first && hintRequested) {
7607 hintRequested = FALSE;
7608 if (ParseOneMove(buf1, forwardMostMove, &moveType,
7609 &fromX, &fromY, &toX, &toY, &promoChar)) {
7610 (void) CoordsToAlgebraic(boards[forwardMostMove],
7611 PosFlags(forwardMostMove),
7612 fromY, fromX, toY, toX, promoChar, buf1);
7613 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
7614 DisplayInformation(buf2);
7616 /* Hint move could not be parsed!? */
7617 snprintf(buf2, sizeof(buf2),
7618 _("Illegal hint move \"%s\"\nfrom %s chess program"),
7620 DisplayError(buf2, 0);
7623 strcpy(lastHint, buf1);
7629 * Ignore other messages if game is not in progress
7631 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
7632 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
7635 * look for win, lose, draw, or draw offer
7637 if (strncmp(message, "1-0", 3) == 0) {
7638 char *p, *q, *r = "";
7639 p = strchr(message, '{');
7647 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
7649 } else if (strncmp(message, "0-1", 3) == 0) {
7650 char *p, *q, *r = "";
7651 p = strchr(message, '{');
7659 /* Kludge for Arasan 4.1 bug */
7660 if (strcmp(r, "Black resigns") == 0) {
7661 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
7664 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
7666 } else if (strncmp(message, "1/2", 3) == 0) {
7667 char *p, *q, *r = "";
7668 p = strchr(message, '{');
7677 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
7680 } else if (strncmp(message, "White resign", 12) == 0) {
7681 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
7683 } else if (strncmp(message, "Black resign", 12) == 0) {
7684 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
7686 } else if (strncmp(message, "White matches", 13) == 0 ||
7687 strncmp(message, "Black matches", 13) == 0 ) {
7688 /* [HGM] ignore GNUShogi noises */
7690 } else if (strncmp(message, "White", 5) == 0 &&
7691 message[5] != '(' &&
7692 StrStr(message, "Black") == NULL) {
7693 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
7695 } else if (strncmp(message, "Black", 5) == 0 &&
7696 message[5] != '(') {
7697 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
7699 } else if (strcmp(message, "resign") == 0 ||
7700 strcmp(message, "computer resigns") == 0) {
7702 case MachinePlaysBlack:
7703 case IcsPlayingBlack:
7704 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
7706 case MachinePlaysWhite:
7707 case IcsPlayingWhite:
7708 GameEnds(BlackWins, "White resigns", GE_ENGINE);
7710 case TwoMachinesPlay:
7711 if (cps->twoMachinesColor[0] == 'w')
7712 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
7714 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
7721 } else if (strncmp(message, "opponent mates", 14) == 0) {
7723 case MachinePlaysBlack:
7724 case IcsPlayingBlack:
7725 GameEnds(WhiteWins, "White mates", GE_ENGINE);
7727 case MachinePlaysWhite:
7728 case IcsPlayingWhite:
7729 GameEnds(BlackWins, "Black mates", GE_ENGINE);
7731 case TwoMachinesPlay:
7732 if (cps->twoMachinesColor[0] == 'w')
7733 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
7735 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
7742 } else if (strncmp(message, "computer mates", 14) == 0) {
7744 case MachinePlaysBlack:
7745 case IcsPlayingBlack:
7746 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
7748 case MachinePlaysWhite:
7749 case IcsPlayingWhite:
7750 GameEnds(WhiteWins, "White mates", GE_ENGINE);
7752 case TwoMachinesPlay:
7753 if (cps->twoMachinesColor[0] == 'w')
7754 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
7756 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
7763 } else if (strncmp(message, "checkmate", 9) == 0) {
7764 if (WhiteOnMove(forwardMostMove)) {
7765 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
7767 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
7770 } else if (strstr(message, "Draw") != NULL ||
7771 strstr(message, "game is a draw") != NULL) {
7772 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
7774 } else if (strstr(message, "offer") != NULL &&
7775 strstr(message, "draw") != NULL) {
7777 if (appData.zippyPlay && first.initDone) {
7778 /* Relay offer to ICS */
7779 SendToICS(ics_prefix);
7780 SendToICS("draw\n");
7783 cps->offeredDraw = 2; /* valid until this engine moves twice */
7784 if (gameMode == TwoMachinesPlay) {
7785 if (cps->other->offeredDraw) {
7786 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
7787 /* [HGM] in two-machine mode we delay relaying draw offer */
7788 /* until after we also have move, to see if it is really claim */
7790 } else if (gameMode == MachinePlaysWhite ||
7791 gameMode == MachinePlaysBlack) {
7792 if (userOfferedDraw) {
7793 DisplayInformation(_("Machine accepts your draw offer"));
7794 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
7796 DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
7803 * Look for thinking output
7805 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
7806 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
7808 int plylev, mvleft, mvtot, curscore, time;
7809 char mvname[MOVE_LEN];
7813 int prefixHint = FALSE;
7814 mvname[0] = NULLCHAR;
7817 case MachinePlaysBlack:
7818 case IcsPlayingBlack:
7819 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
7821 case MachinePlaysWhite:
7822 case IcsPlayingWhite:
7823 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
7828 case IcsObserving: /* [DM] icsEngineAnalyze */
7829 if (!appData.icsEngineAnalyze) ignore = TRUE;
7831 case TwoMachinesPlay:
7832 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
7842 ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
7844 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
7845 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
7847 if (plyext != ' ' && plyext != '\t') {
7851 /* [AS] Negate score if machine is playing black and reporting absolute scores */
7852 if( cps->scoreIsAbsolute &&
7853 ( gameMode == MachinePlaysBlack ||
7854 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
7855 gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
7856 (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
7857 !WhiteOnMove(currentMove)
7860 curscore = -curscore;
7864 tempStats.depth = plylev;
7865 tempStats.nodes = nodes;
7866 tempStats.time = time;
7867 tempStats.score = curscore;
7868 tempStats.got_only_move = 0;
7870 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
7873 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
7874 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
7875 if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
7876 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
7877 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
7878 if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
7879 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
7880 blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
7883 /* Buffer overflow protection */
7884 if (buf1[0] != NULLCHAR) {
7885 if (strlen(buf1) >= sizeof(tempStats.movelist)
7886 && appData.debugMode) {
7888 "PV is too long; using the first %u bytes.\n",
7889 (unsigned) sizeof(tempStats.movelist) - 1);
7892 safeStrCpy( tempStats.movelist, buf1, sizeof(tempStats.movelist) );
7894 sprintf(tempStats.movelist, " no PV\n");
7897 if (tempStats.seen_stat) {
7898 tempStats.ok_to_send = 1;
7901 if (strchr(tempStats.movelist, '(') != NULL) {
7902 tempStats.line_is_book = 1;
7903 tempStats.nr_moves = 0;
7904 tempStats.moves_left = 0;
7906 tempStats.line_is_book = 0;
7909 if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
7910 programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
7912 SendProgramStatsToFrontend( cps, &tempStats );
7915 [AS] Protect the thinkOutput buffer from overflow... this
7916 is only useful if buf1 hasn't overflowed first!
7918 sprintf(thinkOutput, "[%d]%c%+.2f %s%s",
7920 (gameMode == TwoMachinesPlay ?
7921 ToUpper(cps->twoMachinesColor[0]) : ' '),
7922 ((double) curscore) / 100.0,
7923 prefixHint ? lastHint : "",
7924 prefixHint ? " " : "" );
7926 if( buf1[0] != NULLCHAR ) {
7927 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
7929 if( strlen(buf1) > max_len ) {
7930 if( appData.debugMode) {
7931 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
7933 buf1[max_len+1] = '\0';
7936 strcat( thinkOutput, buf1 );
7939 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
7940 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
7941 DisplayMove(currentMove - 1);
7945 } else if ((p=StrStr(message, "(only move)")) != NULL) {
7946 /* crafty (9.25+) says "(only move) <move>"
7947 * if there is only 1 legal move
7949 sscanf(p, "(only move) %s", buf1);
7950 sprintf(thinkOutput, "%s (only move)", buf1);
7951 sprintf(programStats.movelist, "%s (only move)", buf1);
7952 programStats.depth = 1;
7953 programStats.nr_moves = 1;
7954 programStats.moves_left = 1;
7955 programStats.nodes = 1;
7956 programStats.time = 1;
7957 programStats.got_only_move = 1;
7959 /* Not really, but we also use this member to
7960 mean "line isn't going to change" (Crafty
7961 isn't searching, so stats won't change) */
7962 programStats.line_is_book = 1;
7964 SendProgramStatsToFrontend( cps, &programStats );
7966 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
7967 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
7968 DisplayMove(currentMove - 1);
7971 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
7972 &time, &nodes, &plylev, &mvleft,
7973 &mvtot, mvname) >= 5) {
7974 /* The stat01: line is from Crafty (9.29+) in response
7975 to the "." command */
7976 programStats.seen_stat = 1;
7977 cps->maybeThinking = TRUE;
7979 if (programStats.got_only_move || !appData.periodicUpdates)
7982 programStats.depth = plylev;
7983 programStats.time = time;
7984 programStats.nodes = nodes;
7985 programStats.moves_left = mvleft;
7986 programStats.nr_moves = mvtot;
7987 strcpy(programStats.move_name, mvname);
7988 programStats.ok_to_send = 1;
7989 programStats.movelist[0] = '\0';
7991 SendProgramStatsToFrontend( cps, &programStats );
7995 } else if (strncmp(message,"++",2) == 0) {
7996 /* Crafty 9.29+ outputs this */
7997 programStats.got_fail = 2;
8000 } else if (strncmp(message,"--",2) == 0) {
8001 /* Crafty 9.29+ outputs this */
8002 programStats.got_fail = 1;
8005 } else if (thinkOutput[0] != NULLCHAR &&
8006 strncmp(message, " ", 4) == 0) {
8007 unsigned message_len;
8010 while (*p && *p == ' ') p++;
8012 message_len = strlen( p );
8014 /* [AS] Avoid buffer overflow */
8015 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
8016 strcat(thinkOutput, " ");
8017 strcat(thinkOutput, p);
8020 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
8021 strcat(programStats.movelist, " ");
8022 strcat(programStats.movelist, p);
8025 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8026 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8027 DisplayMove(currentMove - 1);
8035 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8036 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
8038 ChessProgramStats cpstats;
8040 if (plyext != ' ' && plyext != '\t') {
8044 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8045 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
8046 curscore = -curscore;
8049 cpstats.depth = plylev;
8050 cpstats.nodes = nodes;
8051 cpstats.time = time;
8052 cpstats.score = curscore;
8053 cpstats.got_only_move = 0;
8054 cpstats.movelist[0] = '\0';
8056 if (buf1[0] != NULLCHAR) {
8057 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist) );
8060 cpstats.ok_to_send = 0;
8061 cpstats.line_is_book = 0;
8062 cpstats.nr_moves = 0;
8063 cpstats.moves_left = 0;
8065 SendProgramStatsToFrontend( cps, &cpstats );
8072 /* Parse a game score from the character string "game", and
8073 record it as the history of the current game. The game
8074 score is NOT assumed to start from the standard position.
8075 The display is not updated in any way.
8078 ParseGameHistory(game)
8082 int fromX, fromY, toX, toY, boardIndex;
8087 if (appData.debugMode)
8088 fprintf(debugFP, "Parsing game history: %s\n", game);
8090 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
8091 gameInfo.site = StrSave(appData.icsHost);
8092 gameInfo.date = PGNDate();
8093 gameInfo.round = StrSave("-");
8095 /* Parse out names of players */
8096 while (*game == ' ') game++;
8098 while (*game != ' ') *p++ = *game++;
8100 gameInfo.white = StrSave(buf);
8101 while (*game == ' ') game++;
8103 while (*game != ' ' && *game != '\n') *p++ = *game++;
8105 gameInfo.black = StrSave(buf);
8108 boardIndex = blackPlaysFirst ? 1 : 0;
8111 yyboardindex = boardIndex;
8112 moveType = (ChessMove) yylex();
8114 case IllegalMove: /* maybe suicide chess, etc. */
8115 if (appData.debugMode) {
8116 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
8117 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8118 setbuf(debugFP, NULL);
8120 case WhitePromotionChancellor:
8121 case BlackPromotionChancellor:
8122 case WhitePromotionArchbishop:
8123 case BlackPromotionArchbishop:
8124 case WhitePromotionQueen:
8125 case BlackPromotionQueen:
8126 case WhitePromotionRook:
8127 case BlackPromotionRook:
8128 case WhitePromotionBishop:
8129 case BlackPromotionBishop:
8130 case WhitePromotionKnight:
8131 case BlackPromotionKnight:
8132 case WhitePromotionKing:
8133 case BlackPromotionKing:
8135 case WhiteCapturesEnPassant:
8136 case BlackCapturesEnPassant:
8137 case WhiteKingSideCastle:
8138 case WhiteQueenSideCastle:
8139 case BlackKingSideCastle:
8140 case BlackQueenSideCastle:
8141 case WhiteKingSideCastleWild:
8142 case WhiteQueenSideCastleWild:
8143 case BlackKingSideCastleWild:
8144 case BlackQueenSideCastleWild:
8146 case WhiteHSideCastleFR:
8147 case WhiteASideCastleFR:
8148 case BlackHSideCastleFR:
8149 case BlackASideCastleFR:
8151 fromX = currentMoveString[0] - AAA;
8152 fromY = currentMoveString[1] - ONE;
8153 toX = currentMoveString[2] - AAA;
8154 toY = currentMoveString[3] - ONE;
8155 promoChar = currentMoveString[4];
8159 fromX = moveType == WhiteDrop ?
8160 (int) CharToPiece(ToUpper(currentMoveString[0])) :
8161 (int) CharToPiece(ToLower(currentMoveString[0]));
8163 toX = currentMoveString[2] - AAA;
8164 toY = currentMoveString[3] - ONE;
8165 promoChar = NULLCHAR;
8169 sprintf(buf, _("Ambiguous move in ICS output: \"%s\""), yy_text);
8170 if (appData.debugMode) {
8171 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
8172 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8173 setbuf(debugFP, NULL);
8175 DisplayError(buf, 0);
8177 case ImpossibleMove:
8179 sprintf(buf, _("Illegal move in ICS output: \"%s\""), yy_text);
8180 if (appData.debugMode) {
8181 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
8182 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8183 setbuf(debugFP, NULL);
8185 DisplayError(buf, 0);
8187 case (ChessMove) 0: /* end of file */
8188 if (boardIndex < backwardMostMove) {
8189 /* Oops, gap. How did that happen? */
8190 DisplayError(_("Gap in move list"), 0);
8193 backwardMostMove = blackPlaysFirst ? 1 : 0;
8194 if (boardIndex > forwardMostMove) {
8195 forwardMostMove = boardIndex;
8199 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
8200 strcat(parseList[boardIndex-1], " ");
8201 strcat(parseList[boardIndex-1], yy_text);
8213 case GameUnfinished:
8214 if (gameMode == IcsExamining) {
8215 if (boardIndex < backwardMostMove) {
8216 /* Oops, gap. How did that happen? */
8219 backwardMostMove = blackPlaysFirst ? 1 : 0;
8222 gameInfo.result = moveType;
8223 p = strchr(yy_text, '{');
8224 if (p == NULL) p = strchr(yy_text, '(');
8227 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
8229 q = strchr(p, *p == '{' ? '}' : ')');
8230 if (q != NULL) *q = NULLCHAR;
8233 gameInfo.resultDetails = StrSave(p);
8236 if (boardIndex >= forwardMostMove &&
8237 !(gameMode == IcsObserving && ics_gamenum == -1)) {
8238 backwardMostMove = blackPlaysFirst ? 1 : 0;
8241 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
8242 fromY, fromX, toY, toX, promoChar,
8243 parseList[boardIndex]);
8244 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
8245 /* currentMoveString is set as a side-effect of yylex */
8246 strcpy(moveList[boardIndex], currentMoveString);
8247 strcat(moveList[boardIndex], "\n");
8249 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
8250 switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
8256 if(gameInfo.variant != VariantShogi)
8257 strcat(parseList[boardIndex - 1], "+");
8261 strcat(parseList[boardIndex - 1], "#");
8268 /* Apply a move to the given board */
8270 ApplyMove(fromX, fromY, toX, toY, promoChar, board)
8271 int fromX, fromY, toX, toY;
8275 ChessSquare captured = board[toY][toX], piece, king; int p, oldEP = EP_NONE, berolina = 0;
8276 int promoRank = gameInfo.variant == VariantMakruk ? 3 : 1;
8278 /* [HGM] compute & store e.p. status and castling rights for new position */
8279 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
8282 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
8283 oldEP = (signed char)board[EP_STATUS];
8284 board[EP_STATUS] = EP_NONE;
8286 if( board[toY][toX] != EmptySquare )
8287 board[EP_STATUS] = EP_CAPTURE;
8289 if( board[fromY][fromX] == WhitePawn ) {
8290 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
8291 board[EP_STATUS] = EP_PAWN_MOVE;
8293 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
8294 gameInfo.variant != VariantBerolina || toX < fromX)
8295 board[EP_STATUS] = toX | berolina;
8296 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
8297 gameInfo.variant != VariantBerolina || toX > fromX)
8298 board[EP_STATUS] = toX;
8301 if( board[fromY][fromX] == BlackPawn ) {
8302 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
8303 board[EP_STATUS] = EP_PAWN_MOVE;
8304 if( toY-fromY== -2) {
8305 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
8306 gameInfo.variant != VariantBerolina || toX < fromX)
8307 board[EP_STATUS] = toX | berolina;
8308 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
8309 gameInfo.variant != VariantBerolina || toX > fromX)
8310 board[EP_STATUS] = toX;
8314 for(i=0; i<nrCastlingRights; i++) {
8315 if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
8316 board[CASTLING][i] == toX && castlingRank[i] == toY
8317 ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
8322 /* [HGM] In Shatranj and Courier all promotions are to Ferz */
8323 if((gameInfo.variant==VariantShatranj || gameInfo.variant==VariantCourier || gameInfo.variant == VariantMakruk)
8324 && promoChar != 0) promoChar = PieceToChar(WhiteFerz);
8326 if (fromX == toX && fromY == toY) return;
8328 if (fromY == DROP_RANK) {
8330 piece = board[toY][toX] = (ChessSquare) fromX;
8332 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
8333 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
8334 if(gameInfo.variant == VariantKnightmate)
8335 king += (int) WhiteUnicorn - (int) WhiteKing;
8337 /* Code added by Tord: */
8338 /* FRC castling assumed when king captures friendly rook. */
8339 if (board[fromY][fromX] == WhiteKing &&
8340 board[toY][toX] == WhiteRook) {
8341 board[fromY][fromX] = EmptySquare;
8342 board[toY][toX] = EmptySquare;
8344 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
8346 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
8348 } else if (board[fromY][fromX] == BlackKing &&
8349 board[toY][toX] == BlackRook) {
8350 board[fromY][fromX] = EmptySquare;
8351 board[toY][toX] = EmptySquare;
8353 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
8355 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
8357 /* End of code added by Tord */
8359 } else if (board[fromY][fromX] == king
8360 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8361 && toY == fromY && toX > fromX+1) {
8362 board[fromY][fromX] = EmptySquare;
8363 board[toY][toX] = king;
8364 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
8365 board[fromY][BOARD_RGHT-1] = EmptySquare;
8366 } else if (board[fromY][fromX] == king
8367 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8368 && toY == fromY && toX < fromX-1) {
8369 board[fromY][fromX] = EmptySquare;
8370 board[toY][toX] = king;
8371 board[toY][toX+1] = board[fromY][BOARD_LEFT];
8372 board[fromY][BOARD_LEFT] = EmptySquare;
8373 } else if (board[fromY][fromX] == WhitePawn
8374 && toY >= BOARD_HEIGHT-promoRank
8375 && gameInfo.variant != VariantXiangqi
8377 /* white pawn promotion */
8378 board[toY][toX] = CharToPiece(ToUpper(promoChar));
8379 if (board[toY][toX] == EmptySquare) {
8380 board[toY][toX] = WhiteQueen;
8382 if(gameInfo.variant==VariantBughouse ||
8383 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
8384 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
8385 board[fromY][fromX] = EmptySquare;
8386 } else if ((fromY == BOARD_HEIGHT-4)
8388 && gameInfo.variant != VariantXiangqi
8389 && gameInfo.variant != VariantBerolina
8390 && (board[fromY][fromX] == WhitePawn)
8391 && (board[toY][toX] == EmptySquare)) {
8392 board[fromY][fromX] = EmptySquare;
8393 board[toY][toX] = WhitePawn;
8394 captured = board[toY - 1][toX];
8395 board[toY - 1][toX] = EmptySquare;
8396 } else if ((fromY == BOARD_HEIGHT-4)
8398 && gameInfo.variant == VariantBerolina
8399 && (board[fromY][fromX] == WhitePawn)
8400 && (board[toY][toX] == EmptySquare)) {
8401 board[fromY][fromX] = EmptySquare;
8402 board[toY][toX] = WhitePawn;
8403 if(oldEP & EP_BEROLIN_A) {
8404 captured = board[fromY][fromX-1];
8405 board[fromY][fromX-1] = EmptySquare;
8406 }else{ captured = board[fromY][fromX+1];
8407 board[fromY][fromX+1] = EmptySquare;
8409 } else if (board[fromY][fromX] == king
8410 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8411 && toY == fromY && toX > fromX+1) {
8412 board[fromY][fromX] = EmptySquare;
8413 board[toY][toX] = king;
8414 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
8415 board[fromY][BOARD_RGHT-1] = EmptySquare;
8416 } else if (board[fromY][fromX] == king
8417 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8418 && toY == fromY && toX < fromX-1) {
8419 board[fromY][fromX] = EmptySquare;
8420 board[toY][toX] = king;
8421 board[toY][toX+1] = board[fromY][BOARD_LEFT];
8422 board[fromY][BOARD_LEFT] = EmptySquare;
8423 } else if (fromY == 7 && fromX == 3
8424 && board[fromY][fromX] == BlackKing
8425 && toY == 7 && toX == 5) {
8426 board[fromY][fromX] = EmptySquare;
8427 board[toY][toX] = BlackKing;
8428 board[fromY][7] = EmptySquare;
8429 board[toY][4] = BlackRook;
8430 } else if (fromY == 7 && fromX == 3
8431 && board[fromY][fromX] == BlackKing
8432 && toY == 7 && toX == 1) {
8433 board[fromY][fromX] = EmptySquare;
8434 board[toY][toX] = BlackKing;
8435 board[fromY][0] = EmptySquare;
8436 board[toY][2] = BlackRook;
8437 } else if (board[fromY][fromX] == BlackPawn
8439 && gameInfo.variant != VariantXiangqi
8441 /* black pawn promotion */
8442 board[toY][toX] = CharToPiece(ToLower(promoChar));
8443 if (board[toY][toX] == EmptySquare) {
8444 board[toY][toX] = BlackQueen;
8446 if(gameInfo.variant==VariantBughouse ||
8447 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
8448 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
8449 board[fromY][fromX] = EmptySquare;
8450 } else if ((fromY == 3)
8452 && gameInfo.variant != VariantXiangqi
8453 && gameInfo.variant != VariantBerolina
8454 && (board[fromY][fromX] == BlackPawn)
8455 && (board[toY][toX] == EmptySquare)) {
8456 board[fromY][fromX] = EmptySquare;
8457 board[toY][toX] = BlackPawn;
8458 captured = board[toY + 1][toX];
8459 board[toY + 1][toX] = EmptySquare;
8460 } else if ((fromY == 3)
8462 && gameInfo.variant == VariantBerolina
8463 && (board[fromY][fromX] == BlackPawn)
8464 && (board[toY][toX] == EmptySquare)) {
8465 board[fromY][fromX] = EmptySquare;
8466 board[toY][toX] = BlackPawn;
8467 if(oldEP & EP_BEROLIN_A) {
8468 captured = board[fromY][fromX-1];
8469 board[fromY][fromX-1] = EmptySquare;
8470 }else{ captured = board[fromY][fromX+1];
8471 board[fromY][fromX+1] = EmptySquare;
8474 board[toY][toX] = board[fromY][fromX];
8475 board[fromY][fromX] = EmptySquare;
8478 /* [HGM] now we promote for Shogi, if needed */
8479 if(gameInfo.variant == VariantShogi && promoChar == 'q')
8480 board[toY][toX] = (ChessSquare) (PROMOTED piece);
8483 if (gameInfo.holdingsWidth != 0) {
8485 /* !!A lot more code needs to be written to support holdings */
8486 /* [HGM] OK, so I have written it. Holdings are stored in the */
8487 /* penultimate board files, so they are automaticlly stored */
8488 /* in the game history. */
8489 if (fromY == DROP_RANK) {
8490 /* Delete from holdings, by decreasing count */
8491 /* and erasing image if necessary */
8493 if(p < (int) BlackPawn) { /* white drop */
8494 p -= (int)WhitePawn;
8495 p = PieceToNumber((ChessSquare)p);
8496 if(p >= gameInfo.holdingsSize) p = 0;
8497 if(--board[p][BOARD_WIDTH-2] <= 0)
8498 board[p][BOARD_WIDTH-1] = EmptySquare;
8499 if((int)board[p][BOARD_WIDTH-2] < 0)
8500 board[p][BOARD_WIDTH-2] = 0;
8501 } else { /* black drop */
8502 p -= (int)BlackPawn;
8503 p = PieceToNumber((ChessSquare)p);
8504 if(p >= gameInfo.holdingsSize) p = 0;
8505 if(--board[BOARD_HEIGHT-1-p][1] <= 0)
8506 board[BOARD_HEIGHT-1-p][0] = EmptySquare;
8507 if((int)board[BOARD_HEIGHT-1-p][1] < 0)
8508 board[BOARD_HEIGHT-1-p][1] = 0;
8511 if (captured != EmptySquare && gameInfo.holdingsSize > 0
8512 && gameInfo.variant != VariantBughouse ) {
8513 /* [HGM] holdings: Add to holdings, if holdings exist */
8514 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
8515 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
8516 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
8519 if (p >= (int) BlackPawn) {
8520 p -= (int)BlackPawn;
8521 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
8522 /* in Shogi restore piece to its original first */
8523 captured = (ChessSquare) (DEMOTED captured);
8526 p = PieceToNumber((ChessSquare)p);
8527 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
8528 board[p][BOARD_WIDTH-2]++;
8529 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
8531 p -= (int)WhitePawn;
8532 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
8533 captured = (ChessSquare) (DEMOTED captured);
8536 p = PieceToNumber((ChessSquare)p);
8537 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
8538 board[BOARD_HEIGHT-1-p][1]++;
8539 board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
8542 } else if (gameInfo.variant == VariantAtomic) {
8543 if (captured != EmptySquare) {
8545 for (y = toY-1; y <= toY+1; y++) {
8546 for (x = toX-1; x <= toX+1; x++) {
8547 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
8548 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
8549 board[y][x] = EmptySquare;
8553 board[toY][toX] = EmptySquare;
8556 if(gameInfo.variant == VariantShogi && promoChar != NULLCHAR && promoChar != '=') {
8557 /* [HGM] Shogi promotions */
8558 board[toY][toX] = (ChessSquare) (PROMOTED piece);
8561 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
8562 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
8563 // [HGM] superchess: take promotion piece out of holdings
8564 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
8565 if((int)piece < (int)BlackPawn) { // determine stm from piece color
8566 if(!--board[k][BOARD_WIDTH-2])
8567 board[k][BOARD_WIDTH-1] = EmptySquare;
8569 if(!--board[BOARD_HEIGHT-1-k][1])
8570 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
8576 /* Updates forwardMostMove */
8578 MakeMove(fromX, fromY, toX, toY, promoChar)
8579 int fromX, fromY, toX, toY;
8582 // forwardMostMove++; // [HGM] bare: moved downstream
8584 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
8585 int timeLeft; static int lastLoadFlag=0; int king, piece;
8586 piece = boards[forwardMostMove][fromY][fromX];
8587 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
8588 if(gameInfo.variant == VariantKnightmate)
8589 king += (int) WhiteUnicorn - (int) WhiteKing;
8590 if(forwardMostMove == 0) {
8592 fprintf(serverMoves, "%s;", second.tidy);
8593 fprintf(serverMoves, "%s;", first.tidy);
8594 if(!blackPlaysFirst)
8595 fprintf(serverMoves, "%s;", second.tidy);
8596 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
8597 lastLoadFlag = loadFlag;
8599 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
8600 // print castling suffix
8601 if( toY == fromY && piece == king ) {
8603 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
8605 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
8608 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
8609 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
8610 boards[forwardMostMove][toY][toX] == EmptySquare
8611 && fromX != toX && fromY != toY)
8612 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
8614 if(promoChar != NULLCHAR)
8615 fprintf(serverMoves, ":%c:%c%c", promoChar, AAA+toX, ONE+toY);
8617 fprintf(serverMoves, "/%d/%d",
8618 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
8619 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
8620 else timeLeft = blackTimeRemaining/1000;
8621 fprintf(serverMoves, "/%d", timeLeft);
8623 fflush(serverMoves);
8626 if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations
8627 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
8631 UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
8632 if (commentList[forwardMostMove+1] != NULL) {
8633 free(commentList[forwardMostMove+1]);
8634 commentList[forwardMostMove+1] = NULL;
8636 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
8637 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
8638 // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
8639 SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
8640 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
8641 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
8642 gameInfo.result = GameUnfinished;
8643 if (gameInfo.resultDetails != NULL) {
8644 free(gameInfo.resultDetails);
8645 gameInfo.resultDetails = NULL;
8647 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
8648 moveList[forwardMostMove - 1]);
8649 (void) CoordsToAlgebraic(boards[forwardMostMove - 1],
8650 PosFlags(forwardMostMove - 1),
8651 fromY, fromX, toY, toX, promoChar,
8652 parseList[forwardMostMove - 1]);
8653 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
8659 if(gameInfo.variant != VariantShogi)
8660 strcat(parseList[forwardMostMove - 1], "+");
8664 strcat(parseList[forwardMostMove - 1], "#");
8667 if (appData.debugMode) {
8668 fprintf(debugFP, "move: %s, parse: %s (%c)\n", moveList[forwardMostMove-1], parseList[forwardMostMove-1], moveList[forwardMostMove-1][4]);
8673 /* Updates currentMove if not pausing */
8675 ShowMove(fromX, fromY, toX, toY)
8677 int instant = (gameMode == PlayFromGameFile) ?
8678 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
8679 if(appData.noGUI) return;
8680 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
8682 if (forwardMostMove == currentMove + 1) {
8683 AnimateMove(boards[forwardMostMove - 1],
8684 fromX, fromY, toX, toY);
8686 if (appData.highlightLastMove) {
8687 SetHighlights(fromX, fromY, toX, toY);
8690 currentMove = forwardMostMove;
8693 if (instant) return;
8695 DisplayMove(currentMove - 1);
8696 DrawPosition(FALSE, boards[currentMove]);
8697 DisplayBothClocks();
8698 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
8701 void SendEgtPath(ChessProgramState *cps)
8702 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
8703 char buf[MSG_SIZ], name[MSG_SIZ], *p;
8705 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
8708 char c, *q = name+1, *r, *s;
8710 name[0] = ','; // extract next format name from feature and copy with prefixed ','
8711 while(*p && *p != ',') *q++ = *p++;
8713 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
8714 strcmp(name, ",nalimov:") == 0 ) {
8715 // take nalimov path from the menu-changeable option first, if it is defined
8716 sprintf(buf, "egtpath nalimov %s\n", appData.defaultPathEGTB);
8717 SendToProgram(buf,cps); // send egtbpath command for nalimov
8719 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
8720 (s = StrStr(appData.egtFormats, name)) != NULL) {
8721 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
8722 s = r = StrStr(s, ":") + 1; // beginning of path info
8723 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
8724 c = *r; *r = 0; // temporarily null-terminate path info
8725 *--q = 0; // strip of trailig ':' from name
8726 sprintf(buf, "egtpath %s %s\n", name+1, s);
8728 SendToProgram(buf,cps); // send egtbpath command for this format
8730 if(*p == ',') p++; // read away comma to position for next format name
8735 InitChessProgram(cps, setup)
8736 ChessProgramState *cps;
8737 int setup; /* [HGM] needed to setup FRC opening position */
8739 char buf[MSG_SIZ], b[MSG_SIZ]; int overruled;
8740 if (appData.noChessProgram) return;
8741 hintRequested = FALSE;
8742 bookRequested = FALSE;
8744 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
8745 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
8746 if(cps->memSize) { /* [HGM] memory */
8747 sprintf(buf, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
8748 SendToProgram(buf, cps);
8750 SendEgtPath(cps); /* [HGM] EGT */
8751 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
8752 sprintf(buf, "cores %d\n", appData.smpCores);
8753 SendToProgram(buf, cps);
8756 SendToProgram(cps->initString, cps);
8757 if (gameInfo.variant != VariantNormal &&
8758 gameInfo.variant != VariantLoadable
8759 /* [HGM] also send variant if board size non-standard */
8760 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0
8762 char *v = VariantName(gameInfo.variant);
8763 if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) {
8764 /* [HGM] in protocol 1 we have to assume all variants valid */
8765 sprintf(buf, _("Variant %s not supported by %s"), v, cps->tidy);
8766 DisplayFatalError(buf, 0, 1);
8770 /* [HGM] make prefix for non-standard board size. Awkward testing... */
8771 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
8772 if( gameInfo.variant == VariantXiangqi )
8773 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 0;
8774 if( gameInfo.variant == VariantShogi )
8775 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 9 || gameInfo.holdingsSize != 7;
8776 if( gameInfo.variant == VariantBughouse || gameInfo.variant == VariantCrazyhouse )
8777 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 5;
8778 if( gameInfo.variant == VariantCapablanca || gameInfo.variant == VariantCapaRandom ||
8779 gameInfo.variant == VariantGothic || gameInfo.variant == VariantFalcon )
8780 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
8781 if( gameInfo.variant == VariantCourier )
8782 overruled = gameInfo.boardWidth != 12 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
8783 if( gameInfo.variant == VariantSuper )
8784 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
8785 if( gameInfo.variant == VariantGreat )
8786 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
8789 sprintf(b, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
8790 gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
8791 /* [HGM] varsize: try first if this defiant size variant is specifically known */
8792 if(StrStr(cps->variants, b) == NULL) {
8793 // specific sized variant not known, check if general sizing allowed
8794 if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best
8795 if(StrStr(cps->variants, "boardsize") == NULL) {
8796 sprintf(buf, "Board size %dx%d+%d not supported by %s",
8797 gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy);
8798 DisplayFatalError(buf, 0, 1);
8801 /* [HGM] here we really should compare with the maximum supported board size */
8804 } else sprintf(b, "%s", VariantName(gameInfo.variant));
8805 sprintf(buf, "variant %s\n", b);
8806 SendToProgram(buf, cps);
8808 currentlyInitializedVariant = gameInfo.variant;
8810 /* [HGM] send opening position in FRC to first engine */
8812 SendToProgram("force\n", cps);
8814 /* engine is now in force mode! Set flag to wake it up after first move. */
8815 setboardSpoiledMachineBlack = 1;
8819 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
8820 SendToProgram(buf, cps);
8822 cps->maybeThinking = FALSE;
8823 cps->offeredDraw = 0;
8824 if (!appData.icsActive) {
8825 SendTimeControl(cps, movesPerSession, timeControl,
8826 timeIncrement, appData.searchDepth,
8829 if (appData.showThinking
8830 // [HGM] thinking: four options require thinking output to be sent
8831 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
8833 SendToProgram("post\n", cps);
8835 SendToProgram("hard\n", cps);
8836 if (!appData.ponderNextMove) {
8837 /* Warning: "easy" is a toggle in GNU Chess, so don't send
8838 it without being sure what state we are in first. "hard"
8839 is not a toggle, so that one is OK.
8841 SendToProgram("easy\n", cps);
8844 sprintf(buf, "ping %d\n", ++cps->lastPing);
8845 SendToProgram(buf, cps);
8847 cps->initDone = TRUE;
8852 StartChessProgram(cps)
8853 ChessProgramState *cps;
8858 if (appData.noChessProgram) return;
8859 cps->initDone = FALSE;
8861 if (strcmp(cps->host, "localhost") == 0) {
8862 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
8863 } else if (*appData.remoteShell == NULLCHAR) {
8864 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
8866 if (*appData.remoteUser == NULLCHAR) {
8867 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
8870 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
8871 cps->host, appData.remoteUser, cps->program);
8873 err = StartChildProcess(buf, "", &cps->pr);
8877 sprintf(buf, _("Startup failure on '%s'"), cps->program);
8878 DisplayFatalError(buf, err, 1);
8884 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
8885 if (cps->protocolVersion > 1) {
8886 sprintf(buf, "xboard\nprotover %d\n", cps->protocolVersion);
8887 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
8888 cps->comboCnt = 0; // and values of combo boxes
8889 SendToProgram(buf, cps);
8891 SendToProgram("xboard\n", cps);
8897 TwoMachinesEventIfReady P((void))
8899 if (first.lastPing != first.lastPong) {
8900 DisplayMessage("", _("Waiting for first chess program"));
8901 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
8904 if (second.lastPing != second.lastPong) {
8905 DisplayMessage("", _("Waiting for second chess program"));
8906 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
8914 NextMatchGame P((void))
8916 int index; /* [HGM] autoinc: step load index during match */
8918 if (*appData.loadGameFile != NULLCHAR) {
8919 index = appData.loadGameIndex;
8920 if(index < 0) { // [HGM] autoinc
8921 lastIndex = index = (index == -2 && first.twoMachinesColor[0] == 'b') ? lastIndex : lastIndex+1;
8922 if(appData.rewindIndex > 0 && index > appData.rewindIndex) lastIndex = index = 1;
8924 LoadGameFromFile(appData.loadGameFile,
8926 appData.loadGameFile, FALSE);
8927 } else if (*appData.loadPositionFile != NULLCHAR) {
8928 index = appData.loadPositionIndex;
8929 if(index < 0) { // [HGM] autoinc
8930 lastIndex = index = (index == -2 && first.twoMachinesColor[0] == 'b') ? lastIndex : lastIndex+1;
8931 if(appData.rewindIndex > 0 && index > appData.rewindIndex) lastIndex = index = 1;
8933 LoadPositionFromFile(appData.loadPositionFile,
8935 appData.loadPositionFile);
8937 TwoMachinesEventIfReady();
8940 void UserAdjudicationEvent( int result )
8942 ChessMove gameResult = GameIsDrawn;
8945 gameResult = WhiteWins;
8947 else if( result < 0 ) {
8948 gameResult = BlackWins;
8951 if( gameMode == TwoMachinesPlay ) {
8952 GameEnds( gameResult, "User adjudication", GE_XBOARD );
8957 // [HGM] save: calculate checksum of game to make games easily identifiable
8958 int StringCheckSum(char *s)
8961 if(s==NULL) return 0;
8962 while(*s) i = i*259 + *s++;
8969 for(i=backwardMostMove; i<forwardMostMove; i++) {
8970 sum += pvInfoList[i].depth;
8971 sum += StringCheckSum(parseList[i]);
8972 sum += StringCheckSum(commentList[i]);
8975 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
8976 return sum + StringCheckSum(commentList[i]);
8977 } // end of save patch
8980 GameEnds(result, resultDetails, whosays)
8982 char *resultDetails;
8985 GameMode nextGameMode;
8987 char buf[MSG_SIZ], popupRequested = 0;
8989 if(endingGame) return; /* [HGM] crash: forbid recursion */
8991 if(twoBoards) { // [HGM] dual: switch back to one board
8992 twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
8993 DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
8995 if (appData.debugMode) {
8996 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
8997 result, resultDetails ? resultDetails : "(null)", whosays);
9000 fromX = fromY = -1; // [HGM] abort any move the user is entering.
9002 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
9003 /* If we are playing on ICS, the server decides when the
9004 game is over, but the engine can offer to draw, claim
9008 if (appData.zippyPlay && first.initDone) {
9009 if (result == GameIsDrawn) {
9010 /* In case draw still needs to be claimed */
9011 SendToICS(ics_prefix);
9012 SendToICS("draw\n");
9013 } else if (StrCaseStr(resultDetails, "resign")) {
9014 SendToICS(ics_prefix);
9015 SendToICS("resign\n");
9019 endingGame = 0; /* [HGM] crash */
9023 /* If we're loading the game from a file, stop */
9024 if (whosays == GE_FILE) {
9025 (void) StopLoadGameTimer();
9029 /* Cancel draw offers */
9030 first.offeredDraw = second.offeredDraw = 0;
9032 /* If this is an ICS game, only ICS can really say it's done;
9033 if not, anyone can. */
9034 isIcsGame = (gameMode == IcsPlayingWhite ||
9035 gameMode == IcsPlayingBlack ||
9036 gameMode == IcsObserving ||
9037 gameMode == IcsExamining);
9039 if (!isIcsGame || whosays == GE_ICS) {
9040 /* OK -- not an ICS game, or ICS said it was done */
9042 if (!isIcsGame && !appData.noChessProgram)
9043 SetUserThinkingEnables();
9045 /* [HGM] if a machine claims the game end we verify this claim */
9046 if(gameMode == TwoMachinesPlay && appData.testClaims) {
9047 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
9049 ChessMove trueResult = (ChessMove) -1;
9051 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
9052 first.twoMachinesColor[0] :
9053 second.twoMachinesColor[0] ;
9055 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
9056 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
9057 /* [HGM] verify: engine mate claims accepted if they were flagged */
9058 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
9060 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
9061 /* [HGM] verify: engine mate claims accepted if they were flagged */
9062 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
9064 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
9065 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
9068 // now verify win claims, but not in drop games, as we don't understand those yet
9069 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
9070 || gameInfo.variant == VariantGreat) &&
9071 (result == WhiteWins && claimer == 'w' ||
9072 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
9073 if (appData.debugMode) {
9074 fprintf(debugFP, "result=%d sp=%d move=%d\n",
9075 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
9077 if(result != trueResult) {
9078 sprintf(buf, "False win claim: '%s'", resultDetails);
9079 result = claimer == 'w' ? BlackWins : WhiteWins;
9080 resultDetails = buf;
9083 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
9084 && (forwardMostMove <= backwardMostMove ||
9085 (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
9086 (claimer=='b')==(forwardMostMove&1))
9088 /* [HGM] verify: draws that were not flagged are false claims */
9089 sprintf(buf, "False draw claim: '%s'", resultDetails);
9090 result = claimer == 'w' ? BlackWins : WhiteWins;
9091 resultDetails = buf;
9093 /* (Claiming a loss is accepted no questions asked!) */
9095 /* [HGM] bare: don't allow bare King to win */
9096 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
9097 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
9098 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
9099 && result != GameIsDrawn)
9100 { int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
9101 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
9102 int p = (signed char)boards[forwardMostMove][i][j] - color;
9103 if(p >= 0 && p <= (int)WhiteKing) k++;
9105 if (appData.debugMode) {
9106 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
9107 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
9110 result = GameIsDrawn;
9111 sprintf(buf, "%s but bare king", resultDetails);
9112 resultDetails = buf;
9118 if(serverMoves != NULL && !loadFlag) { char c = '=';
9119 if(result==WhiteWins) c = '+';
9120 if(result==BlackWins) c = '-';
9121 if(resultDetails != NULL)
9122 fprintf(serverMoves, ";%c;%s\n", c, resultDetails);
9124 if (resultDetails != NULL) {
9125 gameInfo.result = result;
9126 gameInfo.resultDetails = StrSave(resultDetails);
9128 /* display last move only if game was not loaded from file */
9129 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
9130 DisplayMove(currentMove - 1);
9132 if (forwardMostMove != 0) {
9133 if (gameMode != PlayFromGameFile && gameMode != EditGame
9134 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
9136 if (*appData.saveGameFile != NULLCHAR) {
9137 SaveGameToFile(appData.saveGameFile, TRUE);
9138 } else if (appData.autoSaveGames) {
9141 if (*appData.savePositionFile != NULLCHAR) {
9142 SavePositionToFile(appData.savePositionFile);
9147 /* Tell program how game ended in case it is learning */
9148 /* [HGM] Moved this to after saving the PGN, just in case */
9149 /* engine died and we got here through time loss. In that */
9150 /* case we will get a fatal error writing the pipe, which */
9151 /* would otherwise lose us the PGN. */
9152 /* [HGM] crash: not needed anymore, but doesn't hurt; */
9153 /* output during GameEnds should never be fatal anymore */
9154 if (gameMode == MachinePlaysWhite ||
9155 gameMode == MachinePlaysBlack ||
9156 gameMode == TwoMachinesPlay ||
9157 gameMode == IcsPlayingWhite ||
9158 gameMode == IcsPlayingBlack ||
9159 gameMode == BeginningOfGame) {
9161 sprintf(buf, "result %s {%s}\n", PGNResult(result),
9163 if (first.pr != NoProc) {
9164 SendToProgram(buf, &first);
9166 if (second.pr != NoProc &&
9167 gameMode == TwoMachinesPlay) {
9168 SendToProgram(buf, &second);
9173 if (appData.icsActive) {
9174 if (appData.quietPlay &&
9175 (gameMode == IcsPlayingWhite ||
9176 gameMode == IcsPlayingBlack)) {
9177 SendToICS(ics_prefix);
9178 SendToICS("set shout 1\n");
9180 nextGameMode = IcsIdle;
9181 ics_user_moved = FALSE;
9182 /* clean up premove. It's ugly when the game has ended and the
9183 * premove highlights are still on the board.
9187 ClearPremoveHighlights();
9188 DrawPosition(FALSE, boards[currentMove]);
9190 if (whosays == GE_ICS) {
9193 if (gameMode == IcsPlayingWhite)
9195 else if(gameMode == IcsPlayingBlack)
9199 if (gameMode == IcsPlayingBlack)
9201 else if(gameMode == IcsPlayingWhite)
9208 PlayIcsUnfinishedSound();
9211 } else if (gameMode == EditGame ||
9212 gameMode == PlayFromGameFile ||
9213 gameMode == AnalyzeMode ||
9214 gameMode == AnalyzeFile) {
9215 nextGameMode = gameMode;
9217 nextGameMode = EndOfGame;
9222 nextGameMode = gameMode;
9225 if (appData.noChessProgram) {
9226 gameMode = nextGameMode;
9228 endingGame = 0; /* [HGM] crash */
9233 /* Put first chess program into idle state */
9234 if (first.pr != NoProc &&
9235 (gameMode == MachinePlaysWhite ||
9236 gameMode == MachinePlaysBlack ||
9237 gameMode == TwoMachinesPlay ||
9238 gameMode == IcsPlayingWhite ||
9239 gameMode == IcsPlayingBlack ||
9240 gameMode == BeginningOfGame)) {
9241 SendToProgram("force\n", &first);
9242 if (first.usePing) {
9244 sprintf(buf, "ping %d\n", ++first.lastPing);
9245 SendToProgram(buf, &first);
9248 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
9249 /* Kill off first chess program */
9250 if (first.isr != NULL)
9251 RemoveInputSource(first.isr);
9254 if (first.pr != NoProc) {
9256 DoSleep( appData.delayBeforeQuit );
9257 SendToProgram("quit\n", &first);
9258 DoSleep( appData.delayAfterQuit );
9259 DestroyChildProcess(first.pr, first.useSigterm);
9264 /* Put second chess program into idle state */
9265 if (second.pr != NoProc &&
9266 gameMode == TwoMachinesPlay) {
9267 SendToProgram("force\n", &second);
9268 if (second.usePing) {
9270 sprintf(buf, "ping %d\n", ++second.lastPing);
9271 SendToProgram(buf, &second);
9274 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
9275 /* Kill off second chess program */
9276 if (second.isr != NULL)
9277 RemoveInputSource(second.isr);
9280 if (second.pr != NoProc) {
9281 DoSleep( appData.delayBeforeQuit );
9282 SendToProgram("quit\n", &second);
9283 DoSleep( appData.delayAfterQuit );
9284 DestroyChildProcess(second.pr, second.useSigterm);
9289 if (matchMode && gameMode == TwoMachinesPlay) {
9292 if (first.twoMachinesColor[0] == 'w') {
9299 if (first.twoMachinesColor[0] == 'b') {
9308 if (matchGame < appData.matchGames) {
9310 if(appData.sameColorGames <= 1) { /* [HGM] alternate: suppress color swap */
9311 tmp = first.twoMachinesColor;
9312 first.twoMachinesColor = second.twoMachinesColor;
9313 second.twoMachinesColor = tmp;
9315 gameMode = nextGameMode;
9317 if(appData.matchPause>10000 || appData.matchPause<10)
9318 appData.matchPause = 10000; /* [HGM] make pause adjustable */
9319 ScheduleDelayedEvent(NextMatchGame, appData.matchPause);
9320 endingGame = 0; /* [HGM] crash */
9323 gameMode = nextGameMode;
9324 sprintf(buf, _("Match %s vs. %s: final score %d-%d-%d"),
9325 first.tidy, second.tidy,
9326 first.matchWins, second.matchWins,
9327 appData.matchGames - (first.matchWins + second.matchWins));
9328 popupRequested++; // [HGM] crash: postpone to after resetting endingGame
9331 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
9332 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
9334 gameMode = nextGameMode;
9336 endingGame = 0; /* [HGM] crash */
9337 if(popupRequested) DisplayFatalError(buf, 0, 0); // [HGM] crash: this call GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
9340 /* Assumes program was just initialized (initString sent).
9341 Leaves program in force mode. */
9343 FeedMovesToProgram(cps, upto)
9344 ChessProgramState *cps;
9349 if (appData.debugMode)
9350 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
9351 startedFromSetupPosition ? "position and " : "",
9352 backwardMostMove, upto, cps->which);
9353 if(currentlyInitializedVariant != gameInfo.variant) { char buf[MSG_SIZ];
9354 // [HGM] variantswitch: make engine aware of new variant
9355 if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL)
9356 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
9357 sprintf(buf, "variant %s\n", VariantName(gameInfo.variant));
9358 SendToProgram(buf, cps);
9359 currentlyInitializedVariant = gameInfo.variant;
9361 SendToProgram("force\n", cps);
9362 if (startedFromSetupPosition) {
9363 SendBoard(cps, backwardMostMove);
9364 if (appData.debugMode) {
9365 fprintf(debugFP, "feedMoves\n");
9368 for (i = backwardMostMove; i < upto; i++) {
9369 SendMoveToProgram(i, cps);
9375 ResurrectChessProgram()
9377 /* The chess program may have exited.
9378 If so, restart it and feed it all the moves made so far. */
9380 if (appData.noChessProgram || first.pr != NoProc) return;
9382 StartChessProgram(&first);
9383 InitChessProgram(&first, FALSE);
9384 FeedMovesToProgram(&first, currentMove);
9386 if (!first.sendTime) {
9387 /* can't tell gnuchess what its clock should read,
9388 so we bow to its notion. */
9390 timeRemaining[0][currentMove] = whiteTimeRemaining;
9391 timeRemaining[1][currentMove] = blackTimeRemaining;
9394 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
9395 appData.icsEngineAnalyze) && first.analysisSupport) {
9396 SendToProgram("analyze\n", &first);
9397 first.analyzing = TRUE;
9410 if (appData.debugMode) {
9411 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
9412 redraw, init, gameMode);
9414 CleanupTail(); // [HGM] vari: delete any stored variations
9415 pausing = pauseExamInvalid = FALSE;
9416 startedFromSetupPosition = blackPlaysFirst = FALSE;
9418 whiteFlag = blackFlag = FALSE;
9419 userOfferedDraw = FALSE;
9420 hintRequested = bookRequested = FALSE;
9421 first.maybeThinking = FALSE;
9422 second.maybeThinking = FALSE;
9423 first.bookSuspend = FALSE; // [HGM] book
9424 second.bookSuspend = FALSE;
9425 thinkOutput[0] = NULLCHAR;
9426 lastHint[0] = NULLCHAR;
9427 ClearGameInfo(&gameInfo);
9428 gameInfo.variant = StringToVariant(appData.variant);
9429 ics_user_moved = ics_clock_paused = FALSE;
9430 ics_getting_history = H_FALSE;
9432 white_holding[0] = black_holding[0] = NULLCHAR;
9433 ClearProgramStats();
9434 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
9438 flipView = appData.flipView;
9439 ClearPremoveHighlights();
9441 alarmSounded = FALSE;
9443 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
9444 if(appData.serverMovesName != NULL) {
9445 /* [HGM] prepare to make moves file for broadcasting */
9446 clock_t t = clock();
9447 if(serverMoves != NULL) fclose(serverMoves);
9448 serverMoves = fopen(appData.serverMovesName, "r");
9449 if(serverMoves != NULL) {
9450 fclose(serverMoves);
9451 /* delay 15 sec before overwriting, so all clients can see end */
9452 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
9454 serverMoves = fopen(appData.serverMovesName, "w");
9458 gameMode = BeginningOfGame;
9460 if(appData.icsActive) gameInfo.variant = VariantNormal;
9461 currentMove = forwardMostMove = backwardMostMove = 0;
9462 InitPosition(redraw);
9463 for (i = 0; i < MAX_MOVES; i++) {
9464 if (commentList[i] != NULL) {
9465 free(commentList[i]);
9466 commentList[i] = NULL;
9470 timeRemaining[0][0] = whiteTimeRemaining;
9471 timeRemaining[1][0] = blackTimeRemaining;
9472 if (first.pr == NULL) {
9473 StartChessProgram(&first);
9476 InitChessProgram(&first, startedFromSetupPosition);
9479 DisplayMessage("", "");
9480 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
9481 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
9488 if (!AutoPlayOneMove())
9490 if (matchMode || appData.timeDelay == 0)
9492 if (appData.timeDelay < 0 || gameMode == AnalyzeFile)
9494 StartLoadGameTimer((long)(1000.0 * appData.timeDelay));
9503 int fromX, fromY, toX, toY;
9505 if (appData.debugMode) {
9506 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
9509 if (gameMode != PlayFromGameFile)
9512 if (currentMove >= forwardMostMove) {
9513 gameMode = EditGame;
9516 /* [AS] Clear current move marker at the end of a game */
9517 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
9522 toX = moveList[currentMove][2] - AAA;
9523 toY = moveList[currentMove][3] - ONE;
9525 if (moveList[currentMove][1] == '@') {
9526 if (appData.highlightLastMove) {
9527 SetHighlights(-1, -1, toX, toY);
9530 fromX = moveList[currentMove][0] - AAA;
9531 fromY = moveList[currentMove][1] - ONE;
9533 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
9535 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
9537 if (appData.highlightLastMove) {
9538 SetHighlights(fromX, fromY, toX, toY);
9541 DisplayMove(currentMove);
9542 SendMoveToProgram(currentMove++, &first);
9543 DisplayBothClocks();
9544 DrawPosition(FALSE, boards[currentMove]);
9545 // [HGM] PV info: always display, routine tests if empty
9546 DisplayComment(currentMove - 1, commentList[currentMove]);
9552 LoadGameOneMove(readAhead)
9553 ChessMove readAhead;
9555 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
9556 char promoChar = NULLCHAR;
9561 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
9562 gameMode != AnalyzeMode && gameMode != Training) {
9567 yyboardindex = forwardMostMove;
9568 if (readAhead != (ChessMove)0) {
9569 moveType = readAhead;
9571 if (gameFileFP == NULL)
9573 moveType = (ChessMove) yylex();
9579 if (appData.debugMode)
9580 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
9583 /* append the comment but don't display it */
9584 AppendComment(currentMove, p, FALSE);
9587 case WhiteCapturesEnPassant:
9588 case BlackCapturesEnPassant:
9589 case WhitePromotionChancellor:
9590 case BlackPromotionChancellor:
9591 case WhitePromotionArchbishop:
9592 case BlackPromotionArchbishop:
9593 case WhitePromotionCentaur:
9594 case BlackPromotionCentaur:
9595 case WhitePromotionQueen:
9596 case BlackPromotionQueen:
9597 case WhitePromotionRook:
9598 case BlackPromotionRook:
9599 case WhitePromotionBishop:
9600 case BlackPromotionBishop:
9601 case WhitePromotionKnight:
9602 case BlackPromotionKnight:
9603 case WhitePromotionKing:
9604 case BlackPromotionKing:
9606 case WhiteKingSideCastle:
9607 case WhiteQueenSideCastle:
9608 case BlackKingSideCastle:
9609 case BlackQueenSideCastle:
9610 case WhiteKingSideCastleWild:
9611 case WhiteQueenSideCastleWild:
9612 case BlackKingSideCastleWild:
9613 case BlackQueenSideCastleWild:
9615 case WhiteHSideCastleFR:
9616 case WhiteASideCastleFR:
9617 case BlackHSideCastleFR:
9618 case BlackASideCastleFR:
9620 if (appData.debugMode)
9621 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
9622 fromX = currentMoveString[0] - AAA;
9623 fromY = currentMoveString[1] - ONE;
9624 toX = currentMoveString[2] - AAA;
9625 toY = currentMoveString[3] - ONE;
9626 promoChar = currentMoveString[4];
9631 if (appData.debugMode)
9632 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
9633 fromX = moveType == WhiteDrop ?
9634 (int) CharToPiece(ToUpper(currentMoveString[0])) :
9635 (int) CharToPiece(ToLower(currentMoveString[0]));
9637 toX = currentMoveString[2] - AAA;
9638 toY = currentMoveString[3] - ONE;
9644 case GameUnfinished:
9645 if (appData.debugMode)
9646 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
9647 p = strchr(yy_text, '{');
9648 if (p == NULL) p = strchr(yy_text, '(');
9651 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
9653 q = strchr(p, *p == '{' ? '}' : ')');
9654 if (q != NULL) *q = NULLCHAR;
9657 GameEnds(moveType, p, GE_FILE);
9659 if (cmailMsgLoaded) {
9661 flipView = WhiteOnMove(currentMove);
9662 if (moveType == GameUnfinished) flipView = !flipView;
9663 if (appData.debugMode)
9664 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
9668 case (ChessMove) 0: /* end of file */
9669 if (appData.debugMode)
9670 fprintf(debugFP, "Parser hit end of file\n");
9671 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
9677 if (WhiteOnMove(currentMove)) {
9678 GameEnds(BlackWins, "Black mates", GE_FILE);
9680 GameEnds(WhiteWins, "White mates", GE_FILE);
9684 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
9691 if (lastLoadGameStart == GNUChessGame) {
9692 /* GNUChessGames have numbers, but they aren't move numbers */
9693 if (appData.debugMode)
9694 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
9695 yy_text, (int) moveType);
9696 return LoadGameOneMove((ChessMove)0); /* tail recursion */
9698 /* else fall thru */
9703 /* Reached start of next game in file */
9704 if (appData.debugMode)
9705 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
9706 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
9712 if (WhiteOnMove(currentMove)) {
9713 GameEnds(BlackWins, "Black mates", GE_FILE);
9715 GameEnds(WhiteWins, "White mates", GE_FILE);
9719 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
9725 case PositionDiagram: /* should not happen; ignore */
9726 case ElapsedTime: /* ignore */
9727 case NAG: /* ignore */
9728 if (appData.debugMode)
9729 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
9730 yy_text, (int) moveType);
9731 return LoadGameOneMove((ChessMove)0); /* tail recursion */
9734 if (appData.testLegality) {
9735 if (appData.debugMode)
9736 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
9737 sprintf(move, _("Illegal move: %d.%s%s"),
9738 (forwardMostMove / 2) + 1,
9739 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
9740 DisplayError(move, 0);
9743 if (appData.debugMode)
9744 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
9745 yy_text, currentMoveString);
9746 fromX = currentMoveString[0] - AAA;
9747 fromY = currentMoveString[1] - ONE;
9748 toX = currentMoveString[2] - AAA;
9749 toY = currentMoveString[3] - ONE;
9750 promoChar = currentMoveString[4];
9755 if (appData.debugMode)
9756 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
9757 sprintf(move, _("Ambiguous move: %d.%s%s"),
9758 (forwardMostMove / 2) + 1,
9759 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
9760 DisplayError(move, 0);
9765 case ImpossibleMove:
9766 if (appData.debugMode)
9767 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
9768 sprintf(move, _("Illegal move: %d.%s%s"),
9769 (forwardMostMove / 2) + 1,
9770 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
9771 DisplayError(move, 0);
9777 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
9778 DrawPosition(FALSE, boards[currentMove]);
9779 DisplayBothClocks();
9780 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
9781 DisplayComment(currentMove - 1, commentList[currentMove]);
9783 (void) StopLoadGameTimer();
9785 cmailOldMove = forwardMostMove;
9788 /* currentMoveString is set as a side-effect of yylex */
9789 strcat(currentMoveString, "\n");
9790 strcpy(moveList[forwardMostMove], currentMoveString);
9792 thinkOutput[0] = NULLCHAR;
9793 MakeMove(fromX, fromY, toX, toY, promoChar);
9794 currentMove = forwardMostMove;
9799 /* Load the nth game from the given file */
9801 LoadGameFromFile(filename, n, title, useList)
9805 /*Boolean*/ int useList;
9810 if (strcmp(filename, "-") == 0) {
9814 f = fopen(filename, "rb");
9816 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
9817 DisplayError(buf, errno);
9821 if (fseek(f, 0, 0) == -1) {
9822 /* f is not seekable; probably a pipe */
9825 if (useList && n == 0) {
9826 int error = GameListBuild(f);
9828 DisplayError(_("Cannot build game list"), error);
9829 } else if (!ListEmpty(&gameList) &&
9830 ((ListGame *) gameList.tailPred)->number > 1) {
9831 GameListPopUp(f, title);
9838 return LoadGame(f, n, title, FALSE);
9843 MakeRegisteredMove()
9845 int fromX, fromY, toX, toY;
9847 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
9848 switch (cmailMoveType[lastLoadGameNumber - 1]) {
9851 if (appData.debugMode)
9852 fprintf(debugFP, "Restoring %s for game %d\n",
9853 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
9855 thinkOutput[0] = NULLCHAR;
9856 strcpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1]);
9857 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
9858 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
9859 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
9860 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
9861 promoChar = cmailMove[lastLoadGameNumber - 1][4];
9862 MakeMove(fromX, fromY, toX, toY, promoChar);
9863 ShowMove(fromX, fromY, toX, toY);
9865 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
9872 if (WhiteOnMove(currentMove)) {
9873 GameEnds(BlackWins, "Black mates", GE_PLAYER);
9875 GameEnds(WhiteWins, "White mates", GE_PLAYER);
9880 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
9887 if (WhiteOnMove(currentMove)) {
9888 GameEnds(BlackWins, "White resigns", GE_PLAYER);
9890 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
9895 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
9906 /* Wrapper around LoadGame for use when a Cmail message is loaded */
9908 CmailLoadGame(f, gameNumber, title, useList)
9916 if (gameNumber > nCmailGames) {
9917 DisplayError(_("No more games in this message"), 0);
9920 if (f == lastLoadGameFP) {
9921 int offset = gameNumber - lastLoadGameNumber;
9923 cmailMsg[0] = NULLCHAR;
9924 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
9925 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
9926 nCmailMovesRegistered--;
9928 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
9929 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
9930 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
9933 if (! RegisterMove()) return FALSE;
9937 retVal = LoadGame(f, gameNumber, title, useList);
9939 /* Make move registered during previous look at this game, if any */
9940 MakeRegisteredMove();
9942 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
9943 commentList[currentMove]
9944 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
9945 DisplayComment(currentMove - 1, commentList[currentMove]);
9951 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
9956 int gameNumber = lastLoadGameNumber + offset;
9957 if (lastLoadGameFP == NULL) {
9958 DisplayError(_("No game has been loaded yet"), 0);
9961 if (gameNumber <= 0) {
9962 DisplayError(_("Can't back up any further"), 0);
9965 if (cmailMsgLoaded) {
9966 return CmailLoadGame(lastLoadGameFP, gameNumber,
9967 lastLoadGameTitle, lastLoadGameUseList);
9969 return LoadGame(lastLoadGameFP, gameNumber,
9970 lastLoadGameTitle, lastLoadGameUseList);
9976 /* Load the nth game from open file f */
9978 LoadGame(f, gameNumber, title, useList)
9986 int gn = gameNumber;
9987 ListGame *lg = NULL;
9990 GameMode oldGameMode;
9991 VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
9993 if (appData.debugMode)
9994 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
9996 if (gameMode == Training )
9997 SetTrainingModeOff();
9999 oldGameMode = gameMode;
10000 if (gameMode != BeginningOfGame) {
10001 Reset(FALSE, TRUE);
10005 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
10006 fclose(lastLoadGameFP);
10010 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
10013 fseek(f, lg->offset, 0);
10014 GameListHighlight(gameNumber);
10018 DisplayError(_("Game number out of range"), 0);
10023 if (fseek(f, 0, 0) == -1) {
10024 if (f == lastLoadGameFP ?
10025 gameNumber == lastLoadGameNumber + 1 :
10029 DisplayError(_("Can't seek on game file"), 0);
10034 lastLoadGameFP = f;
10035 lastLoadGameNumber = gameNumber;
10036 strcpy(lastLoadGameTitle, title);
10037 lastLoadGameUseList = useList;
10041 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
10042 snprintf(buf, sizeof(buf), "%s vs. %s", lg->gameInfo.white,
10043 lg->gameInfo.black);
10045 } else if (*title != NULLCHAR) {
10046 if (gameNumber > 1) {
10047 sprintf(buf, "%s %d", title, gameNumber);
10050 DisplayTitle(title);
10054 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
10055 gameMode = PlayFromGameFile;
10059 currentMove = forwardMostMove = backwardMostMove = 0;
10060 CopyBoard(boards[0], initialPosition);
10064 * Skip the first gn-1 games in the file.
10065 * Also skip over anything that precedes an identifiable
10066 * start of game marker, to avoid being confused by
10067 * garbage at the start of the file. Currently
10068 * recognized start of game markers are the move number "1",
10069 * the pattern "gnuchess .* game", the pattern
10070 * "^[#;%] [^ ]* game file", and a PGN tag block.
10071 * A game that starts with one of the latter two patterns
10072 * will also have a move number 1, possibly
10073 * following a position diagram.
10074 * 5-4-02: Let's try being more lenient and allowing a game to
10075 * start with an unnumbered move. Does that break anything?
10077 cm = lastLoadGameStart = (ChessMove) 0;
10079 yyboardindex = forwardMostMove;
10080 cm = (ChessMove) yylex();
10082 case (ChessMove) 0:
10083 if (cmailMsgLoaded) {
10084 nCmailGames = CMAIL_MAX_GAMES - gn;
10087 DisplayError(_("Game not found in file"), 0);
10094 lastLoadGameStart = cm;
10097 case MoveNumberOne:
10098 switch (lastLoadGameStart) {
10103 case MoveNumberOne:
10104 case (ChessMove) 0:
10105 gn--; /* count this game */
10106 lastLoadGameStart = cm;
10115 switch (lastLoadGameStart) {
10118 case MoveNumberOne:
10119 case (ChessMove) 0:
10120 gn--; /* count this game */
10121 lastLoadGameStart = cm;
10124 lastLoadGameStart = cm; /* game counted already */
10132 yyboardindex = forwardMostMove;
10133 cm = (ChessMove) yylex();
10134 } while (cm == PGNTag || cm == Comment);
10141 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
10142 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
10143 != CMAIL_OLD_RESULT) {
10145 cmailResult[ CMAIL_MAX_GAMES
10146 - gn - 1] = CMAIL_OLD_RESULT;
10152 /* Only a NormalMove can be at the start of a game
10153 * without a position diagram. */
10154 if (lastLoadGameStart == (ChessMove) 0) {
10156 lastLoadGameStart = MoveNumberOne;
10165 if (appData.debugMode)
10166 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
10168 if (cm == XBoardGame) {
10169 /* Skip any header junk before position diagram and/or move 1 */
10171 yyboardindex = forwardMostMove;
10172 cm = (ChessMove) yylex();
10174 if (cm == (ChessMove) 0 ||
10175 cm == GNUChessGame || cm == XBoardGame) {
10176 /* Empty game; pretend end-of-file and handle later */
10177 cm = (ChessMove) 0;
10181 if (cm == MoveNumberOne || cm == PositionDiagram ||
10182 cm == PGNTag || cm == Comment)
10185 } else if (cm == GNUChessGame) {
10186 if (gameInfo.event != NULL) {
10187 free(gameInfo.event);
10189 gameInfo.event = StrSave(yy_text);
10192 startedFromSetupPosition = FALSE;
10193 while (cm == PGNTag) {
10194 if (appData.debugMode)
10195 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
10196 err = ParsePGNTag(yy_text, &gameInfo);
10197 if (!err) numPGNTags++;
10199 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
10200 if(gameInfo.variant != oldVariant) {
10201 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
10202 ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
10203 InitPosition(TRUE);
10204 oldVariant = gameInfo.variant;
10205 if (appData.debugMode)
10206 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
10210 if (gameInfo.fen != NULL) {
10211 Board initial_position;
10212 startedFromSetupPosition = TRUE;
10213 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
10215 DisplayError(_("Bad FEN position in file"), 0);
10218 CopyBoard(boards[0], initial_position);
10219 if (blackPlaysFirst) {
10220 currentMove = forwardMostMove = backwardMostMove = 1;
10221 CopyBoard(boards[1], initial_position);
10222 strcpy(moveList[0], "");
10223 strcpy(parseList[0], "");
10224 timeRemaining[0][1] = whiteTimeRemaining;
10225 timeRemaining[1][1] = blackTimeRemaining;
10226 if (commentList[0] != NULL) {
10227 commentList[1] = commentList[0];
10228 commentList[0] = NULL;
10231 currentMove = forwardMostMove = backwardMostMove = 0;
10233 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
10235 initialRulePlies = FENrulePlies;
10236 for( i=0; i< nrCastlingRights; i++ )
10237 initialRights[i] = initial_position[CASTLING][i];
10239 yyboardindex = forwardMostMove;
10240 free(gameInfo.fen);
10241 gameInfo.fen = NULL;
10244 yyboardindex = forwardMostMove;
10245 cm = (ChessMove) yylex();
10247 /* Handle comments interspersed among the tags */
10248 while (cm == Comment) {
10250 if (appData.debugMode)
10251 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10253 AppendComment(currentMove, p, FALSE);
10254 yyboardindex = forwardMostMove;
10255 cm = (ChessMove) yylex();
10259 /* don't rely on existence of Event tag since if game was
10260 * pasted from clipboard the Event tag may not exist
10262 if (numPGNTags > 0){
10264 if (gameInfo.variant == VariantNormal) {
10265 VariantClass v = StringToVariant(gameInfo.event);
10266 // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
10267 if(v < VariantShogi) gameInfo.variant = v;
10270 if( appData.autoDisplayTags ) {
10271 tags = PGNTags(&gameInfo);
10272 TagsPopUp(tags, CmailMsg());
10277 /* Make something up, but don't display it now */
10282 if (cm == PositionDiagram) {
10285 Board initial_position;
10287 if (appData.debugMode)
10288 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
10290 if (!startedFromSetupPosition) {
10292 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
10293 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
10303 initial_position[i][j++] = CharToPiece(*p);
10306 while (*p == ' ' || *p == '\t' ||
10307 *p == '\n' || *p == '\r') p++;
10309 if (strncmp(p, "black", strlen("black"))==0)
10310 blackPlaysFirst = TRUE;
10312 blackPlaysFirst = FALSE;
10313 startedFromSetupPosition = TRUE;
10315 CopyBoard(boards[0], initial_position);
10316 if (blackPlaysFirst) {
10317 currentMove = forwardMostMove = backwardMostMove = 1;
10318 CopyBoard(boards[1], initial_position);
10319 strcpy(moveList[0], "");
10320 strcpy(parseList[0], "");
10321 timeRemaining[0][1] = whiteTimeRemaining;
10322 timeRemaining[1][1] = blackTimeRemaining;
10323 if (commentList[0] != NULL) {
10324 commentList[1] = commentList[0];
10325 commentList[0] = NULL;
10328 currentMove = forwardMostMove = backwardMostMove = 0;
10331 yyboardindex = forwardMostMove;
10332 cm = (ChessMove) yylex();
10335 if (first.pr == NoProc) {
10336 StartChessProgram(&first);
10338 InitChessProgram(&first, FALSE);
10339 SendToProgram("force\n", &first);
10340 if (startedFromSetupPosition) {
10341 SendBoard(&first, forwardMostMove);
10342 if (appData.debugMode) {
10343 fprintf(debugFP, "Load Game\n");
10345 DisplayBothClocks();
10348 /* [HGM] server: flag to write setup moves in broadcast file as one */
10349 loadFlag = appData.suppressLoadMoves;
10351 while (cm == Comment) {
10353 if (appData.debugMode)
10354 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10356 AppendComment(currentMove, p, FALSE);
10357 yyboardindex = forwardMostMove;
10358 cm = (ChessMove) yylex();
10361 if ((cm == (ChessMove) 0 && lastLoadGameStart != (ChessMove) 0) ||
10362 cm == WhiteWins || cm == BlackWins ||
10363 cm == GameIsDrawn || cm == GameUnfinished) {
10364 DisplayMessage("", _("No moves in game"));
10365 if (cmailMsgLoaded) {
10366 if (appData.debugMode)
10367 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
10371 DrawPosition(FALSE, boards[currentMove]);
10372 DisplayBothClocks();
10373 gameMode = EditGame;
10380 // [HGM] PV info: routine tests if comment empty
10381 if (!matchMode && (pausing || appData.timeDelay != 0)) {
10382 DisplayComment(currentMove - 1, commentList[currentMove]);
10384 if (!matchMode && appData.timeDelay != 0)
10385 DrawPosition(FALSE, boards[currentMove]);
10387 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
10388 programStats.ok_to_send = 1;
10391 /* if the first token after the PGN tags is a move
10392 * and not move number 1, retrieve it from the parser
10394 if (cm != MoveNumberOne)
10395 LoadGameOneMove(cm);
10397 /* load the remaining moves from the file */
10398 while (LoadGameOneMove((ChessMove)0)) {
10399 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
10400 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
10403 /* rewind to the start of the game */
10404 currentMove = backwardMostMove;
10406 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
10408 if (oldGameMode == AnalyzeFile ||
10409 oldGameMode == AnalyzeMode) {
10410 AnalyzeFileEvent();
10413 if (matchMode || appData.timeDelay == 0) {
10415 gameMode = EditGame;
10417 } else if (appData.timeDelay > 0) {
10418 AutoPlayGameLoop();
10421 if (appData.debugMode)
10422 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
10424 loadFlag = 0; /* [HGM] true game starts */
10428 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
10430 ReloadPosition(offset)
10433 int positionNumber = lastLoadPositionNumber + offset;
10434 if (lastLoadPositionFP == NULL) {
10435 DisplayError(_("No position has been loaded yet"), 0);
10438 if (positionNumber <= 0) {
10439 DisplayError(_("Can't back up any further"), 0);
10442 return LoadPosition(lastLoadPositionFP, positionNumber,
10443 lastLoadPositionTitle);
10446 /* Load the nth position from the given file */
10448 LoadPositionFromFile(filename, n, title)
10456 if (strcmp(filename, "-") == 0) {
10457 return LoadPosition(stdin, n, "stdin");
10459 f = fopen(filename, "rb");
10461 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10462 DisplayError(buf, errno);
10465 return LoadPosition(f, n, title);
10470 /* Load the nth position from the given open file, and close it */
10472 LoadPosition(f, positionNumber, title)
10474 int positionNumber;
10477 char *p, line[MSG_SIZ];
10478 Board initial_position;
10479 int i, j, fenMode, pn;
10481 if (gameMode == Training )
10482 SetTrainingModeOff();
10484 if (gameMode != BeginningOfGame) {
10485 Reset(FALSE, TRUE);
10487 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
10488 fclose(lastLoadPositionFP);
10490 if (positionNumber == 0) positionNumber = 1;
10491 lastLoadPositionFP = f;
10492 lastLoadPositionNumber = positionNumber;
10493 strcpy(lastLoadPositionTitle, title);
10494 if (first.pr == NoProc) {
10495 StartChessProgram(&first);
10496 InitChessProgram(&first, FALSE);
10498 pn = positionNumber;
10499 if (positionNumber < 0) {
10500 /* Negative position number means to seek to that byte offset */
10501 if (fseek(f, -positionNumber, 0) == -1) {
10502 DisplayError(_("Can't seek on position file"), 0);
10507 if (fseek(f, 0, 0) == -1) {
10508 if (f == lastLoadPositionFP ?
10509 positionNumber == lastLoadPositionNumber + 1 :
10510 positionNumber == 1) {
10513 DisplayError(_("Can't seek on position file"), 0);
10518 /* See if this file is FEN or old-style xboard */
10519 if (fgets(line, MSG_SIZ, f) == NULL) {
10520 DisplayError(_("Position not found in file"), 0);
10523 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
10524 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
10527 if (fenMode || line[0] == '#') pn--;
10529 /* skip positions before number pn */
10530 if (fgets(line, MSG_SIZ, f) == NULL) {
10532 DisplayError(_("Position not found in file"), 0);
10535 if (fenMode || line[0] == '#') pn--;
10540 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
10541 DisplayError(_("Bad FEN position in file"), 0);
10545 (void) fgets(line, MSG_SIZ, f);
10546 (void) fgets(line, MSG_SIZ, f);
10548 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
10549 (void) fgets(line, MSG_SIZ, f);
10550 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
10553 initial_position[i][j++] = CharToPiece(*p);
10557 blackPlaysFirst = FALSE;
10559 (void) fgets(line, MSG_SIZ, f);
10560 if (strncmp(line, "black", strlen("black"))==0)
10561 blackPlaysFirst = TRUE;
10564 startedFromSetupPosition = TRUE;
10566 SendToProgram("force\n", &first);
10567 CopyBoard(boards[0], initial_position);
10568 if (blackPlaysFirst) {
10569 currentMove = forwardMostMove = backwardMostMove = 1;
10570 strcpy(moveList[0], "");
10571 strcpy(parseList[0], "");
10572 CopyBoard(boards[1], initial_position);
10573 DisplayMessage("", _("Black to play"));
10575 currentMove = forwardMostMove = backwardMostMove = 0;
10576 DisplayMessage("", _("White to play"));
10578 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
10579 SendBoard(&first, forwardMostMove);
10580 if (appData.debugMode) {
10582 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
10583 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
10584 fprintf(debugFP, "Load Position\n");
10587 if (positionNumber > 1) {
10588 sprintf(line, "%s %d", title, positionNumber);
10589 DisplayTitle(line);
10591 DisplayTitle(title);
10593 gameMode = EditGame;
10596 timeRemaining[0][1] = whiteTimeRemaining;
10597 timeRemaining[1][1] = blackTimeRemaining;
10598 DrawPosition(FALSE, boards[currentMove]);
10605 CopyPlayerNameIntoFileName(dest, src)
10608 while (*src != NULLCHAR && *src != ',') {
10613 *(*dest)++ = *src++;
10618 char *DefaultFileName(ext)
10621 static char def[MSG_SIZ];
10624 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
10626 CopyPlayerNameIntoFileName(&p, gameInfo.white);
10628 CopyPlayerNameIntoFileName(&p, gameInfo.black);
10637 /* Save the current game to the given file */
10639 SaveGameToFile(filename, append)
10646 if (strcmp(filename, "-") == 0) {
10647 return SaveGame(stdout, 0, NULL);
10649 f = fopen(filename, append ? "a" : "w");
10651 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10652 DisplayError(buf, errno);
10655 return SaveGame(f, 0, NULL);
10664 static char buf[MSG_SIZ];
10667 p = strchr(str, ' ');
10668 if (p == NULL) return str;
10669 strncpy(buf, str, p - str);
10670 buf[p - str] = NULLCHAR;
10674 #define PGN_MAX_LINE 75
10676 #define PGN_SIDE_WHITE 0
10677 #define PGN_SIDE_BLACK 1
10680 static int FindFirstMoveOutOfBook( int side )
10684 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
10685 int index = backwardMostMove;
10686 int has_book_hit = 0;
10688 if( (index % 2) != side ) {
10692 while( index < forwardMostMove ) {
10693 /* Check to see if engine is in book */
10694 int depth = pvInfoList[index].depth;
10695 int score = pvInfoList[index].score;
10701 else if( score == 0 && depth == 63 ) {
10702 in_book = 1; /* Zappa */
10704 else if( score == 2 && depth == 99 ) {
10705 in_book = 1; /* Abrok */
10708 has_book_hit += in_book;
10724 void GetOutOfBookInfo( char * buf )
10728 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
10730 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
10731 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
10735 if( oob[0] >= 0 || oob[1] >= 0 ) {
10736 for( i=0; i<2; i++ ) {
10740 if( i > 0 && oob[0] >= 0 ) {
10741 strcat( buf, " " );
10744 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
10745 sprintf( buf+strlen(buf), "%s%.2f",
10746 pvInfoList[idx].score >= 0 ? "+" : "",
10747 pvInfoList[idx].score / 100.0 );
10753 /* Save game in PGN style and close the file */
10758 int i, offset, linelen, newblock;
10762 int movelen, numlen, blank;
10763 char move_buffer[100]; /* [AS] Buffer for move+PV info */
10765 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
10767 tm = time((time_t *) NULL);
10769 PrintPGNTags(f, &gameInfo);
10771 if (backwardMostMove > 0 || startedFromSetupPosition) {
10772 char *fen = PositionToFEN(backwardMostMove, NULL);
10773 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
10774 fprintf(f, "\n{--------------\n");
10775 PrintPosition(f, backwardMostMove);
10776 fprintf(f, "--------------}\n");
10780 /* [AS] Out of book annotation */
10781 if( appData.saveOutOfBookInfo ) {
10784 GetOutOfBookInfo( buf );
10786 if( buf[0] != '\0' ) {
10787 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
10794 i = backwardMostMove;
10798 while (i < forwardMostMove) {
10799 /* Print comments preceding this move */
10800 if (commentList[i] != NULL) {
10801 if (linelen > 0) fprintf(f, "\n");
10802 fprintf(f, "%s", commentList[i]);
10807 /* Format move number */
10808 if ((i % 2) == 0) {
10809 sprintf(numtext, "%d.", (i - offset)/2 + 1);
10812 sprintf(numtext, "%d...", (i - offset)/2 + 1);
10814 numtext[0] = NULLCHAR;
10817 numlen = strlen(numtext);
10820 /* Print move number */
10821 blank = linelen > 0 && numlen > 0;
10822 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
10831 fprintf(f, "%s", numtext);
10835 strcpy(move_buffer, SavePart(parseList[i])); // [HGM] pgn: print move via buffer, so it can be edited
10836 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
10839 blank = linelen > 0 && movelen > 0;
10840 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
10849 fprintf(f, "%s", move_buffer);
10850 linelen += movelen;
10852 /* [AS] Add PV info if present */
10853 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
10854 /* [HGM] add time */
10855 char buf[MSG_SIZ]; int seconds;
10857 seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
10859 if( seconds <= 0) buf[0] = 0; else
10860 if( seconds < 30 ) sprintf(buf, " %3.1f%c", seconds/10., 0); else {
10861 seconds = (seconds + 4)/10; // round to full seconds
10862 if( seconds < 60 ) sprintf(buf, " %d%c", seconds, 0); else
10863 sprintf(buf, " %d:%02d%c", seconds/60, seconds%60, 0);
10866 sprintf( move_buffer, "{%s%.2f/%d%s}",
10867 pvInfoList[i].score >= 0 ? "+" : "",
10868 pvInfoList[i].score / 100.0,
10869 pvInfoList[i].depth,
10872 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
10874 /* Print score/depth */
10875 blank = linelen > 0 && movelen > 0;
10876 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
10885 fprintf(f, "%s", move_buffer);
10886 linelen += movelen;
10892 /* Start a new line */
10893 if (linelen > 0) fprintf(f, "\n");
10895 /* Print comments after last move */
10896 if (commentList[i] != NULL) {
10897 fprintf(f, "%s\n", commentList[i]);
10901 if (gameInfo.resultDetails != NULL &&
10902 gameInfo.resultDetails[0] != NULLCHAR) {
10903 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
10904 PGNResult(gameInfo.result));
10906 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
10910 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
10914 /* Save game in old style and close the file */
10916 SaveGameOldStyle(f)
10922 tm = time((time_t *) NULL);
10924 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
10927 if (backwardMostMove > 0 || startedFromSetupPosition) {
10928 fprintf(f, "\n[--------------\n");
10929 PrintPosition(f, backwardMostMove);
10930 fprintf(f, "--------------]\n");
10935 i = backwardMostMove;
10936 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
10938 while (i < forwardMostMove) {
10939 if (commentList[i] != NULL) {
10940 fprintf(f, "[%s]\n", commentList[i]);
10943 if ((i % 2) == 1) {
10944 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
10947 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
10949 if (commentList[i] != NULL) {
10953 if (i >= forwardMostMove) {
10957 fprintf(f, "%s\n", parseList[i]);
10962 if (commentList[i] != NULL) {
10963 fprintf(f, "[%s]\n", commentList[i]);
10966 /* This isn't really the old style, but it's close enough */
10967 if (gameInfo.resultDetails != NULL &&
10968 gameInfo.resultDetails[0] != NULLCHAR) {
10969 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
10970 gameInfo.resultDetails);
10972 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
10979 /* Save the current game to open file f and close the file */
10981 SaveGame(f, dummy, dummy2)
10986 if (gameMode == EditPosition) EditPositionDone(TRUE);
10987 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
10988 if (appData.oldSaveStyle)
10989 return SaveGameOldStyle(f);
10991 return SaveGamePGN(f);
10994 /* Save the current position to the given file */
10996 SavePositionToFile(filename)
11002 if (strcmp(filename, "-") == 0) {
11003 return SavePosition(stdout, 0, NULL);
11005 f = fopen(filename, "a");
11007 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
11008 DisplayError(buf, errno);
11011 SavePosition(f, 0, NULL);
11017 /* Save the current position to the given open file and close the file */
11019 SavePosition(f, dummy, dummy2)
11027 if (gameMode == EditPosition) EditPositionDone(TRUE);
11028 if (appData.oldSaveStyle) {
11029 tm = time((time_t *) NULL);
11031 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
11033 fprintf(f, "[--------------\n");
11034 PrintPosition(f, currentMove);
11035 fprintf(f, "--------------]\n");
11037 fen = PositionToFEN(currentMove, NULL);
11038 fprintf(f, "%s\n", fen);
11046 ReloadCmailMsgEvent(unregister)
11050 static char *inFilename = NULL;
11051 static char *outFilename;
11053 struct stat inbuf, outbuf;
11056 /* Any registered moves are unregistered if unregister is set, */
11057 /* i.e. invoked by the signal handler */
11059 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
11060 cmailMoveRegistered[i] = FALSE;
11061 if (cmailCommentList[i] != NULL) {
11062 free(cmailCommentList[i]);
11063 cmailCommentList[i] = NULL;
11066 nCmailMovesRegistered = 0;
11069 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
11070 cmailResult[i] = CMAIL_NOT_RESULT;
11074 if (inFilename == NULL) {
11075 /* Because the filenames are static they only get malloced once */
11076 /* and they never get freed */
11077 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
11078 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
11080 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
11081 sprintf(outFilename, "%s.out", appData.cmailGameName);
11084 status = stat(outFilename, &outbuf);
11086 cmailMailedMove = FALSE;
11088 status = stat(inFilename, &inbuf);
11089 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
11092 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
11093 counts the games, notes how each one terminated, etc.
11095 It would be nice to remove this kludge and instead gather all
11096 the information while building the game list. (And to keep it
11097 in the game list nodes instead of having a bunch of fixed-size
11098 parallel arrays.) Note this will require getting each game's
11099 termination from the PGN tags, as the game list builder does
11100 not process the game moves. --mann
11102 cmailMsgLoaded = TRUE;
11103 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
11105 /* Load first game in the file or popup game menu */
11106 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
11108 #endif /* !WIN32 */
11116 char string[MSG_SIZ];
11118 if ( cmailMailedMove
11119 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
11120 return TRUE; /* Allow free viewing */
11123 /* Unregister move to ensure that we don't leave RegisterMove */
11124 /* with the move registered when the conditions for registering no */
11126 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11127 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
11128 nCmailMovesRegistered --;
11130 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
11132 free(cmailCommentList[lastLoadGameNumber - 1]);
11133 cmailCommentList[lastLoadGameNumber - 1] = NULL;
11137 if (cmailOldMove == -1) {
11138 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
11142 if (currentMove > cmailOldMove + 1) {
11143 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
11147 if (currentMove < cmailOldMove) {
11148 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
11152 if (forwardMostMove > currentMove) {
11153 /* Silently truncate extra moves */
11157 if ( (currentMove == cmailOldMove + 1)
11158 || ( (currentMove == cmailOldMove)
11159 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
11160 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
11161 if (gameInfo.result != GameUnfinished) {
11162 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
11165 if (commentList[currentMove] != NULL) {
11166 cmailCommentList[lastLoadGameNumber - 1]
11167 = StrSave(commentList[currentMove]);
11169 strcpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1]);
11171 if (appData.debugMode)
11172 fprintf(debugFP, "Saving %s for game %d\n",
11173 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
11176 "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
11178 f = fopen(string, "w");
11179 if (appData.oldSaveStyle) {
11180 SaveGameOldStyle(f); /* also closes the file */
11182 sprintf(string, "%s.pos.out", appData.cmailGameName);
11183 f = fopen(string, "w");
11184 SavePosition(f, 0, NULL); /* also closes the file */
11186 fprintf(f, "{--------------\n");
11187 PrintPosition(f, currentMove);
11188 fprintf(f, "--------------}\n\n");
11190 SaveGame(f, 0, NULL); /* also closes the file*/
11193 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
11194 nCmailMovesRegistered ++;
11195 } else if (nCmailGames == 1) {
11196 DisplayError(_("You have not made a move yet"), 0);
11207 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
11208 FILE *commandOutput;
11209 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
11210 int nBytes = 0; /* Suppress warnings on uninitialized variables */
11216 if (! cmailMsgLoaded) {
11217 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
11221 if (nCmailGames == nCmailResults) {
11222 DisplayError(_("No unfinished games"), 0);
11226 #if CMAIL_PROHIBIT_REMAIL
11227 if (cmailMailedMove) {
11228 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);
11229 DisplayError(msg, 0);
11234 if (! (cmailMailedMove || RegisterMove())) return;
11236 if ( cmailMailedMove
11237 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
11238 sprintf(string, partCommandString,
11239 appData.debugMode ? " -v" : "", appData.cmailGameName);
11240 commandOutput = popen(string, "r");
11242 if (commandOutput == NULL) {
11243 DisplayError(_("Failed to invoke cmail"), 0);
11245 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
11246 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
11248 if (nBuffers > 1) {
11249 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
11250 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
11251 nBytes = MSG_SIZ - 1;
11253 (void) memcpy(msg, buffer, nBytes);
11255 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
11257 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
11258 cmailMailedMove = TRUE; /* Prevent >1 moves */
11261 for (i = 0; i < nCmailGames; i ++) {
11262 if (cmailResult[i] == CMAIL_NOT_RESULT) {
11267 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
11269 sprintf(buffer, "%s/%s.%s.archive",
11271 appData.cmailGameName,
11273 LoadGameFromFile(buffer, 1, buffer, FALSE);
11274 cmailMsgLoaded = FALSE;
11278 DisplayInformation(msg);
11279 pclose(commandOutput);
11282 if ((*cmailMsg) != '\0') {
11283 DisplayInformation(cmailMsg);
11288 #endif /* !WIN32 */
11297 int prependComma = 0;
11299 char string[MSG_SIZ]; /* Space for game-list */
11302 if (!cmailMsgLoaded) return "";
11304 if (cmailMailedMove) {
11305 sprintf(cmailMsg, _("Waiting for reply from opponent\n"));
11307 /* Create a list of games left */
11308 sprintf(string, "[");
11309 for (i = 0; i < nCmailGames; i ++) {
11310 if (! ( cmailMoveRegistered[i]
11311 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
11312 if (prependComma) {
11313 sprintf(number, ",%d", i + 1);
11315 sprintf(number, "%d", i + 1);
11319 strcat(string, number);
11322 strcat(string, "]");
11324 if (nCmailMovesRegistered + nCmailResults == 0) {
11325 switch (nCmailGames) {
11328 _("Still need to make move for game\n"));
11333 _("Still need to make moves for both games\n"));
11338 _("Still need to make moves for all %d games\n"),
11343 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
11346 _("Still need to make a move for game %s\n"),
11351 if (nCmailResults == nCmailGames) {
11352 sprintf(cmailMsg, _("No unfinished games\n"));
11354 sprintf(cmailMsg, _("Ready to send mail\n"));
11360 _("Still need to make moves for games %s\n"),
11372 if (gameMode == Training)
11373 SetTrainingModeOff();
11376 cmailMsgLoaded = FALSE;
11377 if (appData.icsActive) {
11378 SendToICS(ics_prefix);
11379 SendToICS("refresh\n");
11389 /* Give up on clean exit */
11393 /* Keep trying for clean exit */
11397 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
11399 if (telnetISR != NULL) {
11400 RemoveInputSource(telnetISR);
11402 if (icsPR != NoProc) {
11403 DestroyChildProcess(icsPR, TRUE);
11406 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
11407 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
11409 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
11410 /* make sure this other one finishes before killing it! */
11411 if(endingGame) { int count = 0;
11412 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
11413 while(endingGame && count++ < 10) DoSleep(1);
11414 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
11417 /* Kill off chess programs */
11418 if (first.pr != NoProc) {
11421 DoSleep( appData.delayBeforeQuit );
11422 SendToProgram("quit\n", &first);
11423 DoSleep( appData.delayAfterQuit );
11424 DestroyChildProcess(first.pr, 10 /* [AS] first.useSigterm */ );
11426 if (second.pr != NoProc) {
11427 DoSleep( appData.delayBeforeQuit );
11428 SendToProgram("quit\n", &second);
11429 DoSleep( appData.delayAfterQuit );
11430 DestroyChildProcess(second.pr, 10 /* [AS] second.useSigterm */ );
11432 if (first.isr != NULL) {
11433 RemoveInputSource(first.isr);
11435 if (second.isr != NULL) {
11436 RemoveInputSource(second.isr);
11439 ShutDownFrontEnd();
11446 if (appData.debugMode)
11447 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
11451 if (gameMode == MachinePlaysWhite ||
11452 gameMode == MachinePlaysBlack) {
11455 DisplayBothClocks();
11457 if (gameMode == PlayFromGameFile) {
11458 if (appData.timeDelay >= 0)
11459 AutoPlayGameLoop();
11460 } else if (gameMode == IcsExamining && pauseExamInvalid) {
11461 Reset(FALSE, TRUE);
11462 SendToICS(ics_prefix);
11463 SendToICS("refresh\n");
11464 } else if (currentMove < forwardMostMove) {
11465 ForwardInner(forwardMostMove);
11467 pauseExamInvalid = FALSE;
11469 switch (gameMode) {
11473 pauseExamForwardMostMove = forwardMostMove;
11474 pauseExamInvalid = FALSE;
11477 case IcsPlayingWhite:
11478 case IcsPlayingBlack:
11482 case PlayFromGameFile:
11483 (void) StopLoadGameTimer();
11487 case BeginningOfGame:
11488 if (appData.icsActive) return;
11489 /* else fall through */
11490 case MachinePlaysWhite:
11491 case MachinePlaysBlack:
11492 case TwoMachinesPlay:
11493 if (forwardMostMove == 0)
11494 return; /* don't pause if no one has moved */
11495 if ((gameMode == MachinePlaysWhite &&
11496 !WhiteOnMove(forwardMostMove)) ||
11497 (gameMode == MachinePlaysBlack &&
11498 WhiteOnMove(forwardMostMove))) {
11511 char title[MSG_SIZ];
11513 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
11514 strcpy(title, _("Edit comment"));
11516 sprintf(title, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
11517 WhiteOnMove(currentMove - 1) ? " " : ".. ",
11518 parseList[currentMove - 1]);
11521 EditCommentPopUp(currentMove, title, commentList[currentMove]);
11528 char *tags = PGNTags(&gameInfo);
11529 EditTagsPopUp(tags);
11536 if (appData.noChessProgram || gameMode == AnalyzeMode)
11539 if (gameMode != AnalyzeFile) {
11540 if (!appData.icsEngineAnalyze) {
11542 if (gameMode != EditGame) return;
11544 ResurrectChessProgram();
11545 SendToProgram("analyze\n", &first);
11546 first.analyzing = TRUE;
11547 /*first.maybeThinking = TRUE;*/
11548 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11549 EngineOutputPopUp();
11551 if (!appData.icsEngineAnalyze) gameMode = AnalyzeMode;
11556 StartAnalysisClock();
11557 GetTimeMark(&lastNodeCountTime);
11564 if (appData.noChessProgram || gameMode == AnalyzeFile)
11567 if (gameMode != AnalyzeMode) {
11569 if (gameMode != EditGame) return;
11570 ResurrectChessProgram();
11571 SendToProgram("analyze\n", &first);
11572 first.analyzing = TRUE;
11573 /*first.maybeThinking = TRUE;*/
11574 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11575 EngineOutputPopUp();
11577 gameMode = AnalyzeFile;
11582 StartAnalysisClock();
11583 GetTimeMark(&lastNodeCountTime);
11588 MachineWhiteEvent()
11591 char *bookHit = NULL;
11593 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
11597 if (gameMode == PlayFromGameFile ||
11598 gameMode == TwoMachinesPlay ||
11599 gameMode == Training ||
11600 gameMode == AnalyzeMode ||
11601 gameMode == EndOfGame)
11604 if (gameMode == EditPosition)
11605 EditPositionDone(TRUE);
11607 if (!WhiteOnMove(currentMove)) {
11608 DisplayError(_("It is not White's turn"), 0);
11612 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
11615 if (gameMode == EditGame || gameMode == AnalyzeMode ||
11616 gameMode == AnalyzeFile)
11619 ResurrectChessProgram(); /* in case it isn't running */
11620 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
11621 gameMode = MachinePlaysWhite;
11624 gameMode = MachinePlaysWhite;
11628 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
11630 if (first.sendName) {
11631 sprintf(buf, "name %s\n", gameInfo.black);
11632 SendToProgram(buf, &first);
11634 if (first.sendTime) {
11635 if (first.useColors) {
11636 SendToProgram("black\n", &first); /*gnu kludge*/
11638 SendTimeRemaining(&first, TRUE);
11640 if (first.useColors) {
11641 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
11643 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
11644 SetMachineThinkingEnables();
11645 first.maybeThinking = TRUE;
11649 if (appData.autoFlipView && !flipView) {
11650 flipView = !flipView;
11651 DrawPosition(FALSE, NULL);
11652 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
11655 if(bookHit) { // [HGM] book: simulate book reply
11656 static char bookMove[MSG_SIZ]; // a bit generous?
11658 programStats.nodes = programStats.depth = programStats.time =
11659 programStats.score = programStats.got_only_move = 0;
11660 sprintf(programStats.movelist, "%s (xbook)", bookHit);
11662 strcpy(bookMove, "move ");
11663 strcat(bookMove, bookHit);
11664 HandleMachineMove(bookMove, &first);
11669 MachineBlackEvent()
11672 char *bookHit = NULL;
11674 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
11678 if (gameMode == PlayFromGameFile ||
11679 gameMode == TwoMachinesPlay ||
11680 gameMode == Training ||
11681 gameMode == AnalyzeMode ||
11682 gameMode == EndOfGame)
11685 if (gameMode == EditPosition)
11686 EditPositionDone(TRUE);
11688 if (WhiteOnMove(currentMove)) {
11689 DisplayError(_("It is not Black's turn"), 0);
11693 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
11696 if (gameMode == EditGame || gameMode == AnalyzeMode ||
11697 gameMode == AnalyzeFile)
11700 ResurrectChessProgram(); /* in case it isn't running */
11701 gameMode = MachinePlaysBlack;
11705 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
11707 if (first.sendName) {
11708 sprintf(buf, "name %s\n", gameInfo.white);
11709 SendToProgram(buf, &first);
11711 if (first.sendTime) {
11712 if (first.useColors) {
11713 SendToProgram("white\n", &first); /*gnu kludge*/
11715 SendTimeRemaining(&first, FALSE);
11717 if (first.useColors) {
11718 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
11720 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
11721 SetMachineThinkingEnables();
11722 first.maybeThinking = TRUE;
11725 if (appData.autoFlipView && flipView) {
11726 flipView = !flipView;
11727 DrawPosition(FALSE, NULL);
11728 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
11730 if(bookHit) { // [HGM] book: simulate book reply
11731 static char bookMove[MSG_SIZ]; // a bit generous?
11733 programStats.nodes = programStats.depth = programStats.time =
11734 programStats.score = programStats.got_only_move = 0;
11735 sprintf(programStats.movelist, "%s (xbook)", bookHit);
11737 strcpy(bookMove, "move ");
11738 strcat(bookMove, bookHit);
11739 HandleMachineMove(bookMove, &first);
11745 DisplayTwoMachinesTitle()
11748 if (appData.matchGames > 0) {
11749 if (first.twoMachinesColor[0] == 'w') {
11750 sprintf(buf, "%s vs. %s (%d-%d-%d)",
11751 gameInfo.white, gameInfo.black,
11752 first.matchWins, second.matchWins,
11753 matchGame - 1 - (first.matchWins + second.matchWins));
11755 sprintf(buf, "%s vs. %s (%d-%d-%d)",
11756 gameInfo.white, gameInfo.black,
11757 second.matchWins, first.matchWins,
11758 matchGame - 1 - (first.matchWins + second.matchWins));
11761 sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black);
11767 TwoMachinesEvent P((void))
11771 ChessProgramState *onmove;
11772 char *bookHit = NULL;
11774 if (appData.noChessProgram) return;
11776 switch (gameMode) {
11777 case TwoMachinesPlay:
11779 case MachinePlaysWhite:
11780 case MachinePlaysBlack:
11781 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
11782 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
11786 case BeginningOfGame:
11787 case PlayFromGameFile:
11790 if (gameMode != EditGame) return;
11793 EditPositionDone(TRUE);
11804 // forwardMostMove = currentMove;
11805 TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
11806 ResurrectChessProgram(); /* in case first program isn't running */
11808 if (second.pr == NULL) {
11809 StartChessProgram(&second);
11810 if (second.protocolVersion == 1) {
11811 TwoMachinesEventIfReady();
11813 /* kludge: allow timeout for initial "feature" command */
11815 DisplayMessage("", _("Starting second chess program"));
11816 ScheduleDelayedEvent(TwoMachinesEventIfReady, FEATURE_TIMEOUT);
11820 DisplayMessage("", "");
11821 InitChessProgram(&second, FALSE);
11822 SendToProgram("force\n", &second);
11823 if (startedFromSetupPosition) {
11824 SendBoard(&second, backwardMostMove);
11825 if (appData.debugMode) {
11826 fprintf(debugFP, "Two Machines\n");
11829 for (i = backwardMostMove; i < forwardMostMove; i++) {
11830 SendMoveToProgram(i, &second);
11833 gameMode = TwoMachinesPlay;
11837 DisplayTwoMachinesTitle();
11839 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
11845 SendToProgram(first.computerString, &first);
11846 if (first.sendName) {
11847 sprintf(buf, "name %s\n", second.tidy);
11848 SendToProgram(buf, &first);
11850 SendToProgram(second.computerString, &second);
11851 if (second.sendName) {
11852 sprintf(buf, "name %s\n", first.tidy);
11853 SendToProgram(buf, &second);
11857 if (!first.sendTime || !second.sendTime) {
11858 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
11859 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
11861 if (onmove->sendTime) {
11862 if (onmove->useColors) {
11863 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
11865 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
11867 if (onmove->useColors) {
11868 SendToProgram(onmove->twoMachinesColor, onmove);
11870 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
11871 // SendToProgram("go\n", onmove);
11872 onmove->maybeThinking = TRUE;
11873 SetMachineThinkingEnables();
11877 if(bookHit) { // [HGM] book: simulate book reply
11878 static char bookMove[MSG_SIZ]; // a bit generous?
11880 programStats.nodes = programStats.depth = programStats.time =
11881 programStats.score = programStats.got_only_move = 0;
11882 sprintf(programStats.movelist, "%s (xbook)", bookHit);
11884 strcpy(bookMove, "move ");
11885 strcat(bookMove, bookHit);
11886 savedMessage = bookMove; // args for deferred call
11887 savedState = onmove;
11888 ScheduleDelayedEvent(DeferredBookMove, 1);
11895 if (gameMode == Training) {
11896 SetTrainingModeOff();
11897 gameMode = PlayFromGameFile;
11898 DisplayMessage("", _("Training mode off"));
11900 gameMode = Training;
11901 animateTraining = appData.animate;
11903 /* make sure we are not already at the end of the game */
11904 if (currentMove < forwardMostMove) {
11905 SetTrainingModeOn();
11906 DisplayMessage("", _("Training mode on"));
11908 gameMode = PlayFromGameFile;
11909 DisplayError(_("Already at end of game"), 0);
11918 if (!appData.icsActive) return;
11919 switch (gameMode) {
11920 case IcsPlayingWhite:
11921 case IcsPlayingBlack:
11924 case BeginningOfGame:
11932 EditPositionDone(TRUE);
11945 gameMode = IcsIdle;
11956 switch (gameMode) {
11958 SetTrainingModeOff();
11960 case MachinePlaysWhite:
11961 case MachinePlaysBlack:
11962 case BeginningOfGame:
11963 SendToProgram("force\n", &first);
11964 SetUserThinkingEnables();
11966 case PlayFromGameFile:
11967 (void) StopLoadGameTimer();
11968 if (gameFileFP != NULL) {
11973 EditPositionDone(TRUE);
11978 SendToProgram("force\n", &first);
11980 case TwoMachinesPlay:
11981 GameEnds((ChessMove) 0, NULL, GE_PLAYER);
11982 ResurrectChessProgram();
11983 SetUserThinkingEnables();
11986 ResurrectChessProgram();
11988 case IcsPlayingBlack:
11989 case IcsPlayingWhite:
11990 DisplayError(_("Warning: You are still playing a game"), 0);
11993 DisplayError(_("Warning: You are still observing a game"), 0);
11996 DisplayError(_("Warning: You are still examining a game"), 0);
12007 first.offeredDraw = second.offeredDraw = 0;
12009 if (gameMode == PlayFromGameFile) {
12010 whiteTimeRemaining = timeRemaining[0][currentMove];
12011 blackTimeRemaining = timeRemaining[1][currentMove];
12015 if (gameMode == MachinePlaysWhite ||
12016 gameMode == MachinePlaysBlack ||
12017 gameMode == TwoMachinesPlay ||
12018 gameMode == EndOfGame) {
12019 i = forwardMostMove;
12020 while (i > currentMove) {
12021 SendToProgram("undo\n", &first);
12024 whiteTimeRemaining = timeRemaining[0][currentMove];
12025 blackTimeRemaining = timeRemaining[1][currentMove];
12026 DisplayBothClocks();
12027 if (whiteFlag || blackFlag) {
12028 whiteFlag = blackFlag = 0;
12033 gameMode = EditGame;
12040 EditPositionEvent()
12042 if (gameMode == EditPosition) {
12048 if (gameMode != EditGame) return;
12050 gameMode = EditPosition;
12053 if (currentMove > 0)
12054 CopyBoard(boards[0], boards[currentMove]);
12056 blackPlaysFirst = !WhiteOnMove(currentMove);
12058 currentMove = forwardMostMove = backwardMostMove = 0;
12059 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12066 /* [DM] icsEngineAnalyze - possible call from other functions */
12067 if (appData.icsEngineAnalyze) {
12068 appData.icsEngineAnalyze = FALSE;
12070 DisplayMessage("",_("Close ICS engine analyze..."));
12072 if (first.analysisSupport && first.analyzing) {
12073 SendToProgram("exit\n", &first);
12074 first.analyzing = FALSE;
12076 thinkOutput[0] = NULLCHAR;
12080 EditPositionDone(Boolean fakeRights)
12082 int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
12084 startedFromSetupPosition = TRUE;
12085 InitChessProgram(&first, FALSE);
12086 if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
12087 boards[0][EP_STATUS] = EP_NONE;
12088 boards[0][CASTLING][2] = boards[0][CASTLING][5] = BOARD_WIDTH>>1;
12089 if(boards[0][0][BOARD_WIDTH>>1] == king) {
12090 boards[0][CASTLING][1] = boards[0][0][BOARD_LEFT] == WhiteRook ? 0 : NoRights;
12091 boards[0][CASTLING][0] = boards[0][0][BOARD_RGHT-1] == WhiteRook ? BOARD_RGHT-1 : NoRights;
12092 } else boards[0][CASTLING][2] = NoRights;
12093 if(boards[0][BOARD_HEIGHT-1][BOARD_WIDTH>>1] == WHITE_TO_BLACK king) {
12094 boards[0][CASTLING][4] = boards[0][BOARD_HEIGHT-1][BOARD_LEFT] == BlackRook ? 0 : NoRights;
12095 boards[0][CASTLING][3] = boards[0][BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook ? BOARD_RGHT-1 : NoRights;
12096 } else boards[0][CASTLING][5] = NoRights;
12098 SendToProgram("force\n", &first);
12099 if (blackPlaysFirst) {
12100 strcpy(moveList[0], "");
12101 strcpy(parseList[0], "");
12102 currentMove = forwardMostMove = backwardMostMove = 1;
12103 CopyBoard(boards[1], boards[0]);
12105 currentMove = forwardMostMove = backwardMostMove = 0;
12107 SendBoard(&first, forwardMostMove);
12108 if (appData.debugMode) {
12109 fprintf(debugFP, "EditPosDone\n");
12112 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
12113 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
12114 gameMode = EditGame;
12116 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12117 ClearHighlights(); /* [AS] */
12120 /* Pause for `ms' milliseconds */
12121 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
12131 } while (SubtractTimeMarks(&m2, &m1) < ms);
12134 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
12136 SendMultiLineToICS(buf)
12139 char temp[MSG_SIZ+1], *p;
12146 strncpy(temp, buf, len);
12151 if (*p == '\n' || *p == '\r')
12156 strcat(temp, "\n");
12158 SendToPlayer(temp, strlen(temp));
12162 SetWhiteToPlayEvent()
12164 if (gameMode == EditPosition) {
12165 blackPlaysFirst = FALSE;
12166 DisplayBothClocks(); /* works because currentMove is 0 */
12167 } else if (gameMode == IcsExamining) {
12168 SendToICS(ics_prefix);
12169 SendToICS("tomove white\n");
12174 SetBlackToPlayEvent()
12176 if (gameMode == EditPosition) {
12177 blackPlaysFirst = TRUE;
12178 currentMove = 1; /* kludge */
12179 DisplayBothClocks();
12181 } else if (gameMode == IcsExamining) {
12182 SendToICS(ics_prefix);
12183 SendToICS("tomove black\n");
12188 EditPositionMenuEvent(selection, x, y)
12189 ChessSquare selection;
12193 ChessSquare piece = boards[0][y][x];
12195 if (gameMode != EditPosition && gameMode != IcsExamining) return;
12197 switch (selection) {
12199 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
12200 SendToICS(ics_prefix);
12201 SendToICS("bsetup clear\n");
12202 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
12203 SendToICS(ics_prefix);
12204 SendToICS("clearboard\n");
12206 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
12207 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
12208 for (y = 0; y < BOARD_HEIGHT; y++) {
12209 if (gameMode == IcsExamining) {
12210 if (boards[currentMove][y][x] != EmptySquare) {
12211 sprintf(buf, "%sx@%c%c\n", ics_prefix,
12216 boards[0][y][x] = p;
12221 if (gameMode == EditPosition) {
12222 DrawPosition(FALSE, boards[0]);
12227 SetWhiteToPlayEvent();
12231 SetBlackToPlayEvent();
12235 if (gameMode == IcsExamining) {
12236 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
12237 sprintf(buf, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
12240 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
12241 if(x == BOARD_LEFT-2) {
12242 if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
12243 boards[0][y][1] = 0;
12245 if(x == BOARD_RGHT+1) {
12246 if(y >= gameInfo.holdingsSize) break;
12247 boards[0][y][BOARD_WIDTH-2] = 0;
12250 boards[0][y][x] = EmptySquare;
12251 DrawPosition(FALSE, boards[0]);
12256 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
12257 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
12258 selection = (ChessSquare) (PROMOTED piece);
12259 } else if(piece == EmptySquare) selection = WhiteSilver;
12260 else selection = (ChessSquare)((int)piece - 1);
12264 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
12265 piece > (int)BlackMan && piece <= (int)BlackKing ) {
12266 selection = (ChessSquare) (DEMOTED piece);
12267 } else if(piece == EmptySquare) selection = BlackSilver;
12268 else selection = (ChessSquare)((int)piece + 1);
12273 if(gameInfo.variant == VariantShatranj ||
12274 gameInfo.variant == VariantXiangqi ||
12275 gameInfo.variant == VariantCourier ||
12276 gameInfo.variant == VariantMakruk )
12277 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
12282 if(gameInfo.variant == VariantXiangqi)
12283 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
12284 if(gameInfo.variant == VariantKnightmate)
12285 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
12288 if (gameMode == IcsExamining) {
12289 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
12290 sprintf(buf, "%s%c@%c%c\n", ics_prefix,
12291 PieceToChar(selection), AAA + x, ONE + y);
12294 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
12296 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
12297 n = PieceToNumber(selection - BlackPawn);
12298 if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
12299 boards[0][BOARD_HEIGHT-1-n][0] = selection;
12300 boards[0][BOARD_HEIGHT-1-n][1]++;
12302 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
12303 n = PieceToNumber(selection);
12304 if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
12305 boards[0][n][BOARD_WIDTH-1] = selection;
12306 boards[0][n][BOARD_WIDTH-2]++;
12309 boards[0][y][x] = selection;
12310 DrawPosition(TRUE, boards[0]);
12318 DropMenuEvent(selection, x, y)
12319 ChessSquare selection;
12322 ChessMove moveType;
12324 switch (gameMode) {
12325 case IcsPlayingWhite:
12326 case MachinePlaysBlack:
12327 if (!WhiteOnMove(currentMove)) {
12328 DisplayMoveError(_("It is Black's turn"));
12331 moveType = WhiteDrop;
12333 case IcsPlayingBlack:
12334 case MachinePlaysWhite:
12335 if (WhiteOnMove(currentMove)) {
12336 DisplayMoveError(_("It is White's turn"));
12339 moveType = BlackDrop;
12342 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
12348 if (moveType == BlackDrop && selection < BlackPawn) {
12349 selection = (ChessSquare) ((int) selection
12350 + (int) BlackPawn - (int) WhitePawn);
12352 if (boards[currentMove][y][x] != EmptySquare) {
12353 DisplayMoveError(_("That square is occupied"));
12357 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
12363 /* Accept a pending offer of any kind from opponent */
12365 if (appData.icsActive) {
12366 SendToICS(ics_prefix);
12367 SendToICS("accept\n");
12368 } else if (cmailMsgLoaded) {
12369 if (currentMove == cmailOldMove &&
12370 commentList[cmailOldMove] != NULL &&
12371 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12372 "Black offers a draw" : "White offers a draw")) {
12374 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12375 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
12377 DisplayError(_("There is no pending offer on this move"), 0);
12378 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12381 /* Not used for offers from chess program */
12388 /* Decline a pending offer of any kind from opponent */
12390 if (appData.icsActive) {
12391 SendToICS(ics_prefix);
12392 SendToICS("decline\n");
12393 } else if (cmailMsgLoaded) {
12394 if (currentMove == cmailOldMove &&
12395 commentList[cmailOldMove] != NULL &&
12396 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12397 "Black offers a draw" : "White offers a draw")) {
12399 AppendComment(cmailOldMove, "Draw declined", TRUE);
12400 DisplayComment(cmailOldMove - 1, "Draw declined");
12403 DisplayError(_("There is no pending offer on this move"), 0);
12406 /* Not used for offers from chess program */
12413 /* Issue ICS rematch command */
12414 if (appData.icsActive) {
12415 SendToICS(ics_prefix);
12416 SendToICS("rematch\n");
12423 /* Call your opponent's flag (claim a win on time) */
12424 if (appData.icsActive) {
12425 SendToICS(ics_prefix);
12426 SendToICS("flag\n");
12428 switch (gameMode) {
12431 case MachinePlaysWhite:
12434 GameEnds(GameIsDrawn, "Both players ran out of time",
12437 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
12439 DisplayError(_("Your opponent is not out of time"), 0);
12442 case MachinePlaysBlack:
12445 GameEnds(GameIsDrawn, "Both players ran out of time",
12448 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
12450 DisplayError(_("Your opponent is not out of time"), 0);
12460 /* Offer draw or accept pending draw offer from opponent */
12462 if (appData.icsActive) {
12463 /* Note: tournament rules require draw offers to be
12464 made after you make your move but before you punch
12465 your clock. Currently ICS doesn't let you do that;
12466 instead, you immediately punch your clock after making
12467 a move, but you can offer a draw at any time. */
12469 SendToICS(ics_prefix);
12470 SendToICS("draw\n");
12471 userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
12472 } else if (cmailMsgLoaded) {
12473 if (currentMove == cmailOldMove &&
12474 commentList[cmailOldMove] != NULL &&
12475 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12476 "Black offers a draw" : "White offers a draw")) {
12477 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12478 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
12479 } else if (currentMove == cmailOldMove + 1) {
12480 char *offer = WhiteOnMove(cmailOldMove) ?
12481 "White offers a draw" : "Black offers a draw";
12482 AppendComment(currentMove, offer, TRUE);
12483 DisplayComment(currentMove - 1, offer);
12484 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
12486 DisplayError(_("You must make your move before offering a draw"), 0);
12487 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12489 } else if (first.offeredDraw) {
12490 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
12492 if (first.sendDrawOffers) {
12493 SendToProgram("draw\n", &first);
12494 userOfferedDraw = TRUE;
12502 /* Offer Adjourn or accept pending Adjourn offer from opponent */
12504 if (appData.icsActive) {
12505 SendToICS(ics_prefix);
12506 SendToICS("adjourn\n");
12508 /* Currently GNU Chess doesn't offer or accept Adjourns */
12516 /* Offer Abort or accept pending Abort offer from opponent */
12518 if (appData.icsActive) {
12519 SendToICS(ics_prefix);
12520 SendToICS("abort\n");
12522 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
12529 /* Resign. You can do this even if it's not your turn. */
12531 if (appData.icsActive) {
12532 SendToICS(ics_prefix);
12533 SendToICS("resign\n");
12535 switch (gameMode) {
12536 case MachinePlaysWhite:
12537 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12539 case MachinePlaysBlack:
12540 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12543 if (cmailMsgLoaded) {
12545 if (WhiteOnMove(cmailOldMove)) {
12546 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12548 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12550 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
12561 StopObservingEvent()
12563 /* Stop observing current games */
12564 SendToICS(ics_prefix);
12565 SendToICS("unobserve\n");
12569 StopExaminingEvent()
12571 /* Stop observing current game */
12572 SendToICS(ics_prefix);
12573 SendToICS("unexamine\n");
12577 ForwardInner(target)
12582 if (appData.debugMode)
12583 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
12584 target, currentMove, forwardMostMove);
12586 if (gameMode == EditPosition)
12589 if (gameMode == PlayFromGameFile && !pausing)
12592 if (gameMode == IcsExamining && pausing)
12593 limit = pauseExamForwardMostMove;
12595 limit = forwardMostMove;
12597 if (target > limit) target = limit;
12599 if (target > 0 && moveList[target - 1][0]) {
12600 int fromX, fromY, toX, toY;
12601 toX = moveList[target - 1][2] - AAA;
12602 toY = moveList[target - 1][3] - ONE;
12603 if (moveList[target - 1][1] == '@') {
12604 if (appData.highlightLastMove) {
12605 SetHighlights(-1, -1, toX, toY);
12608 fromX = moveList[target - 1][0] - AAA;
12609 fromY = moveList[target - 1][1] - ONE;
12610 if (target == currentMove + 1) {
12611 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
12613 if (appData.highlightLastMove) {
12614 SetHighlights(fromX, fromY, toX, toY);
12618 if (gameMode == EditGame || gameMode == AnalyzeMode ||
12619 gameMode == Training || gameMode == PlayFromGameFile ||
12620 gameMode == AnalyzeFile) {
12621 while (currentMove < target) {
12622 SendMoveToProgram(currentMove++, &first);
12625 currentMove = target;
12628 if (gameMode == EditGame || gameMode == EndOfGame) {
12629 whiteTimeRemaining = timeRemaining[0][currentMove];
12630 blackTimeRemaining = timeRemaining[1][currentMove];
12632 DisplayBothClocks();
12633 DisplayMove(currentMove - 1);
12634 DrawPosition(FALSE, boards[currentMove]);
12635 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
12636 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
12637 DisplayComment(currentMove - 1, commentList[currentMove]);
12645 if (gameMode == IcsExamining && !pausing) {
12646 SendToICS(ics_prefix);
12647 SendToICS("forward\n");
12649 ForwardInner(currentMove + 1);
12656 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
12657 /* to optimze, we temporarily turn off analysis mode while we feed
12658 * the remaining moves to the engine. Otherwise we get analysis output
12661 if (first.analysisSupport) {
12662 SendToProgram("exit\nforce\n", &first);
12663 first.analyzing = FALSE;
12667 if (gameMode == IcsExamining && !pausing) {
12668 SendToICS(ics_prefix);
12669 SendToICS("forward 999999\n");
12671 ForwardInner(forwardMostMove);
12674 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
12675 /* we have fed all the moves, so reactivate analysis mode */
12676 SendToProgram("analyze\n", &first);
12677 first.analyzing = TRUE;
12678 /*first.maybeThinking = TRUE;*/
12679 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
12684 BackwardInner(target)
12687 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
12689 if (appData.debugMode)
12690 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
12691 target, currentMove, forwardMostMove);
12693 if (gameMode == EditPosition) return;
12694 if (currentMove <= backwardMostMove) {
12696 DrawPosition(full_redraw, boards[currentMove]);
12699 if (gameMode == PlayFromGameFile && !pausing)
12702 if (moveList[target][0]) {
12703 int fromX, fromY, toX, toY;
12704 toX = moveList[target][2] - AAA;
12705 toY = moveList[target][3] - ONE;
12706 if (moveList[target][1] == '@') {
12707 if (appData.highlightLastMove) {
12708 SetHighlights(-1, -1, toX, toY);
12711 fromX = moveList[target][0] - AAA;
12712 fromY = moveList[target][1] - ONE;
12713 if (target == currentMove - 1) {
12714 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
12716 if (appData.highlightLastMove) {
12717 SetHighlights(fromX, fromY, toX, toY);
12721 if (gameMode == EditGame || gameMode==AnalyzeMode ||
12722 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
12723 while (currentMove > target) {
12724 SendToProgram("undo\n", &first);
12728 currentMove = target;
12731 if (gameMode == EditGame || gameMode == EndOfGame) {
12732 whiteTimeRemaining = timeRemaining[0][currentMove];
12733 blackTimeRemaining = timeRemaining[1][currentMove];
12735 DisplayBothClocks();
12736 DisplayMove(currentMove - 1);
12737 DrawPosition(full_redraw, boards[currentMove]);
12738 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
12739 // [HGM] PV info: routine tests if comment empty
12740 DisplayComment(currentMove - 1, commentList[currentMove]);
12746 if (gameMode == IcsExamining && !pausing) {
12747 SendToICS(ics_prefix);
12748 SendToICS("backward\n");
12750 BackwardInner(currentMove - 1);
12757 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
12758 /* to optimize, we temporarily turn off analysis mode while we undo
12759 * all the moves. Otherwise we get analysis output after each undo.
12761 if (first.analysisSupport) {
12762 SendToProgram("exit\nforce\n", &first);
12763 first.analyzing = FALSE;
12767 if (gameMode == IcsExamining && !pausing) {
12768 SendToICS(ics_prefix);
12769 SendToICS("backward 999999\n");
12771 BackwardInner(backwardMostMove);
12774 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
12775 /* we have fed all the moves, so reactivate analysis mode */
12776 SendToProgram("analyze\n", &first);
12777 first.analyzing = TRUE;
12778 /*first.maybeThinking = TRUE;*/
12779 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
12786 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
12787 if (to >= forwardMostMove) to = forwardMostMove;
12788 if (to <= backwardMostMove) to = backwardMostMove;
12789 if (to < currentMove) {
12797 RevertEvent(Boolean annotate)
12799 if(PopTail(annotate)) { // [HGM] vari: restore old game tail
12802 if (gameMode != IcsExamining) {
12803 DisplayError(_("You are not examining a game"), 0);
12807 DisplayError(_("You can't revert while pausing"), 0);
12810 SendToICS(ics_prefix);
12811 SendToICS("revert\n");
12817 switch (gameMode) {
12818 case MachinePlaysWhite:
12819 case MachinePlaysBlack:
12820 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
12821 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
12824 if (forwardMostMove < 2) return;
12825 currentMove = forwardMostMove = forwardMostMove - 2;
12826 whiteTimeRemaining = timeRemaining[0][currentMove];
12827 blackTimeRemaining = timeRemaining[1][currentMove];
12828 DisplayBothClocks();
12829 DisplayMove(currentMove - 1);
12830 ClearHighlights();/*!! could figure this out*/
12831 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
12832 SendToProgram("remove\n", &first);
12833 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
12836 case BeginningOfGame:
12840 case IcsPlayingWhite:
12841 case IcsPlayingBlack:
12842 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
12843 SendToICS(ics_prefix);
12844 SendToICS("takeback 2\n");
12846 SendToICS(ics_prefix);
12847 SendToICS("takeback 1\n");
12856 ChessProgramState *cps;
12858 switch (gameMode) {
12859 case MachinePlaysWhite:
12860 if (!WhiteOnMove(forwardMostMove)) {
12861 DisplayError(_("It is your turn"), 0);
12866 case MachinePlaysBlack:
12867 if (WhiteOnMove(forwardMostMove)) {
12868 DisplayError(_("It is your turn"), 0);
12873 case TwoMachinesPlay:
12874 if (WhiteOnMove(forwardMostMove) ==
12875 (first.twoMachinesColor[0] == 'w')) {
12881 case BeginningOfGame:
12885 SendToProgram("?\n", cps);
12889 TruncateGameEvent()
12892 if (gameMode != EditGame) return;
12899 CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
12900 if (forwardMostMove > currentMove) {
12901 if (gameInfo.resultDetails != NULL) {
12902 free(gameInfo.resultDetails);
12903 gameInfo.resultDetails = NULL;
12904 gameInfo.result = GameUnfinished;
12906 forwardMostMove = currentMove;
12907 HistorySet(parseList, backwardMostMove, forwardMostMove,
12915 if (appData.noChessProgram) return;
12916 switch (gameMode) {
12917 case MachinePlaysWhite:
12918 if (WhiteOnMove(forwardMostMove)) {
12919 DisplayError(_("Wait until your turn"), 0);
12923 case BeginningOfGame:
12924 case MachinePlaysBlack:
12925 if (!WhiteOnMove(forwardMostMove)) {
12926 DisplayError(_("Wait until your turn"), 0);
12931 DisplayError(_("No hint available"), 0);
12934 SendToProgram("hint\n", &first);
12935 hintRequested = TRUE;
12941 if (appData.noChessProgram) return;
12942 switch (gameMode) {
12943 case MachinePlaysWhite:
12944 if (WhiteOnMove(forwardMostMove)) {
12945 DisplayError(_("Wait until your turn"), 0);
12949 case BeginningOfGame:
12950 case MachinePlaysBlack:
12951 if (!WhiteOnMove(forwardMostMove)) {
12952 DisplayError(_("Wait until your turn"), 0);
12957 EditPositionDone(TRUE);
12959 case TwoMachinesPlay:
12964 SendToProgram("bk\n", &first);
12965 bookOutput[0] = NULLCHAR;
12966 bookRequested = TRUE;
12972 char *tags = PGNTags(&gameInfo);
12973 TagsPopUp(tags, CmailMsg());
12977 /* end button procedures */
12980 PrintPosition(fp, move)
12986 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
12987 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
12988 char c = PieceToChar(boards[move][i][j]);
12989 fputc(c == 'x' ? '.' : c, fp);
12990 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
12993 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
12994 fprintf(fp, "white to play\n");
12996 fprintf(fp, "black to play\n");
13003 if (gameInfo.white != NULL) {
13004 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
13010 /* Find last component of program's own name, using some heuristics */
13012 TidyProgramName(prog, host, buf)
13013 char *prog, *host, buf[MSG_SIZ];
13016 int local = (strcmp(host, "localhost") == 0);
13017 while (!local && (p = strchr(prog, ';')) != NULL) {
13019 while (*p == ' ') p++;
13022 if (*prog == '"' || *prog == '\'') {
13023 q = strchr(prog + 1, *prog);
13025 q = strchr(prog, ' ');
13027 if (q == NULL) q = prog + strlen(prog);
13029 while (p >= prog && *p != '/' && *p != '\\') p--;
13031 if(p == prog && *p == '"') p++;
13032 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) q -= 4;
13033 memcpy(buf, p, q - p);
13034 buf[q - p] = NULLCHAR;
13042 TimeControlTagValue()
13045 if (!appData.clockMode) {
13047 } else if (movesPerSession > 0) {
13048 sprintf(buf, "%d/%ld", movesPerSession, timeControl/1000);
13049 } else if (timeIncrement == 0) {
13050 sprintf(buf, "%ld", timeControl/1000);
13052 sprintf(buf, "%ld+%ld", timeControl/1000, timeIncrement/1000);
13054 return StrSave(buf);
13060 /* This routine is used only for certain modes */
13061 VariantClass v = gameInfo.variant;
13062 ChessMove r = GameUnfinished;
13065 if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
13066 r = gameInfo.result;
13067 p = gameInfo.resultDetails;
13068 gameInfo.resultDetails = NULL;
13070 ClearGameInfo(&gameInfo);
13071 gameInfo.variant = v;
13073 switch (gameMode) {
13074 case MachinePlaysWhite:
13075 gameInfo.event = StrSave( appData.pgnEventHeader );
13076 gameInfo.site = StrSave(HostName());
13077 gameInfo.date = PGNDate();
13078 gameInfo.round = StrSave("-");
13079 gameInfo.white = StrSave(first.tidy);
13080 gameInfo.black = StrSave(UserName());
13081 gameInfo.timeControl = TimeControlTagValue();
13084 case MachinePlaysBlack:
13085 gameInfo.event = StrSave( appData.pgnEventHeader );
13086 gameInfo.site = StrSave(HostName());
13087 gameInfo.date = PGNDate();
13088 gameInfo.round = StrSave("-");
13089 gameInfo.white = StrSave(UserName());
13090 gameInfo.black = StrSave(first.tidy);
13091 gameInfo.timeControl = TimeControlTagValue();
13094 case TwoMachinesPlay:
13095 gameInfo.event = StrSave( appData.pgnEventHeader );
13096 gameInfo.site = StrSave(HostName());
13097 gameInfo.date = PGNDate();
13098 if (matchGame > 0) {
13100 sprintf(buf, "%d", matchGame);
13101 gameInfo.round = StrSave(buf);
13103 gameInfo.round = StrSave("-");
13105 if (first.twoMachinesColor[0] == 'w') {
13106 gameInfo.white = StrSave(first.tidy);
13107 gameInfo.black = StrSave(second.tidy);
13109 gameInfo.white = StrSave(second.tidy);
13110 gameInfo.black = StrSave(first.tidy);
13112 gameInfo.timeControl = TimeControlTagValue();
13116 gameInfo.event = StrSave("Edited game");
13117 gameInfo.site = StrSave(HostName());
13118 gameInfo.date = PGNDate();
13119 gameInfo.round = StrSave("-");
13120 gameInfo.white = StrSave("-");
13121 gameInfo.black = StrSave("-");
13122 gameInfo.result = r;
13123 gameInfo.resultDetails = p;
13127 gameInfo.event = StrSave("Edited position");
13128 gameInfo.site = StrSave(HostName());
13129 gameInfo.date = PGNDate();
13130 gameInfo.round = StrSave("-");
13131 gameInfo.white = StrSave("-");
13132 gameInfo.black = StrSave("-");
13135 case IcsPlayingWhite:
13136 case IcsPlayingBlack:
13141 case PlayFromGameFile:
13142 gameInfo.event = StrSave("Game from non-PGN file");
13143 gameInfo.site = StrSave(HostName());
13144 gameInfo.date = PGNDate();
13145 gameInfo.round = StrSave("-");
13146 gameInfo.white = StrSave("?");
13147 gameInfo.black = StrSave("?");
13156 ReplaceComment(index, text)
13162 while (*text == '\n') text++;
13163 len = strlen(text);
13164 while (len > 0 && text[len - 1] == '\n') len--;
13166 if (commentList[index] != NULL)
13167 free(commentList[index]);
13170 commentList[index] = NULL;
13173 if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
13174 *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
13175 *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
13176 commentList[index] = (char *) malloc(len + 2);
13177 strncpy(commentList[index], text, len);
13178 commentList[index][len] = '\n';
13179 commentList[index][len + 1] = NULLCHAR;
13181 // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
13183 commentList[index] = (char *) malloc(len + 6);
13184 strcpy(commentList[index], "{\n");
13185 strncpy(commentList[index]+2, text, len);
13186 commentList[index][len+2] = NULLCHAR;
13187 while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
13188 strcat(commentList[index], "\n}\n");
13202 if (ch == '\r') continue;
13204 } while (ch != '\0');
13208 AppendComment(index, text, addBraces)
13211 Boolean addBraces; // [HGM] braces: tells if we should add {}
13216 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces); fflush(debugFP);
13217 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
13220 while (*text == '\n') text++;
13221 len = strlen(text);
13222 while (len > 0 && text[len - 1] == '\n') len--;
13224 if (len == 0) return;
13226 if (commentList[index] != NULL) {
13227 old = commentList[index];
13228 oldlen = strlen(old);
13229 while(commentList[index][oldlen-1] == '\n')
13230 commentList[index][--oldlen] = NULLCHAR;
13231 commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
13232 strcpy(commentList[index], old);
13234 // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
13235 if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces)) {
13236 if(addBraces) addBraces = FALSE; else { text++; len--; }
13237 while (*text == '\n') { text++; len--; }
13238 commentList[index][--oldlen] = NULLCHAR;
13240 if(addBraces) strcat(commentList[index], "\n{\n");
13241 else strcat(commentList[index], "\n");
13242 strcat(commentList[index], text);
13243 if(addBraces) strcat(commentList[index], "\n}\n");
13244 else strcat(commentList[index], "\n");
13246 commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
13248 strcpy(commentList[index], "{\n");
13249 else commentList[index][0] = NULLCHAR;
13250 strcat(commentList[index], text);
13251 strcat(commentList[index], "\n");
13252 if(addBraces) strcat(commentList[index], "}\n");
13256 static char * FindStr( char * text, char * sub_text )
13258 char * result = strstr( text, sub_text );
13260 if( result != NULL ) {
13261 result += strlen( sub_text );
13267 /* [AS] Try to extract PV info from PGN comment */
13268 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
13269 char *GetInfoFromComment( int index, char * text )
13273 if( text != NULL && index > 0 ) {
13276 int time = -1, sec = 0, deci;
13277 char * s_eval = FindStr( text, "[%eval " );
13278 char * s_emt = FindStr( text, "[%emt " );
13280 if( s_eval != NULL || s_emt != NULL ) {
13284 if( s_eval != NULL ) {
13285 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
13289 if( delim != ']' ) {
13294 if( s_emt != NULL ) {
13299 /* We expect something like: [+|-]nnn.nn/dd */
13302 if(*text != '{') return text; // [HGM] braces: must be normal comment
13304 sep = strchr( text, '/' );
13305 if( sep == NULL || sep < (text+4) ) {
13309 time = -1; sec = -1; deci = -1;
13310 if( sscanf( text+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
13311 sscanf( text+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
13312 sscanf( text+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
13313 sscanf( text+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
13317 if( score_lo < 0 || score_lo >= 100 ) {
13321 if(sec >= 0) time = 600*time + 10*sec; else
13322 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
13324 score = score >= 0 ? score*100 + score_lo : score*100 - score_lo;
13326 /* [HGM] PV time: now locate end of PV info */
13327 while( *++sep >= '0' && *sep <= '9'); // strip depth
13329 while( *++sep >= '0' && *sep <= '9'); // strip time
13331 while( *++sep >= '0' && *sep <= '9'); // strip seconds
13333 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
13334 while(*sep == ' ') sep++;
13345 pvInfoList[index-1].depth = depth;
13346 pvInfoList[index-1].score = score;
13347 pvInfoList[index-1].time = 10*time; // centi-sec
13348 if(*sep == '}') *sep = 0; else *--sep = '{';
13354 SendToProgram(message, cps)
13356 ChessProgramState *cps;
13358 int count, outCount, error;
13361 if (cps->pr == NULL) return;
13364 if (appData.debugMode) {
13367 fprintf(debugFP, "%ld >%-6s: %s",
13368 SubtractTimeMarks(&now, &programStartTime),
13369 cps->which, message);
13372 count = strlen(message);
13373 outCount = OutputToProcess(cps->pr, message, count, &error);
13374 if (outCount < count && !exiting
13375 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
13376 sprintf(buf, _("Error writing to %s chess program"), cps->which);
13377 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
13378 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
13379 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
13380 sprintf(buf, "%s program exits in draw position (%s)", cps->which, cps->program);
13382 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
13384 gameInfo.resultDetails = StrSave(buf);
13386 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
13391 ReceiveFromProgram(isr, closure, message, count, error)
13392 InputSourceRef isr;
13400 ChessProgramState *cps = (ChessProgramState *)closure;
13402 if (isr != cps->isr) return; /* Killed intentionally */
13406 _("Error: %s chess program (%s) exited unexpectedly"),
13407 cps->which, cps->program);
13408 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
13409 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
13410 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
13411 sprintf(buf, _("%s program exits in draw position (%s)"), cps->which, cps->program);
13413 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
13415 gameInfo.resultDetails = StrSave(buf);
13417 RemoveInputSource(cps->isr);
13418 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
13421 _("Error reading from %s chess program (%s)"),
13422 cps->which, cps->program);
13423 RemoveInputSource(cps->isr);
13425 /* [AS] Program is misbehaving badly... kill it */
13426 if( count == -2 ) {
13427 DestroyChildProcess( cps->pr, 9 );
13431 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
13436 if ((end_str = strchr(message, '\r')) != NULL)
13437 *end_str = NULLCHAR;
13438 if ((end_str = strchr(message, '\n')) != NULL)
13439 *end_str = NULLCHAR;
13441 if (appData.debugMode) {
13442 TimeMark now; int print = 1;
13443 char *quote = ""; char c; int i;
13445 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
13446 char start = message[0];
13447 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
13448 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
13449 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
13450 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
13451 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
13452 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
13453 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
13454 sscanf(message, "pong %c", &c)!=1 && start != '#') {
13455 quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
13456 print = (appData.engineComments >= 2);
13458 message[0] = start; // restore original message
13462 fprintf(debugFP, "%ld <%-6s: %s%s\n",
13463 SubtractTimeMarks(&now, &programStartTime), cps->which,
13469 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
13470 if (appData.icsEngineAnalyze) {
13471 if (strstr(message, "whisper") != NULL ||
13472 strstr(message, "kibitz") != NULL ||
13473 strstr(message, "tellics") != NULL) return;
13476 HandleMachineMove(message, cps);
13481 SendTimeControl(cps, mps, tc, inc, sd, st)
13482 ChessProgramState *cps;
13483 int mps, inc, sd, st;
13489 if( timeControl_2 > 0 ) {
13490 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
13491 tc = timeControl_2;
13494 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
13495 inc /= cps->timeOdds;
13496 st /= cps->timeOdds;
13498 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
13501 /* Set exact time per move, normally using st command */
13502 if (cps->stKludge) {
13503 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
13505 if (seconds == 0) {
13506 sprintf(buf, "level 1 %d\n", st/60);
13508 sprintf(buf, "level 1 %d:%02d\n", st/60, seconds);
13511 sprintf(buf, "st %d\n", st);
13514 /* Set conventional or incremental time control, using level command */
13515 if (seconds == 0) {
13516 /* Note old gnuchess bug -- minutes:seconds used to not work.
13517 Fixed in later versions, but still avoid :seconds
13518 when seconds is 0. */
13519 sprintf(buf, "level %d %ld %d\n", mps, tc/60000, inc/1000);
13521 sprintf(buf, "level %d %ld:%02d %d\n", mps, tc/60000,
13522 seconds, inc/1000);
13525 SendToProgram(buf, cps);
13527 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
13528 /* Orthogonally, limit search to given depth */
13530 if (cps->sdKludge) {
13531 sprintf(buf, "depth\n%d\n", sd);
13533 sprintf(buf, "sd %d\n", sd);
13535 SendToProgram(buf, cps);
13538 if(cps->nps > 0) { /* [HGM] nps */
13539 if(cps->supportsNPS == FALSE) cps->nps = -1; // don't use if engine explicitly says not supported!
13541 sprintf(buf, "nps %d\n", cps->nps);
13542 SendToProgram(buf, cps);
13547 ChessProgramState *WhitePlayer()
13548 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
13550 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
13551 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
13557 SendTimeRemaining(cps, machineWhite)
13558 ChessProgramState *cps;
13559 int /*boolean*/ machineWhite;
13561 char message[MSG_SIZ];
13564 /* Note: this routine must be called when the clocks are stopped
13565 or when they have *just* been set or switched; otherwise
13566 it will be off by the time since the current tick started.
13568 if (machineWhite) {
13569 time = whiteTimeRemaining / 10;
13570 otime = blackTimeRemaining / 10;
13572 time = blackTimeRemaining / 10;
13573 otime = whiteTimeRemaining / 10;
13575 /* [HGM] translate opponent's time by time-odds factor */
13576 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
13577 if (appData.debugMode) {
13578 fprintf(debugFP, "time odds: %f %f \n", cps->timeOdds, cps->other->timeOdds);
13581 if (time <= 0) time = 1;
13582 if (otime <= 0) otime = 1;
13584 sprintf(message, "time %ld\n", time);
13585 SendToProgram(message, cps);
13587 sprintf(message, "otim %ld\n", otime);
13588 SendToProgram(message, cps);
13592 BoolFeature(p, name, loc, cps)
13596 ChessProgramState *cps;
13599 int len = strlen(name);
13601 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
13603 sscanf(*p, "%d", &val);
13605 while (**p && **p != ' ') (*p)++;
13606 sprintf(buf, "accepted %s\n", name);
13607 SendToProgram(buf, cps);
13614 IntFeature(p, name, loc, cps)
13618 ChessProgramState *cps;
13621 int len = strlen(name);
13622 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
13624 sscanf(*p, "%d", loc);
13625 while (**p && **p != ' ') (*p)++;
13626 sprintf(buf, "accepted %s\n", name);
13627 SendToProgram(buf, cps);
13634 StringFeature(p, name, loc, cps)
13638 ChessProgramState *cps;
13641 int len = strlen(name);
13642 if (strncmp((*p), name, len) == 0
13643 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
13645 sscanf(*p, "%[^\"]", loc);
13646 while (**p && **p != '\"') (*p)++;
13647 if (**p == '\"') (*p)++;
13648 sprintf(buf, "accepted %s\n", name);
13649 SendToProgram(buf, cps);
13656 ParseOption(Option *opt, ChessProgramState *cps)
13657 // [HGM] options: process the string that defines an engine option, and determine
13658 // name, type, default value, and allowed value range
13660 char *p, *q, buf[MSG_SIZ];
13661 int n, min = (-1)<<31, max = 1<<31, def;
13663 if(p = strstr(opt->name, " -spin ")) {
13664 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
13665 if(max < min) max = min; // enforce consistency
13666 if(def < min) def = min;
13667 if(def > max) def = max;
13672 } else if((p = strstr(opt->name, " -slider "))) {
13673 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
13674 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
13675 if(max < min) max = min; // enforce consistency
13676 if(def < min) def = min;
13677 if(def > max) def = max;
13681 opt->type = Spin; // Slider;
13682 } else if((p = strstr(opt->name, " -string "))) {
13683 opt->textValue = p+9;
13684 opt->type = TextBox;
13685 } else if((p = strstr(opt->name, " -file "))) {
13686 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
13687 opt->textValue = p+7;
13688 opt->type = TextBox; // FileName;
13689 } else if((p = strstr(opt->name, " -path "))) {
13690 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
13691 opt->textValue = p+7;
13692 opt->type = TextBox; // PathName;
13693 } else if(p = strstr(opt->name, " -check ")) {
13694 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
13695 opt->value = (def != 0);
13696 opt->type = CheckBox;
13697 } else if(p = strstr(opt->name, " -combo ")) {
13698 opt->textValue = (char*) (&cps->comboList[cps->comboCnt]); // cheat with pointer type
13699 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
13700 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
13701 opt->value = n = 0;
13702 while(q = StrStr(q, " /// ")) {
13703 n++; *q = 0; // count choices, and null-terminate each of them
13705 if(*q == '*') { // remember default, which is marked with * prefix
13709 cps->comboList[cps->comboCnt++] = q;
13711 cps->comboList[cps->comboCnt++] = NULL;
13713 opt->type = ComboBox;
13714 } else if(p = strstr(opt->name, " -button")) {
13715 opt->type = Button;
13716 } else if(p = strstr(opt->name, " -save")) {
13717 opt->type = SaveButton;
13718 } else return FALSE;
13719 *p = 0; // terminate option name
13720 // now look if the command-line options define a setting for this engine option.
13721 if(cps->optionSettings && cps->optionSettings[0])
13722 p = strstr(cps->optionSettings, opt->name); else p = NULL;
13723 if(p && (p == cps->optionSettings || p[-1] == ',')) {
13724 sprintf(buf, "option %s", p);
13725 if(p = strstr(buf, ",")) *p = 0;
13727 SendToProgram(buf, cps);
13733 FeatureDone(cps, val)
13734 ChessProgramState* cps;
13737 DelayedEventCallback cb = GetDelayedEvent();
13738 if ((cb == InitBackEnd3 && cps == &first) ||
13739 (cb == TwoMachinesEventIfReady && cps == &second)) {
13740 CancelDelayedEvent();
13741 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
13743 cps->initDone = val;
13746 /* Parse feature command from engine */
13748 ParseFeatures(args, cps)
13750 ChessProgramState *cps;
13758 while (*p == ' ') p++;
13759 if (*p == NULLCHAR) return;
13761 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
13762 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
13763 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
13764 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
13765 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
13766 if (BoolFeature(&p, "reuse", &val, cps)) {
13767 /* Engine can disable reuse, but can't enable it if user said no */
13768 if (!val) cps->reuse = FALSE;
13771 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
13772 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
13773 if (gameMode == TwoMachinesPlay) {
13774 DisplayTwoMachinesTitle();
13780 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
13781 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
13782 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
13783 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
13784 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
13785 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
13786 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
13787 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
13788 if (BoolFeature(&p, "pause", &val, cps)) continue; /* unused at present */
13789 if (IntFeature(&p, "done", &val, cps)) {
13790 FeatureDone(cps, val);
13793 /* Added by Tord: */
13794 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
13795 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
13796 /* End of additions by Tord */
13798 /* [HGM] added features: */
13799 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
13800 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
13801 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
13802 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
13803 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
13804 if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
13805 if (StringFeature(&p, "option", &(cps->option[cps->nrOptions].name), cps)) {
13806 if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
13807 sprintf(buf, "rejected option %s\n", cps->option[--cps->nrOptions].name);
13808 SendToProgram(buf, cps);
13811 if(cps->nrOptions >= MAX_OPTIONS) {
13813 sprintf(buf, "%s engine has too many options\n", cps->which);
13814 DisplayError(buf, 0);
13818 /* End of additions by HGM */
13820 /* unknown feature: complain and skip */
13822 while (*q && *q != '=') q++;
13823 sprintf(buf, "rejected %.*s\n", (int)(q-p), p);
13824 SendToProgram(buf, cps);
13830 while (*p && *p != '\"') p++;
13831 if (*p == '\"') p++;
13833 while (*p && *p != ' ') p++;
13841 PeriodicUpdatesEvent(newState)
13844 if (newState == appData.periodicUpdates)
13847 appData.periodicUpdates=newState;
13849 /* Display type changes, so update it now */
13850 // DisplayAnalysis();
13852 /* Get the ball rolling again... */
13854 AnalysisPeriodicEvent(1);
13855 StartAnalysisClock();
13860 PonderNextMoveEvent(newState)
13863 if (newState == appData.ponderNextMove) return;
13864 if (gameMode == EditPosition) EditPositionDone(TRUE);
13866 SendToProgram("hard\n", &first);
13867 if (gameMode == TwoMachinesPlay) {
13868 SendToProgram("hard\n", &second);
13871 SendToProgram("easy\n", &first);
13872 thinkOutput[0] = NULLCHAR;
13873 if (gameMode == TwoMachinesPlay) {
13874 SendToProgram("easy\n", &second);
13877 appData.ponderNextMove = newState;
13881 NewSettingEvent(option, feature, command, value)
13883 int option, value, *feature;
13887 if (gameMode == EditPosition) EditPositionDone(TRUE);
13888 sprintf(buf, "%s%s %d\n", (option ? "option ": ""), command, value);
13889 if(feature == NULL || *feature) SendToProgram(buf, &first);
13890 if (gameMode == TwoMachinesPlay) {
13891 if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
13896 ShowThinkingEvent()
13897 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
13899 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
13900 int newState = appData.showThinking
13901 // [HGM] thinking: other features now need thinking output as well
13902 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
13904 if (oldState == newState) return;
13905 oldState = newState;
13906 if (gameMode == EditPosition) EditPositionDone(TRUE);
13908 SendToProgram("post\n", &first);
13909 if (gameMode == TwoMachinesPlay) {
13910 SendToProgram("post\n", &second);
13913 SendToProgram("nopost\n", &first);
13914 thinkOutput[0] = NULLCHAR;
13915 if (gameMode == TwoMachinesPlay) {
13916 SendToProgram("nopost\n", &second);
13919 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
13923 AskQuestionEvent(title, question, replyPrefix, which)
13924 char *title; char *question; char *replyPrefix; char *which;
13926 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
13927 if (pr == NoProc) return;
13928 AskQuestion(title, question, replyPrefix, pr);
13932 DisplayMove(moveNumber)
13935 char message[MSG_SIZ];
13937 char cpThinkOutput[MSG_SIZ];
13939 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
13941 if (moveNumber == forwardMostMove - 1 ||
13942 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13944 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput));
13946 if (strchr(cpThinkOutput, '\n')) {
13947 *strchr(cpThinkOutput, '\n') = NULLCHAR;
13950 *cpThinkOutput = NULLCHAR;
13953 /* [AS] Hide thinking from human user */
13954 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
13955 *cpThinkOutput = NULLCHAR;
13956 if( thinkOutput[0] != NULLCHAR ) {
13959 for( i=0; i<=hiddenThinkOutputState; i++ ) {
13960 cpThinkOutput[i] = '.';
13962 cpThinkOutput[i] = NULLCHAR;
13963 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
13967 if (moveNumber == forwardMostMove - 1 &&
13968 gameInfo.resultDetails != NULL) {
13969 if (gameInfo.resultDetails[0] == NULLCHAR) {
13970 sprintf(res, " %s", PGNResult(gameInfo.result));
13972 sprintf(res, " {%s} %s",
13973 gameInfo.resultDetails, PGNResult(gameInfo.result));
13979 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
13980 DisplayMessage(res, cpThinkOutput);
13982 sprintf(message, "%d.%s%s%s", moveNumber / 2 + 1,
13983 WhiteOnMove(moveNumber) ? " " : ".. ",
13984 parseList[moveNumber], res);
13985 DisplayMessage(message, cpThinkOutput);
13990 DisplayComment(moveNumber, text)
13994 char title[MSG_SIZ];
13995 char buf[8000]; // comment can be long!
13998 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
13999 strcpy(title, "Comment");
14001 sprintf(title, "Comment on %d.%s%s", moveNumber / 2 + 1,
14002 WhiteOnMove(moveNumber) ? " " : ".. ",
14003 parseList[moveNumber]);
14005 // [HGM] PV info: display PV info together with (or as) comment
14006 if(moveNumber >= 0 && (depth = pvInfoList[moveNumber].depth) > 0) {
14007 if(text == NULL) text = "";
14008 score = pvInfoList[moveNumber].score;
14009 sprintf(buf, "%s%.2f/%d %d\n%s", score>0 ? "+" : "", score/100.,
14010 depth, (pvInfoList[moveNumber].time+50)/100, text);
14013 if (text != NULL && (appData.autoDisplayComment || commentUp))
14014 CommentPopUp(title, text);
14017 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
14018 * might be busy thinking or pondering. It can be omitted if your
14019 * gnuchess is configured to stop thinking immediately on any user
14020 * input. However, that gnuchess feature depends on the FIONREAD
14021 * ioctl, which does not work properly on some flavors of Unix.
14025 ChessProgramState *cps;
14028 if (!cps->useSigint) return;
14029 if (appData.noChessProgram || (cps->pr == NoProc)) return;
14030 switch (gameMode) {
14031 case MachinePlaysWhite:
14032 case MachinePlaysBlack:
14033 case TwoMachinesPlay:
14034 case IcsPlayingWhite:
14035 case IcsPlayingBlack:
14038 /* Skip if we know it isn't thinking */
14039 if (!cps->maybeThinking) return;
14040 if (appData.debugMode)
14041 fprintf(debugFP, "Interrupting %s\n", cps->which);
14042 InterruptChildProcess(cps->pr);
14043 cps->maybeThinking = FALSE;
14048 #endif /*ATTENTION*/
14054 if (whiteTimeRemaining <= 0) {
14057 if (appData.icsActive) {
14058 if (appData.autoCallFlag &&
14059 gameMode == IcsPlayingBlack && !blackFlag) {
14060 SendToICS(ics_prefix);
14061 SendToICS("flag\n");
14065 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
14067 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
14068 if (appData.autoCallFlag) {
14069 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
14076 if (blackTimeRemaining <= 0) {
14079 if (appData.icsActive) {
14080 if (appData.autoCallFlag &&
14081 gameMode == IcsPlayingWhite && !whiteFlag) {
14082 SendToICS(ics_prefix);
14083 SendToICS("flag\n");
14087 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
14089 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
14090 if (appData.autoCallFlag) {
14091 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
14104 if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
14105 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
14108 * add time to clocks when time control is achieved ([HGM] now also used for increment)
14110 if ( !WhiteOnMove(forwardMostMove) )
14111 /* White made time control */
14112 whiteTimeRemaining += GetTimeQuota((forwardMostMove-1)/2)
14113 /* [HGM] time odds: correct new time quota for time odds! */
14114 / WhitePlayer()->timeOdds;
14116 /* Black made time control */
14117 blackTimeRemaining += GetTimeQuota((forwardMostMove-1)/2)
14118 / WhitePlayer()->other->timeOdds;
14122 DisplayBothClocks()
14124 int wom = gameMode == EditPosition ?
14125 !blackPlaysFirst : WhiteOnMove(currentMove);
14126 DisplayWhiteClock(whiteTimeRemaining, wom);
14127 DisplayBlackClock(blackTimeRemaining, !wom);
14131 /* Timekeeping seems to be a portability nightmare. I think everyone
14132 has ftime(), but I'm really not sure, so I'm including some ifdefs
14133 to use other calls if you don't. Clocks will be less accurate if
14134 you have neither ftime nor gettimeofday.
14137 /* VS 2008 requires the #include outside of the function */
14138 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
14139 #include <sys/timeb.h>
14142 /* Get the current time as a TimeMark */
14147 #if HAVE_GETTIMEOFDAY
14149 struct timeval timeVal;
14150 struct timezone timeZone;
14152 gettimeofday(&timeVal, &timeZone);
14153 tm->sec = (long) timeVal.tv_sec;
14154 tm->ms = (int) (timeVal.tv_usec / 1000L);
14156 #else /*!HAVE_GETTIMEOFDAY*/
14159 // include <sys/timeb.h> / moved to just above start of function
14160 struct timeb timeB;
14163 tm->sec = (long) timeB.time;
14164 tm->ms = (int) timeB.millitm;
14166 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
14167 tm->sec = (long) time(NULL);
14173 /* Return the difference in milliseconds between two
14174 time marks. We assume the difference will fit in a long!
14177 SubtractTimeMarks(tm2, tm1)
14178 TimeMark *tm2, *tm1;
14180 return 1000L*(tm2->sec - tm1->sec) +
14181 (long) (tm2->ms - tm1->ms);
14186 * Code to manage the game clocks.
14188 * In tournament play, black starts the clock and then white makes a move.
14189 * We give the human user a slight advantage if he is playing white---the
14190 * clocks don't run until he makes his first move, so it takes zero time.
14191 * Also, we don't account for network lag, so we could get out of sync
14192 * with GNU Chess's clock -- but then, referees are always right.
14195 static TimeMark tickStartTM;
14196 static long intendedTickLength;
14199 NextTickLength(timeRemaining)
14200 long timeRemaining;
14202 long nominalTickLength, nextTickLength;
14204 if (timeRemaining > 0L && timeRemaining <= 10000L)
14205 nominalTickLength = 100L;
14207 nominalTickLength = 1000L;
14208 nextTickLength = timeRemaining % nominalTickLength;
14209 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
14211 return nextTickLength;
14214 /* Adjust clock one minute up or down */
14216 AdjustClock(Boolean which, int dir)
14218 if(which) blackTimeRemaining += 60000*dir;
14219 else whiteTimeRemaining += 60000*dir;
14220 DisplayBothClocks();
14223 /* Stop clocks and reset to a fresh time control */
14227 (void) StopClockTimer();
14228 if (appData.icsActive) {
14229 whiteTimeRemaining = blackTimeRemaining = 0;
14230 } else if (searchTime) {
14231 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
14232 blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
14233 } else { /* [HGM] correct new time quote for time odds */
14234 whiteTimeRemaining = GetTimeQuota(-1) / WhitePlayer()->timeOdds;
14235 blackTimeRemaining = GetTimeQuota(-1) / WhitePlayer()->other->timeOdds;
14237 if (whiteFlag || blackFlag) {
14239 whiteFlag = blackFlag = FALSE;
14241 DisplayBothClocks();
14244 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
14246 /* Decrement running clock by amount of time that has passed */
14250 long timeRemaining;
14251 long lastTickLength, fudge;
14254 if (!appData.clockMode) return;
14255 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
14259 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14261 /* Fudge if we woke up a little too soon */
14262 fudge = intendedTickLength - lastTickLength;
14263 if (fudge < 0 || fudge > FUDGE) fudge = 0;
14265 if (WhiteOnMove(forwardMostMove)) {
14266 if(whiteNPS >= 0) lastTickLength = 0;
14267 timeRemaining = whiteTimeRemaining -= lastTickLength;
14268 DisplayWhiteClock(whiteTimeRemaining - fudge,
14269 WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
14271 if(blackNPS >= 0) lastTickLength = 0;
14272 timeRemaining = blackTimeRemaining -= lastTickLength;
14273 DisplayBlackClock(blackTimeRemaining - fudge,
14274 !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
14277 if (CheckFlags()) return;
14280 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
14281 StartClockTimer(intendedTickLength);
14283 /* if the time remaining has fallen below the alarm threshold, sound the
14284 * alarm. if the alarm has sounded and (due to a takeback or time control
14285 * with increment) the time remaining has increased to a level above the
14286 * threshold, reset the alarm so it can sound again.
14289 if (appData.icsActive && appData.icsAlarm) {
14291 /* make sure we are dealing with the user's clock */
14292 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
14293 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
14296 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
14297 alarmSounded = FALSE;
14298 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
14300 alarmSounded = TRUE;
14306 /* A player has just moved, so stop the previously running
14307 clock and (if in clock mode) start the other one.
14308 We redisplay both clocks in case we're in ICS mode, because
14309 ICS gives us an update to both clocks after every move.
14310 Note that this routine is called *after* forwardMostMove
14311 is updated, so the last fractional tick must be subtracted
14312 from the color that is *not* on move now.
14315 SwitchClocks(int newMoveNr)
14317 long lastTickLength;
14319 int flagged = FALSE;
14323 if (StopClockTimer() && appData.clockMode) {
14324 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14325 if (!WhiteOnMove(forwardMostMove)) {
14326 if(blackNPS >= 0) lastTickLength = 0;
14327 blackTimeRemaining -= lastTickLength;
14328 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
14329 // if(pvInfoList[forwardMostMove-1].time == -1)
14330 pvInfoList[forwardMostMove-1].time = // use GUI time
14331 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
14333 if(whiteNPS >= 0) lastTickLength = 0;
14334 whiteTimeRemaining -= lastTickLength;
14335 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
14336 // if(pvInfoList[forwardMostMove-1].time == -1)
14337 pvInfoList[forwardMostMove-1].time =
14338 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
14340 flagged = CheckFlags();
14342 forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
14343 CheckTimeControl();
14345 if (flagged || !appData.clockMode) return;
14347 switch (gameMode) {
14348 case MachinePlaysBlack:
14349 case MachinePlaysWhite:
14350 case BeginningOfGame:
14351 if (pausing) return;
14355 case PlayFromGameFile:
14363 if (searchTime) { // [HGM] st: set clock of player that has to move to max time
14364 if(WhiteOnMove(forwardMostMove))
14365 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
14366 else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
14370 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
14371 whiteTimeRemaining : blackTimeRemaining);
14372 StartClockTimer(intendedTickLength);
14376 /* Stop both clocks */
14380 long lastTickLength;
14383 if (!StopClockTimer()) return;
14384 if (!appData.clockMode) return;
14388 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14389 if (WhiteOnMove(forwardMostMove)) {
14390 if(whiteNPS >= 0) lastTickLength = 0;
14391 whiteTimeRemaining -= lastTickLength;
14392 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
14394 if(blackNPS >= 0) lastTickLength = 0;
14395 blackTimeRemaining -= lastTickLength;
14396 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
14401 /* Start clock of player on move. Time may have been reset, so
14402 if clock is already running, stop and restart it. */
14406 (void) StopClockTimer(); /* in case it was running already */
14407 DisplayBothClocks();
14408 if (CheckFlags()) return;
14410 if (!appData.clockMode) return;
14411 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
14413 GetTimeMark(&tickStartTM);
14414 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
14415 whiteTimeRemaining : blackTimeRemaining);
14417 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
14418 whiteNPS = blackNPS = -1;
14419 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
14420 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
14421 whiteNPS = first.nps;
14422 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
14423 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
14424 blackNPS = first.nps;
14425 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
14426 whiteNPS = second.nps;
14427 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
14428 blackNPS = second.nps;
14429 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
14431 StartClockTimer(intendedTickLength);
14438 long second, minute, hour, day;
14440 static char buf[32];
14442 if (ms > 0 && ms <= 9900) {
14443 /* convert milliseconds to tenths, rounding up */
14444 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
14446 sprintf(buf, " %03.1f ", tenths/10.0);
14450 /* convert milliseconds to seconds, rounding up */
14451 /* use floating point to avoid strangeness of integer division
14452 with negative dividends on many machines */
14453 second = (long) floor(((double) (ms + 999L)) / 1000.0);
14460 day = second / (60 * 60 * 24);
14461 second = second % (60 * 60 * 24);
14462 hour = second / (60 * 60);
14463 second = second % (60 * 60);
14464 minute = second / 60;
14465 second = second % 60;
14468 sprintf(buf, " %s%ld:%02ld:%02ld:%02ld ",
14469 sign, day, hour, minute, second);
14471 sprintf(buf, " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
14473 sprintf(buf, " %s%2ld:%02ld ", sign, minute, second);
14480 * This is necessary because some C libraries aren't ANSI C compliant yet.
14483 StrStr(string, match)
14484 char *string, *match;
14488 length = strlen(match);
14490 for (i = strlen(string) - length; i >= 0; i--, string++)
14491 if (!strncmp(match, string, length))
14498 StrCaseStr(string, match)
14499 char *string, *match;
14503 length = strlen(match);
14505 for (i = strlen(string) - length; i >= 0; i--, string++) {
14506 for (j = 0; j < length; j++) {
14507 if (ToLower(match[j]) != ToLower(string[j]))
14510 if (j == length) return string;
14524 c1 = ToLower(*s1++);
14525 c2 = ToLower(*s2++);
14526 if (c1 > c2) return 1;
14527 if (c1 < c2) return -1;
14528 if (c1 == NULLCHAR) return 0;
14537 return isupper(c) ? tolower(c) : c;
14545 return islower(c) ? toupper(c) : c;
14547 #endif /* !_amigados */
14555 if ((ret = (char *) malloc(strlen(s) + 1))) {
14562 StrSavePtr(s, savePtr)
14563 char *s, **savePtr;
14568 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
14569 strcpy(*savePtr, s);
14581 clock = time((time_t *)NULL);
14582 tm = localtime(&clock);
14583 sprintf(buf, "%04d.%02d.%02d",
14584 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
14585 return StrSave(buf);
14590 PositionToFEN(move, overrideCastling)
14592 char *overrideCastling;
14594 int i, j, fromX, fromY, toX, toY;
14601 whiteToPlay = (gameMode == EditPosition) ?
14602 !blackPlaysFirst : (move % 2 == 0);
14605 /* Piece placement data */
14606 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
14608 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
14609 if (boards[move][i][j] == EmptySquare) {
14611 } else { ChessSquare piece = boards[move][i][j];
14612 if (emptycount > 0) {
14613 if(emptycount<10) /* [HGM] can be >= 10 */
14614 *p++ = '0' + emptycount;
14615 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
14618 if(PieceToChar(piece) == '+') {
14619 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
14621 piece = (ChessSquare)(DEMOTED piece);
14623 *p++ = PieceToChar(piece);
14625 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
14626 p[-1] = PieceToChar((ChessSquare)(DEMOTED piece));
14631 if (emptycount > 0) {
14632 if(emptycount<10) /* [HGM] can be >= 10 */
14633 *p++ = '0' + emptycount;
14634 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
14641 /* [HGM] print Crazyhouse or Shogi holdings */
14642 if( gameInfo.holdingsWidth ) {
14643 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
14645 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
14646 piece = boards[move][i][BOARD_WIDTH-1];
14647 if( piece != EmptySquare )
14648 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
14649 *p++ = PieceToChar(piece);
14651 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
14652 piece = boards[move][BOARD_HEIGHT-i-1][0];
14653 if( piece != EmptySquare )
14654 for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
14655 *p++ = PieceToChar(piece);
14658 if( q == p ) *p++ = '-';
14664 *p++ = whiteToPlay ? 'w' : 'b';
14667 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
14668 while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' '; else --p;
14670 if(nrCastlingRights) {
14672 if(gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) {
14673 /* [HGM] write directly from rights */
14674 if(boards[move][CASTLING][2] != NoRights &&
14675 boards[move][CASTLING][0] != NoRights )
14676 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
14677 if(boards[move][CASTLING][2] != NoRights &&
14678 boards[move][CASTLING][1] != NoRights )
14679 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
14680 if(boards[move][CASTLING][5] != NoRights &&
14681 boards[move][CASTLING][3] != NoRights )
14682 *p++ = boards[move][CASTLING][3] + AAA;
14683 if(boards[move][CASTLING][5] != NoRights &&
14684 boards[move][CASTLING][4] != NoRights )
14685 *p++ = boards[move][CASTLING][4] + AAA;
14688 /* [HGM] write true castling rights */
14689 if( nrCastlingRights == 6 ) {
14690 if(boards[move][CASTLING][0] == BOARD_RGHT-1 &&
14691 boards[move][CASTLING][2] != NoRights ) *p++ = 'K';
14692 if(boards[move][CASTLING][1] == BOARD_LEFT &&
14693 boards[move][CASTLING][2] != NoRights ) *p++ = 'Q';
14694 if(boards[move][CASTLING][3] == BOARD_RGHT-1 &&
14695 boards[move][CASTLING][5] != NoRights ) *p++ = 'k';
14696 if(boards[move][CASTLING][4] == BOARD_LEFT &&
14697 boards[move][CASTLING][5] != NoRights ) *p++ = 'q';
14700 if (q == p) *p++ = '-'; /* No castling rights */
14704 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
14705 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
14706 /* En passant target square */
14707 if (move > backwardMostMove) {
14708 fromX = moveList[move - 1][0] - AAA;
14709 fromY = moveList[move - 1][1] - ONE;
14710 toX = moveList[move - 1][2] - AAA;
14711 toY = moveList[move - 1][3] - ONE;
14712 if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
14713 toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
14714 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
14716 /* 2-square pawn move just happened */
14718 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
14722 } else if(move == backwardMostMove) {
14723 // [HGM] perhaps we should always do it like this, and forget the above?
14724 if((signed char)boards[move][EP_STATUS] >= 0) {
14725 *p++ = boards[move][EP_STATUS] + AAA;
14726 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
14737 /* [HGM] find reversible plies */
14738 { int i = 0, j=move;
14740 if (appData.debugMode) { int k;
14741 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
14742 for(k=backwardMostMove; k<=forwardMostMove; k++)
14743 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
14747 while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
14748 if( j == backwardMostMove ) i += initialRulePlies;
14749 sprintf(p, "%d ", i);
14750 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
14752 /* Fullmove number */
14753 sprintf(p, "%d", (move / 2) + 1);
14755 return StrSave(buf);
14759 ParseFEN(board, blackPlaysFirst, fen)
14761 int *blackPlaysFirst;
14771 /* [HGM] by default clear Crazyhouse holdings, if present */
14772 if(gameInfo.holdingsWidth) {
14773 for(i=0; i<BOARD_HEIGHT; i++) {
14774 board[i][0] = EmptySquare; /* black holdings */
14775 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
14776 board[i][1] = (ChessSquare) 0; /* black counts */
14777 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
14781 /* Piece placement data */
14782 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
14785 if (*p == '/' || *p == ' ' || (*p == '[' && i == 0) ) {
14786 if (*p == '/') p++;
14787 emptycount = gameInfo.boardWidth - j;
14788 while (emptycount--)
14789 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
14791 #if(BOARD_FILES >= 10)
14792 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
14793 p++; emptycount=10;
14794 if (j + emptycount > gameInfo.boardWidth) return FALSE;
14795 while (emptycount--)
14796 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
14798 } else if (isdigit(*p)) {
14799 emptycount = *p++ - '0';
14800 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
14801 if (j + emptycount > gameInfo.boardWidth) return FALSE;
14802 while (emptycount--)
14803 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
14804 } else if (*p == '+' || isalpha(*p)) {
14805 if (j >= gameInfo.boardWidth) return FALSE;
14807 piece = CharToPiece(*++p);
14808 if(piece == EmptySquare) return FALSE; /* unknown piece */
14809 piece = (ChessSquare) (PROMOTED piece ); p++;
14810 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
14811 } else piece = CharToPiece(*p++);
14813 if(piece==EmptySquare) return FALSE; /* unknown piece */
14814 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
14815 piece = (ChessSquare) (PROMOTED piece);
14816 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
14819 board[i][(j++)+gameInfo.holdingsWidth] = piece;
14825 while (*p == '/' || *p == ' ') p++;
14827 /* [HGM] look for Crazyhouse holdings here */
14828 while(*p==' ') p++;
14829 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
14831 if(*p == '-' ) *p++; /* empty holdings */ else {
14832 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
14833 /* if we would allow FEN reading to set board size, we would */
14834 /* have to add holdings and shift the board read so far here */
14835 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
14837 if((int) piece >= (int) BlackPawn ) {
14838 i = (int)piece - (int)BlackPawn;
14839 i = PieceToNumber((ChessSquare)i);
14840 if( i >= gameInfo.holdingsSize ) return FALSE;
14841 board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
14842 board[BOARD_HEIGHT-1-i][1]++; /* black counts */
14844 i = (int)piece - (int)WhitePawn;
14845 i = PieceToNumber((ChessSquare)i);
14846 if( i >= gameInfo.holdingsSize ) return FALSE;
14847 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
14848 board[i][BOARD_WIDTH-2]++; /* black holdings */
14852 if(*p == ']') *p++;
14855 while(*p == ' ') p++;
14859 if(appData.colorNickNames) {
14860 if( c == appData.colorNickNames[0] ) c = 'w'; else
14861 if( c == appData.colorNickNames[1] ) c = 'b';
14865 *blackPlaysFirst = FALSE;
14868 *blackPlaysFirst = TRUE;
14874 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
14875 /* return the extra info in global variiables */
14877 /* set defaults in case FEN is incomplete */
14878 board[EP_STATUS] = EP_UNKNOWN;
14879 for(i=0; i<nrCastlingRights; i++ ) {
14880 board[CASTLING][i] =
14881 gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom ? NoRights : initialRights[i];
14882 } /* assume possible unless obviously impossible */
14883 if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
14884 if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
14885 if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
14886 && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
14887 if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
14888 if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
14889 if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
14890 && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
14893 while(*p==' ') p++;
14894 if(nrCastlingRights) {
14895 if(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-') {
14896 /* castling indicator present, so default becomes no castlings */
14897 for(i=0; i<nrCastlingRights; i++ ) {
14898 board[CASTLING][i] = NoRights;
14901 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
14902 (gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) &&
14903 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
14904 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
14905 char c = *p++; int whiteKingFile=NoRights, blackKingFile=NoRights;
14907 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
14908 if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
14909 if(board[0 ][i] == WhiteKing) whiteKingFile = i;
14911 if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
14912 whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
14913 if(whiteKingFile == NoRights || board[0][whiteKingFile] != WhiteUnicorn
14914 && board[0][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
14915 if(blackKingFile == NoRights || board[BOARD_HEIGHT-1][blackKingFile] != BlackUnicorn
14916 && board[BOARD_HEIGHT-1][blackKingFile] != BlackKing) blackKingFile = NoRights;
14919 for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
14920 board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
14921 board[CASTLING][2] = whiteKingFile;
14924 for(i=BOARD_LEFT; i<BOARD_RGHT && board[0][i]!=WhiteRook && i<whiteKingFile; i++);
14925 board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
14926 board[CASTLING][2] = whiteKingFile;
14929 for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
14930 board[CASTLING][3] = i != blackKingFile ? i : NoRights;
14931 board[CASTLING][5] = blackKingFile;
14934 for(i=BOARD_LEFT; i<BOARD_RGHT && board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
14935 board[CASTLING][4] = i != blackKingFile ? i : NoRights;
14936 board[CASTLING][5] = blackKingFile;
14939 default: /* FRC castlings */
14940 if(c >= 'a') { /* black rights */
14941 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
14942 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
14943 if(i == BOARD_RGHT) break;
14944 board[CASTLING][5] = i;
14946 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
14947 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
14949 board[CASTLING][3] = c;
14951 board[CASTLING][4] = c;
14952 } else { /* white rights */
14953 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
14954 if(board[0][i] == WhiteKing) break;
14955 if(i == BOARD_RGHT) break;
14956 board[CASTLING][2] = i;
14957 c -= AAA - 'a' + 'A';
14958 if(board[0][c] >= WhiteKing) break;
14960 board[CASTLING][0] = c;
14962 board[CASTLING][1] = c;
14966 for(i=0; i<nrCastlingRights; i++)
14967 if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
14968 if (appData.debugMode) {
14969 fprintf(debugFP, "FEN castling rights:");
14970 for(i=0; i<nrCastlingRights; i++)
14971 fprintf(debugFP, " %d", board[CASTLING][i]);
14972 fprintf(debugFP, "\n");
14975 while(*p==' ') p++;
14978 /* read e.p. field in games that know e.p. capture */
14979 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
14980 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
14982 p++; board[EP_STATUS] = EP_NONE;
14984 char c = *p++ - AAA;
14986 if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
14987 if(*p >= '0' && *p <='9') *p++;
14988 board[EP_STATUS] = c;
14993 if(sscanf(p, "%d", &i) == 1) {
14994 FENrulePlies = i; /* 50-move ply counter */
14995 /* (The move number is still ignored) */
15002 EditPositionPasteFEN(char *fen)
15005 Board initial_position;
15007 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
15008 DisplayError(_("Bad FEN position in clipboard"), 0);
15011 int savedBlackPlaysFirst = blackPlaysFirst;
15012 EditPositionEvent();
15013 blackPlaysFirst = savedBlackPlaysFirst;
15014 CopyBoard(boards[0], initial_position);
15015 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
15016 EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
15017 DisplayBothClocks();
15018 DrawPosition(FALSE, boards[currentMove]);
15023 static char cseq[12] = "\\ ";
15025 Boolean set_cont_sequence(char *new_seq)
15030 // handle bad attempts to set the sequence
15032 return 0; // acceptable error - no debug
15034 len = strlen(new_seq);
15035 ret = (len > 0) && (len < sizeof(cseq));
15037 strcpy(cseq, new_seq);
15038 else if (appData.debugMode)
15039 fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
15044 reformat a source message so words don't cross the width boundary. internal
15045 newlines are not removed. returns the wrapped size (no null character unless
15046 included in source message). If dest is NULL, only calculate the size required
15047 for the dest buffer. lp argument indicats line position upon entry, and it's
15048 passed back upon exit.
15050 int wrap(char *dest, char *src, int count, int width, int *lp)
15052 int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
15054 cseq_len = strlen(cseq);
15055 old_line = line = *lp;
15056 ansi = len = clen = 0;
15058 for (i=0; i < count; i++)
15060 if (src[i] == '\033')
15063 // if we hit the width, back up
15064 if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
15066 // store i & len in case the word is too long
15067 old_i = i, old_len = len;
15069 // find the end of the last word
15070 while (i && src[i] != ' ' && src[i] != '\n')
15076 // word too long? restore i & len before splitting it
15077 if ((old_i-i+clen) >= width)
15084 if (i && src[i-1] == ' ')
15087 if (src[i] != ' ' && src[i] != '\n')
15094 // now append the newline and continuation sequence
15099 strncpy(dest+len, cseq, cseq_len);
15107 dest[len] = src[i];
15111 if (src[i] == '\n')
15116 if (dest && appData.debugMode)
15118 fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
15119 count, width, line, len, *lp);
15120 show_bytes(debugFP, src, count);
15121 fprintf(debugFP, "\ndest: ");
15122 show_bytes(debugFP, dest, len);
15123 fprintf(debugFP, "\n");
15125 *lp = dest ? line : old_line;
15130 // [HGM] vari: routines for shelving variations
15133 PushTail(int firstMove, int lastMove)
15135 int i, j, nrMoves = lastMove - firstMove;
15137 if(appData.icsActive) { // only in local mode
15138 forwardMostMove = currentMove; // mimic old ICS behavior
15141 if(storedGames >= MAX_VARIATIONS-1) return;
15143 // push current tail of game on stack
15144 savedResult[storedGames] = gameInfo.result;
15145 savedDetails[storedGames] = gameInfo.resultDetails;
15146 gameInfo.resultDetails = NULL;
15147 savedFirst[storedGames] = firstMove;
15148 savedLast [storedGames] = lastMove;
15149 savedFramePtr[storedGames] = framePtr;
15150 framePtr -= nrMoves; // reserve space for the boards
15151 for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
15152 CopyBoard(boards[framePtr+i], boards[firstMove+i]);
15153 for(j=0; j<MOVE_LEN; j++)
15154 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
15155 for(j=0; j<2*MOVE_LEN; j++)
15156 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
15157 timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
15158 timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
15159 pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
15160 pvInfoList[firstMove+i-1].depth = 0;
15161 commentList[framePtr+i] = commentList[firstMove+i];
15162 commentList[firstMove+i] = NULL;
15166 forwardMostMove = firstMove; // truncate game so we can start variation
15167 if(storedGames == 1) GreyRevert(FALSE);
15171 PopTail(Boolean annotate)
15174 char buf[8000], moveBuf[20];
15176 if(appData.icsActive) return FALSE; // only in local mode
15177 if(!storedGames) return FALSE; // sanity
15178 CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
15181 ToNrEvent(savedFirst[storedGames]); // sets currentMove
15182 nrMoves = savedLast[storedGames] - currentMove;
15185 if(!WhiteOnMove(currentMove)) sprintf(buf, "(%d...", currentMove+2>>1);
15186 else strcpy(buf, "(");
15187 for(i=currentMove; i<forwardMostMove; i++) {
15189 sprintf(moveBuf, " %d. %s", i+2>>1, SavePart(parseList[i]));
15190 else sprintf(moveBuf, " %s", SavePart(parseList[i]));
15191 strcat(buf, moveBuf);
15192 if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
15193 if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
15197 for(i=1; i<=nrMoves; i++) { // copy last variation back
15198 CopyBoard(boards[currentMove+i], boards[framePtr+i]);
15199 for(j=0; j<MOVE_LEN; j++)
15200 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
15201 for(j=0; j<2*MOVE_LEN; j++)
15202 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
15203 timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
15204 timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
15205 pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
15206 if(commentList[currentMove+i]) free(commentList[currentMove+i]);
15207 commentList[currentMove+i] = commentList[framePtr+i];
15208 commentList[framePtr+i] = NULL;
15210 if(annotate) AppendComment(currentMove+1, buf, FALSE);
15211 framePtr = savedFramePtr[storedGames];
15212 gameInfo.result = savedResult[storedGames];
15213 if(gameInfo.resultDetails != NULL) {
15214 free(gameInfo.resultDetails);
15216 gameInfo.resultDetails = savedDetails[storedGames];
15217 forwardMostMove = currentMove + nrMoves;
15218 if(storedGames == 0) GreyRevert(TRUE);
15224 { // remove all shelved variations
15226 for(i=0; i<storedGames; i++) {
15227 if(savedDetails[i])
15228 free(savedDetails[i]);
15229 savedDetails[i] = NULL;
15231 for(i=framePtr; i<MAX_MOVES; i++) {
15232 if(commentList[i]) free(commentList[i]);
15233 commentList[i] = NULL;
15235 framePtr = MAX_MOVES-1;
15240 LoadVariation(int index, char *text)
15241 { // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
15242 char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
15243 int level = 0, move;
15245 if(gameMode != EditGame && gameMode != AnalyzeMode) return;
15246 // first find outermost bracketing variation
15247 while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
15248 if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
15249 if(*p == '{') wait = '}'; else
15250 if(*p == '[') wait = ']'; else
15251 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
15252 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
15254 if(*p == wait) wait = NULLCHAR; // closing ]} found
15257 if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
15258 if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
15259 end[1] = NULLCHAR; // clip off comment beyond variation
15260 ToNrEvent(currentMove-1);
15261 PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
15262 // kludge: use ParsePV() to append variation to game
15263 move = currentMove;
15264 ParsePV(start, TRUE);
15265 forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
15266 ClearPremoveHighlights();
15268 ToNrEvent(currentMove+1);