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, 2011 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) );
60 int flock(int f, int code);
65 #define DoSleep( n ) if( (n) >= 0) sleep(n)
75 #include <sys/types.h>
84 #else /* not STDC_HEADERS */
87 # else /* not HAVE_STRING_H */
89 # endif /* not HAVE_STRING_H */
90 #endif /* not STDC_HEADERS */
93 # include <sys/fcntl.h>
94 #else /* not HAVE_SYS_FCNTL_H */
97 # endif /* HAVE_FCNTL_H */
98 #endif /* not HAVE_SYS_FCNTL_H */
100 #if TIME_WITH_SYS_TIME
101 # include <sys/time.h>
105 # include <sys/time.h>
111 #if defined(_amigados) && !defined(__GNUC__)
116 extern int gettimeofday(struct timeval *, struct timezone *);
124 #include "frontend.h"
131 #include "backendz.h"
135 # define _(s) gettext (s)
136 # define N_(s) gettext_noop (s)
137 # define T_(s) gettext(s)
150 /* A point in time */
152 long sec; /* Assuming this is >= 32 bits */
153 int ms; /* Assuming this is >= 16 bits */
156 int establish P((void));
157 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
158 char *buf, int count, int error));
159 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
160 char *buf, int count, int error));
161 void ics_printf P((char *format, ...));
162 void SendToICS P((char *s));
163 void SendToICSDelayed P((char *s, long msdelay));
164 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar));
165 void HandleMachineMove P((char *message, ChessProgramState *cps));
166 int AutoPlayOneMove P((void));
167 int LoadGameOneMove P((ChessMove readAhead));
168 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
169 int LoadPositionFromFile P((char *filename, int n, char *title));
170 int SavePositionToFile P((char *filename));
171 void ApplyMove P((int fromX, int fromY, int toX, int toY, int promoChar,
173 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
174 void ShowMove P((int fromX, int fromY, int toX, int toY));
175 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
176 /*char*/int promoChar));
177 void BackwardInner P((int target));
178 void ForwardInner P((int target));
179 int Adjudicate P((ChessProgramState *cps));
180 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
181 void EditPositionDone P((Boolean fakeRights));
182 void PrintOpponents P((FILE *fp));
183 void PrintPosition P((FILE *fp, int move));
184 void StartChessProgram P((ChessProgramState *cps));
185 void SendToProgram P((char *message, ChessProgramState *cps));
186 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
187 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
188 char *buf, int count, int error));
189 void SendTimeControl P((ChessProgramState *cps,
190 int mps, long tc, int inc, int sd, int st));
191 char *TimeControlTagValue P((void));
192 void Attention P((ChessProgramState *cps));
193 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
194 void ResurrectChessProgram P((void));
195 void DisplayComment P((int moveNumber, char *text));
196 void DisplayMove P((int moveNumber));
198 void ParseGameHistory P((char *game));
199 void ParseBoard12 P((char *string));
200 void KeepAlive P((void));
201 void StartClocks P((void));
202 void SwitchClocks P((int nr));
203 void StopClocks P((void));
204 void ResetClocks P((void));
205 char *PGNDate P((void));
206 void SetGameInfo P((void));
207 Boolean ParseFEN P((Board board, int *blackPlaysFirst, char *fen));
208 int RegisterMove P((void));
209 void MakeRegisteredMove P((void));
210 void TruncateGame P((void));
211 int looking_at P((char *, int *, char *));
212 void CopyPlayerNameIntoFileName P((char **, char *));
213 char *SavePart P((char *));
214 int SaveGameOldStyle P((FILE *));
215 int SaveGamePGN P((FILE *));
216 void GetTimeMark P((TimeMark *));
217 long SubtractTimeMarks P((TimeMark *, TimeMark *));
218 int CheckFlags P((void));
219 long NextTickLength P((long));
220 void CheckTimeControl P((void));
221 void show_bytes P((FILE *, char *, int));
222 int string_to_rating P((char *str));
223 void ParseFeatures P((char* args, ChessProgramState *cps));
224 void InitBackEnd3 P((void));
225 void FeatureDone P((ChessProgramState* cps, int val));
226 void InitChessProgram P((ChessProgramState *cps, int setup));
227 void OutputKibitz(int window, char *text);
228 int PerpetualChase(int first, int last);
229 int EngineOutputIsUp();
230 void InitDrawingSizes(int x, int y);
233 extern void ConsoleCreate();
236 ChessProgramState *WhitePlayer();
237 void InsertIntoMemo P((int which, char *text)); // [HGM] kibitz: in engineo.c
238 int VerifyDisplayMode P(());
240 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
241 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
242 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
243 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
244 void ics_update_width P((int new_width));
245 extern char installDir[MSG_SIZ];
246 VariantClass startVariant; /* [HGM] nicks: initial variant */
248 extern int tinyLayout, smallLayout;
249 ChessProgramStats programStats;
250 char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
252 static int exiting = 0; /* [HGM] moved to top */
253 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
254 int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
255 Board partnerBoard; /* [HGM] bughouse: for peeking at partner game */
256 int partnerHighlight[2];
257 Boolean partnerBoardValid = 0;
258 char partnerStatus[MSG_SIZ];
260 Boolean originalFlip;
261 Boolean twoBoards = 0;
262 char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
263 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
264 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
265 int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
266 Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing */
267 int opponentKibitzes;
268 int lastSavedGame; /* [HGM] save: ID of game */
269 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
270 extern int chatCount;
272 char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
273 char lastMsg[MSG_SIZ];
274 ChessSquare pieceSweep = EmptySquare;
275 ChessSquare promoSweep = EmptySquare, defaultPromoChoice;
276 int promoDefaultAltered;
278 /* States for ics_getting_history */
280 #define H_REQUESTED 1
281 #define H_GOT_REQ_HEADER 2
282 #define H_GOT_UNREQ_HEADER 3
283 #define H_GETTING_MOVES 4
284 #define H_GOT_UNWANTED_HEADER 5
286 /* whosays values for GameEnds */
295 /* Maximum number of games in a cmail message */
296 #define CMAIL_MAX_GAMES 20
298 /* Different types of move when calling RegisterMove */
300 #define CMAIL_RESIGN 1
302 #define CMAIL_ACCEPT 3
304 /* Different types of result to remember for each game */
305 #define CMAIL_NOT_RESULT 0
306 #define CMAIL_OLD_RESULT 1
307 #define CMAIL_NEW_RESULT 2
309 /* Telnet protocol constants */
320 safeStrCpy( char *dst, const char *src, size_t count )
323 assert( dst != NULL );
324 assert( src != NULL );
327 for(i=0; i<count; i++) if((dst[i] = src[i]) == NULLCHAR) break;
328 if( i == count && dst[count-1] != NULLCHAR)
330 dst[ count-1 ] = '\0'; // make sure incomplete copy still null-terminated
331 if(appData.debugMode)
332 fprintf(debugFP, "safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst, (int)count);
338 /* Some compiler can't cast u64 to double
339 * This function do the job for us:
341 * We use the highest bit for cast, this only
342 * works if the highest bit is not
343 * in use (This should not happen)
345 * We used this for all compiler
348 u64ToDouble(u64 value)
351 u64 tmp = value & u64Const(0x7fffffffffffffff);
352 r = (double)(s64)tmp;
353 if (value & u64Const(0x8000000000000000))
354 r += 9.2233720368547758080e18; /* 2^63 */
358 /* Fake up flags for now, as we aren't keeping track of castling
359 availability yet. [HGM] Change of logic: the flag now only
360 indicates the type of castlings allowed by the rule of the game.
361 The actual rights themselves are maintained in the array
362 castlingRights, as part of the game history, and are not probed
368 int flags = F_ALL_CASTLE_OK;
369 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
370 switch (gameInfo.variant) {
372 flags &= ~F_ALL_CASTLE_OK;
373 case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
374 flags |= F_IGNORE_CHECK;
376 flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
379 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
381 case VariantKriegspiel:
382 flags |= F_KRIEGSPIEL_CAPTURE;
384 case VariantCapaRandom:
385 case VariantFischeRandom:
386 flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
387 case VariantNoCastle:
388 case VariantShatranj:
391 flags &= ~F_ALL_CASTLE_OK;
399 FILE *gameFileFP, *debugFP;
402 [AS] Note: sometimes, the sscanf() function is used to parse the input
403 into a fixed-size buffer. Because of this, we must be prepared to
404 receive strings as long as the size of the input buffer, which is currently
405 set to 4K for Windows and 8K for the rest.
406 So, we must either allocate sufficiently large buffers here, or
407 reduce the size of the input buffer in the input reading part.
410 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
411 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
412 char thinkOutput1[MSG_SIZ*10];
414 ChessProgramState first, second;
416 /* premove variables */
419 int premoveFromX = 0;
420 int premoveFromY = 0;
421 int premovePromoChar = 0;
423 Boolean alarmSounded;
424 /* end premove variables */
426 char *ics_prefix = "$";
427 int ics_type = ICS_GENERIC;
429 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
430 int pauseExamForwardMostMove = 0;
431 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
432 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
433 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
434 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
435 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
436 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
437 int whiteFlag = FALSE, blackFlag = FALSE;
438 int userOfferedDraw = FALSE;
439 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
440 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
441 int cmailMoveType[CMAIL_MAX_GAMES];
442 long ics_clock_paused = 0;
443 ProcRef icsPR = NoProc, cmailPR = NoProc;
444 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
445 GameMode gameMode = BeginningOfGame;
446 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
447 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
448 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
449 int hiddenThinkOutputState = 0; /* [AS] */
450 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
451 int adjudicateLossPlies = 6;
452 char white_holding[64], black_holding[64];
453 TimeMark lastNodeCountTime;
454 long lastNodeCount=0;
455 int shiftKey; // [HGM] set by mouse handler
457 int have_sent_ICS_logon = 0;
459 int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
460 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack;
461 long timeControl_2; /* [AS] Allow separate time controls */
462 char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC; /* [HGM] secondary TC: merge of MPS, TC and inc */
463 long timeRemaining[2][MAX_MOVES];
465 TimeMark programStartTime;
466 char ics_handle[MSG_SIZ];
467 int have_set_title = 0;
469 /* animateTraining preserves the state of appData.animate
470 * when Training mode is activated. This allows the
471 * response to be animated when appData.animate == TRUE and
472 * appData.animateDragging == TRUE.
474 Boolean animateTraining;
480 Board boards[MAX_MOVES];
481 /* [HGM] Following 7 needed for accurate legality tests: */
482 signed char castlingRank[BOARD_FILES]; // and corresponding ranks
483 signed char initialRights[BOARD_FILES];
484 int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
485 int initialRulePlies, FENrulePlies;
486 FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
489 int mute; // mute all sounds
491 // [HGM] vari: next 12 to save and restore variations
492 #define MAX_VARIATIONS 10
493 int framePtr = MAX_MOVES-1; // points to free stack entry
495 int savedFirst[MAX_VARIATIONS];
496 int savedLast[MAX_VARIATIONS];
497 int savedFramePtr[MAX_VARIATIONS];
498 char *savedDetails[MAX_VARIATIONS];
499 ChessMove savedResult[MAX_VARIATIONS];
501 void PushTail P((int firstMove, int lastMove));
502 Boolean PopTail P((Boolean annotate));
503 void CleanupTail P((void));
505 ChessSquare FIDEArray[2][BOARD_FILES] = {
506 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
507 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
508 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
509 BlackKing, BlackBishop, BlackKnight, BlackRook }
512 ChessSquare twoKingsArray[2][BOARD_FILES] = {
513 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
514 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
515 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
516 BlackKing, BlackKing, BlackKnight, BlackRook }
519 ChessSquare KnightmateArray[2][BOARD_FILES] = {
520 { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
521 WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
522 { BlackRook, BlackMan, BlackBishop, BlackQueen,
523 BlackUnicorn, BlackBishop, BlackMan, BlackRook }
526 ChessSquare SpartanArray[2][BOARD_FILES] = {
527 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
528 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
529 { BlackAlfil, BlackMarshall, BlackKing, BlackDragon,
530 BlackDragon, BlackKing, BlackAngel, BlackAlfil }
533 ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
534 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
535 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
536 { BlackCardinal, BlackAlfil, BlackMarshall, BlackAngel,
537 BlackKing, BlackMarshall, BlackAlfil, BlackCardinal }
540 ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
541 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
542 WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
543 { BlackRook, BlackKnight, BlackAlfil, BlackKing,
544 BlackFerz, BlackAlfil, BlackKnight, BlackRook }
547 ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
548 { WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
549 WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
550 { BlackRook, BlackKnight, BlackMan, BlackFerz,
551 BlackKing, BlackMan, BlackKnight, BlackRook }
555 #if (BOARD_FILES>=10)
556 ChessSquare ShogiArray[2][BOARD_FILES] = {
557 { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
558 WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
559 { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
560 BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
563 ChessSquare XiangqiArray[2][BOARD_FILES] = {
564 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
565 WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
566 { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
567 BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
570 ChessSquare CapablancaArray[2][BOARD_FILES] = {
571 { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
572 WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
573 { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
574 BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
577 ChessSquare GreatArray[2][BOARD_FILES] = {
578 { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
579 WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
580 { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
581 BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
584 ChessSquare JanusArray[2][BOARD_FILES] = {
585 { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
586 WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
587 { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
588 BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
592 ChessSquare GothicArray[2][BOARD_FILES] = {
593 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
594 WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
595 { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
596 BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
599 #define GothicArray CapablancaArray
603 ChessSquare FalconArray[2][BOARD_FILES] = {
604 { WhiteRook, WhiteKnight, WhiteBishop, WhiteLance, WhiteQueen,
605 WhiteKing, WhiteLance, WhiteBishop, WhiteKnight, WhiteRook },
606 { BlackRook, BlackKnight, BlackBishop, BlackLance, BlackQueen,
607 BlackKing, BlackLance, BlackBishop, BlackKnight, BlackRook }
610 #define FalconArray CapablancaArray
613 #else // !(BOARD_FILES>=10)
614 #define XiangqiPosition FIDEArray
615 #define CapablancaArray FIDEArray
616 #define GothicArray FIDEArray
617 #define GreatArray FIDEArray
618 #endif // !(BOARD_FILES>=10)
620 #if (BOARD_FILES>=12)
621 ChessSquare CourierArray[2][BOARD_FILES] = {
622 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
623 WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
624 { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
625 BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
627 #else // !(BOARD_FILES>=12)
628 #define CourierArray CapablancaArray
629 #endif // !(BOARD_FILES>=12)
632 Board initialPosition;
635 /* Convert str to a rating. Checks for special cases of "----",
637 "++++", etc. Also strips ()'s */
639 string_to_rating(str)
642 while(*str && !isdigit(*str)) ++str;
644 return 0; /* One of the special "no rating" cases */
652 /* Init programStats */
653 programStats.movelist[0] = 0;
654 programStats.depth = 0;
655 programStats.nr_moves = 0;
656 programStats.moves_left = 0;
657 programStats.nodes = 0;
658 programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
659 programStats.score = 0;
660 programStats.got_only_move = 0;
661 programStats.got_fail = 0;
662 programStats.line_is_book = 0;
667 { // [HGM] moved some code here from InitBackend1 that has to be done after both engines have contributed their settings
668 if (appData.firstPlaysBlack) {
669 first.twoMachinesColor = "black\n";
670 second.twoMachinesColor = "white\n";
672 first.twoMachinesColor = "white\n";
673 second.twoMachinesColor = "black\n";
676 first.other = &second;
677 second.other = &first;
680 if(appData.timeOddsMode) {
681 norm = appData.timeOdds[0];
682 if(norm > appData.timeOdds[1]) norm = appData.timeOdds[1];
684 first.timeOdds = appData.timeOdds[0]/norm;
685 second.timeOdds = appData.timeOdds[1]/norm;
688 if(programVersion) free(programVersion);
689 if (appData.noChessProgram) {
690 programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
691 sprintf(programVersion, "%s", PACKAGE_STRING);
693 /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
694 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
695 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
700 UnloadEngine(ChessProgramState *cps)
702 /* Kill off first chess program */
703 if (cps->isr != NULL)
704 RemoveInputSource(cps->isr);
707 if (cps->pr != NoProc) {
709 DoSleep( appData.delayBeforeQuit );
710 SendToProgram("quit\n", cps);
711 DoSleep( appData.delayAfterQuit );
712 DestroyChildProcess(cps->pr, cps->useSigterm);
718 ClearOptions(ChessProgramState *cps)
721 cps->nrOptions = cps->comboCnt = 0;
722 for(i=0; i<MAX_OPTIONS; i++) {
723 cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
724 cps->option[i].textValue = 0;
728 char *engineNames[] = {
733 InitEngine(ChessProgramState *cps, int n)
734 { // [HGM] all engine initialiation put in a function that does one engine
738 cps->which = engineNames[n];
739 cps->maybeThinking = FALSE;
743 cps->sendDrawOffers = 1;
745 cps->program = appData.chessProgram[n];
746 cps->host = appData.host[n];
747 cps->dir = appData.directory[n];
748 cps->initString = appData.engInitString[n];
749 cps->computerString = appData.computerString[n];
750 cps->useSigint = TRUE;
751 cps->useSigterm = TRUE;
752 cps->reuse = appData.reuse[n];
753 cps->nps = appData.NPS[n]; // [HGM] nps: copy nodes per second
754 cps->useSetboard = FALSE;
756 cps->usePing = FALSE;
759 cps->usePlayother = FALSE;
760 cps->useColors = TRUE;
761 cps->useUsermove = FALSE;
762 cps->sendICS = FALSE;
763 cps->sendName = appData.icsActive;
764 cps->sdKludge = FALSE;
765 cps->stKludge = FALSE;
766 TidyProgramName(cps->program, cps->host, cps->tidy);
768 safeStrCpy(cps->variants, appData.variant, MSG_SIZ);
769 cps->analysisSupport = 2; /* detect */
770 cps->analyzing = FALSE;
771 cps->initDone = FALSE;
773 /* New features added by Tord: */
774 cps->useFEN960 = FALSE;
775 cps->useOOCastle = TRUE;
776 /* End of new features added by Tord. */
777 cps->fenOverride = appData.fenOverride[n];
779 /* [HGM] time odds: set factor for each machine */
780 cps->timeOdds = appData.timeOdds[n];
782 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
783 cps->accumulateTC = appData.accumulateTC[n];
784 cps->maxNrOfSessions = 1;
788 cps->supportsNPS = UNKNOWN;
791 cps->optionSettings = appData.engOptions[n];
793 cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
794 cps->isUCI = appData.isUCI[n]; /* [AS] */
795 cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
797 if (appData.protocolVersion[n] > PROTOVER
798 || appData.protocolVersion[n] < 1)
803 len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
804 appData.protocolVersion[n]);
805 if( (len > MSG_SIZ) && appData.debugMode )
806 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
808 DisplayFatalError(buf, 0, 2);
812 cps->protocolVersion = appData.protocolVersion[n];
815 InitEngineUCI( installDir, cps ); // [HGM] moved here from winboard.c, to make available in xboard
818 ChessProgramState *savCps;
824 if(WaitForEngine(savCps, LoadEngine)) return;
825 CommonEngineInit(); // recalculate time odds
826 if(gameInfo.variant != StringToVariant(appData.variant)) {
827 // we changed variant when loading the engine; this forces us to reset
828 Reset(TRUE, savCps != &first);
829 EditGameEvent(); // for consistency with other path, as Reset changes mode
831 InitChessProgram(savCps, FALSE);
832 SendToProgram("force\n", savCps);
833 DisplayMessage("", "");
834 if (startedFromSetupPosition) SendBoard(savCps, backwardMostMove);
835 for (i = backwardMostMove; i < forwardMostMove; i++) SendMoveToProgram(i, savCps);
841 ReplaceEngine(ChessProgramState *cps, int n)
845 appData.noChessProgram = False;
846 appData.clockMode = True;
848 if(n) return; // only startup first engine immediately; second can wait
849 savCps = cps; // parameter to LoadEngine passed as globals, to allow scheduled calling :-(
856 int matched, min, sec;
858 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
859 startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
861 GetTimeMark(&programStartTime);
862 srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
865 programStats.ok_to_send = 1;
866 programStats.seen_stat = 0;
869 * Initialize game list
875 * Internet chess server status
877 if (appData.icsActive) {
878 appData.matchMode = FALSE;
879 appData.matchGames = 0;
881 appData.noChessProgram = !appData.zippyPlay;
883 appData.zippyPlay = FALSE;
884 appData.zippyTalk = FALSE;
885 appData.noChessProgram = TRUE;
887 if (*appData.icsHelper != NULLCHAR) {
888 appData.useTelnet = TRUE;
889 appData.telnetProgram = appData.icsHelper;
892 appData.zippyTalk = appData.zippyPlay = FALSE;
895 /* [AS] Initialize pv info list [HGM] and game state */
899 for( i=0; i<=framePtr; i++ ) {
900 pvInfoList[i].depth = -1;
901 boards[i][EP_STATUS] = EP_NONE;
902 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
907 * Parse timeControl resource
909 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
910 appData.movesPerSession)) {
912 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
913 DisplayFatalError(buf, 0, 2);
917 * Parse searchTime resource
919 if (*appData.searchTime != NULLCHAR) {
920 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
922 searchTime = min * 60;
923 } else if (matched == 2) {
924 searchTime = min * 60 + sec;
927 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
928 DisplayFatalError(buf, 0, 2);
932 /* [AS] Adjudication threshold */
933 adjudicateLossThreshold = appData.adjudicateLossThreshold;
935 InitEngine(&first, 0);
936 InitEngine(&second, 1);
939 if (appData.icsActive) {
940 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
941 } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
942 appData.clockMode = FALSE;
943 first.sendTime = second.sendTime = 0;
947 /* Override some settings from environment variables, for backward
948 compatibility. Unfortunately it's not feasible to have the env
949 vars just set defaults, at least in xboard. Ugh.
951 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
956 if (!appData.icsActive) {
960 /* Check for variants that are supported only in ICS mode,
961 or not at all. Some that are accepted here nevertheless
962 have bugs; see comments below.
964 VariantClass variant = StringToVariant(appData.variant);
966 case VariantBughouse: /* need four players and two boards */
967 case VariantKriegspiel: /* need to hide pieces and move details */
968 /* case VariantFischeRandom: (Fabien: moved below) */
969 len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
970 if( (len > MSG_SIZ) && appData.debugMode )
971 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
973 DisplayFatalError(buf, 0, 2);
977 case VariantLoadable:
987 len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
988 if( (len > MSG_SIZ) && appData.debugMode )
989 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
991 DisplayFatalError(buf, 0, 2);
994 case VariantXiangqi: /* [HGM] repetition rules not implemented */
995 case VariantFairy: /* [HGM] TestLegality definitely off! */
996 case VariantGothic: /* [HGM] should work */
997 case VariantCapablanca: /* [HGM] should work */
998 case VariantCourier: /* [HGM] initial forced moves not implemented */
999 case VariantShogi: /* [HGM] could still mate with pawn drop */
1000 case VariantKnightmate: /* [HGM] should work */
1001 case VariantCylinder: /* [HGM] untested */
1002 case VariantFalcon: /* [HGM] untested */
1003 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
1004 offboard interposition not understood */
1005 case VariantNormal: /* definitely works! */
1006 case VariantWildCastle: /* pieces not automatically shuffled */
1007 case VariantNoCastle: /* pieces not automatically shuffled */
1008 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
1009 case VariantLosers: /* should work except for win condition,
1010 and doesn't know captures are mandatory */
1011 case VariantSuicide: /* should work except for win condition,
1012 and doesn't know captures are mandatory */
1013 case VariantGiveaway: /* should work except for win condition,
1014 and doesn't know captures are mandatory */
1015 case VariantTwoKings: /* should work */
1016 case VariantAtomic: /* should work except for win condition */
1017 case Variant3Check: /* should work except for win condition */
1018 case VariantShatranj: /* should work except for all win conditions */
1019 case VariantMakruk: /* should work except for daw countdown */
1020 case VariantBerolina: /* might work if TestLegality is off */
1021 case VariantCapaRandom: /* should work */
1022 case VariantJanus: /* should work */
1023 case VariantSuper: /* experimental */
1024 case VariantGreat: /* experimental, requires legality testing to be off */
1025 case VariantSChess: /* S-Chess, should work */
1026 case VariantSpartan: /* should work */
1033 int NextIntegerFromString( char ** str, long * value )
1038 while( *s == ' ' || *s == '\t' ) {
1044 if( *s >= '0' && *s <= '9' ) {
1045 while( *s >= '0' && *s <= '9' ) {
1046 *value = *value * 10 + (*s - '0');
1058 int NextTimeControlFromString( char ** str, long * value )
1061 int result = NextIntegerFromString( str, &temp );
1064 *value = temp * 60; /* Minutes */
1065 if( **str == ':' ) {
1067 result = NextIntegerFromString( str, &temp );
1068 *value += temp; /* Seconds */
1075 int NextSessionFromString( char ** str, int *moves, long * tc, long *inc, int *incType)
1076 { /* [HGM] routine added to read '+moves/time' for secondary time control. */
1077 int result = -1, type = 0; long temp, temp2;
1079 if(**str != ':') return -1; // old params remain in force!
1081 if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
1082 if( NextIntegerFromString( str, &temp ) ) return -1;
1083 if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
1086 /* time only: incremental or sudden-death time control */
1087 if(**str == '+') { /* increment follows; read it */
1089 if(**str == '!') type = *(*str)++; // Bronstein TC
1090 if(result = NextIntegerFromString( str, &temp2)) return -1;
1091 *inc = temp2 * 1000;
1092 if(**str == '.') { // read fraction of increment
1093 char *start = ++(*str);
1094 if(result = NextIntegerFromString( str, &temp2)) return -1;
1096 while(start++ < *str) temp2 /= 10;
1100 *moves = 0; *tc = temp * 1000; *incType = type;
1104 (*str)++; /* classical time control */
1105 result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
1116 int GetTimeQuota(int movenr, int lastUsed, char *tcString)
1117 { /* [HGM] get time to add from the multi-session time-control string */
1118 int incType, moves=1; /* kludge to force reading of first session */
1119 long time, increment;
1122 if(!*s) return 0; // empty TC string means we ran out of the last sudden-death version
1123 if(appData.debugMode) fprintf(debugFP, "TC string = '%s'\n", tcString);
1125 if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
1126 nextSession = s; suddenDeath = moves == 0 && increment == 0;
1127 if(appData.debugMode) fprintf(debugFP, "mps=%d tc=%d inc=%d\n", moves, (int) time, (int) increment);
1128 if(movenr == -1) return time; /* last move before new session */
1129 if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
1130 if(incType == '!' && lastUsed < increment) increment = lastUsed;
1131 if(!moves) return increment; /* current session is incremental */
1132 if(movenr >= 0) movenr -= moves; /* we already finished this session */
1133 } while(movenr >= -1); /* try again for next session */
1135 return 0; // no new time quota on this move
1139 ParseTimeControl(tc, ti, mps)
1146 char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
1149 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1150 if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
1151 sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
1155 snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
1157 snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
1160 snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
1162 snprintf(buf, MSG_SIZ, ":%s", mytc);
1164 fullTimeControlString = StrSave(buf); // this should now be in PGN format
1166 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1171 /* Parse second time control */
1174 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1182 timeControl_2 = tc2 * 1000;
1192 timeControl = tc1 * 1000;
1195 timeIncrement = ti * 1000; /* convert to ms */
1196 movesPerSession = 0;
1199 movesPerSession = mps;
1207 if (appData.debugMode) {
1208 fprintf(debugFP, "%s\n", programVersion);
1211 set_cont_sequence(appData.wrapContSeq);
1212 if (appData.matchGames > 0) {
1213 appData.matchMode = TRUE;
1214 } else if (appData.matchMode) {
1215 appData.matchGames = 1;
1217 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1218 appData.matchGames = appData.sameColorGames;
1219 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1220 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1221 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1224 if (appData.noChessProgram || first.protocolVersion == 1) {
1227 /* kludge: allow timeout for initial "feature" commands */
1229 DisplayMessage("", _("Starting chess program"));
1230 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1235 CalculateIndex(int index, int gameNr)
1236 { // [HGM] autoinc: absolute way to determine load index from game number (taking auto-inc and rewind into account)
1238 if(index > 0) return index; // fixed nmber
1239 if(index == 0) return 1;
1240 res = (index == -1 ? gameNr : (gameNr-1)/2 + 1); // autoinc
1241 if(appData.rewindIndex > 0) res = (res-1) % appData.rewindIndex + 1; // rewind
1246 LoadGameOrPosition(int gameNr)
1247 { // [HGM] taken out of MatchEvent and NextMatchGame (to combine it)
1248 if (*appData.loadGameFile != NULLCHAR) {
1249 if (!LoadGameFromFile(appData.loadGameFile,
1250 CalculateIndex(appData.loadGameIndex, gameNr),
1251 appData.loadGameFile, FALSE)) {
1252 DisplayFatalError(_("Bad game file"), 0, 1);
1255 } else if (*appData.loadPositionFile != NULLCHAR) {
1256 if (!LoadPositionFromFile(appData.loadPositionFile,
1257 CalculateIndex(appData.loadPositionIndex, gameNr),
1258 appData.loadPositionFile)) {
1259 DisplayFatalError(_("Bad position file"), 0, 1);
1267 MatchEvent(int mode)
1268 { // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
1269 /* Set up machine vs. machine match */
1270 if (appData.noChessProgram) {
1271 DisplayFatalError(_("Can't have a match with no chess programs"),
1277 if(!LoadGameOrPositionFile(1)) return;
1278 first.matchWins = second.matchWins = 0; // [HGM] match: needed in later matches
\r
1283 InitBackEnd3 P((void))
1285 GameMode initialMode;
1289 InitChessProgram(&first, startedFromSetupPosition);
1291 if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
1292 free(programVersion);
1293 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1294 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1297 if (appData.icsActive) {
1299 /* [DM] Make a console window if needed [HGM] merged ifs */
1305 if (*appData.icsCommPort != NULLCHAR)
1306 len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1307 appData.icsCommPort);
1309 len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1310 appData.icsHost, appData.icsPort);
1312 if( (len > MSG_SIZ) && appData.debugMode )
1313 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1315 DisplayFatalError(buf, err, 1);
1320 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1322 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1323 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1324 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1325 } else if (appData.noChessProgram) {
1331 if (*appData.cmailGameName != NULLCHAR) {
1333 OpenLoopback(&cmailPR);
1335 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1339 DisplayMessage("", "");
1340 if (StrCaseCmp(appData.initialMode, "") == 0) {
1341 initialMode = BeginningOfGame;
1342 if(!appData.icsActive && appData.noChessProgram) { // [HGM] could be fall-back
1343 gameMode = MachinePlaysBlack; // "Machine Black" might have been implicitly highlighted
1344 ModeHighlight(); // make sure XBoard knows it is highlighted, so it will un-highlight it
1345 gameMode = BeginningOfGame; // in case BeginningOfGame now means "Edit Position"
1348 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1349 initialMode = TwoMachinesPlay;
1350 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1351 initialMode = AnalyzeFile;
1352 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1353 initialMode = AnalyzeMode;
1354 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1355 initialMode = MachinePlaysWhite;
1356 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1357 initialMode = MachinePlaysBlack;
1358 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1359 initialMode = EditGame;
1360 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1361 initialMode = EditPosition;
1362 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1363 initialMode = Training;
1365 len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1366 if( (len > MSG_SIZ) && appData.debugMode )
1367 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1369 DisplayFatalError(buf, 0, 2);
1373 if (appData.matchMode) {
1375 } else if (*appData.cmailGameName != NULLCHAR) {
1376 /* Set up cmail mode */
1377 ReloadCmailMsgEvent(TRUE);
1379 /* Set up other modes */
1380 if (initialMode == AnalyzeFile) {
1381 if (*appData.loadGameFile == NULLCHAR) {
1382 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1386 if (*appData.loadGameFile != NULLCHAR) {
1387 (void) LoadGameFromFile(appData.loadGameFile,
1388 appData.loadGameIndex,
1389 appData.loadGameFile, TRUE);
1390 } else if (*appData.loadPositionFile != NULLCHAR) {
1391 (void) LoadPositionFromFile(appData.loadPositionFile,
1392 appData.loadPositionIndex,
1393 appData.loadPositionFile);
1394 /* [HGM] try to make self-starting even after FEN load */
1395 /* to allow automatic setup of fairy variants with wtm */
1396 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1397 gameMode = BeginningOfGame;
1398 setboardSpoiledMachineBlack = 1;
1400 /* [HGM] loadPos: make that every new game uses the setup */
1401 /* from file as long as we do not switch variant */
1402 if(!blackPlaysFirst) {
1403 startedFromPositionFile = TRUE;
1404 CopyBoard(filePosition, boards[0]);
1407 if (initialMode == AnalyzeMode) {
1408 if (appData.noChessProgram) {
1409 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1412 if (appData.icsActive) {
1413 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1417 } else if (initialMode == AnalyzeFile) {
1418 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1419 ShowThinkingEvent();
1421 AnalysisPeriodicEvent(1);
1422 } else if (initialMode == MachinePlaysWhite) {
1423 if (appData.noChessProgram) {
1424 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1428 if (appData.icsActive) {
1429 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1433 MachineWhiteEvent();
1434 } else if (initialMode == MachinePlaysBlack) {
1435 if (appData.noChessProgram) {
1436 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1440 if (appData.icsActive) {
1441 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1445 MachineBlackEvent();
1446 } else if (initialMode == TwoMachinesPlay) {
1447 if (appData.noChessProgram) {
1448 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1452 if (appData.icsActive) {
1453 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1458 } else if (initialMode == EditGame) {
1460 } else if (initialMode == EditPosition) {
1461 EditPositionEvent();
1462 } else if (initialMode == Training) {
1463 if (*appData.loadGameFile == NULLCHAR) {
1464 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1473 * Establish will establish a contact to a remote host.port.
1474 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1475 * used to talk to the host.
1476 * Returns 0 if okay, error code if not.
1483 if (*appData.icsCommPort != NULLCHAR) {
1484 /* Talk to the host through a serial comm port */
1485 return OpenCommPort(appData.icsCommPort, &icsPR);
1487 } else if (*appData.gateway != NULLCHAR) {
1488 if (*appData.remoteShell == NULLCHAR) {
1489 /* Use the rcmd protocol to run telnet program on a gateway host */
1490 snprintf(buf, sizeof(buf), "%s %s %s",
1491 appData.telnetProgram, appData.icsHost, appData.icsPort);
1492 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1495 /* Use the rsh program to run telnet program on a gateway host */
1496 if (*appData.remoteUser == NULLCHAR) {
1497 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1498 appData.gateway, appData.telnetProgram,
1499 appData.icsHost, appData.icsPort);
1501 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1502 appData.remoteShell, appData.gateway,
1503 appData.remoteUser, appData.telnetProgram,
1504 appData.icsHost, appData.icsPort);
1506 return StartChildProcess(buf, "", &icsPR);
1509 } else if (appData.useTelnet) {
1510 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1513 /* TCP socket interface differs somewhat between
1514 Unix and NT; handle details in the front end.
1516 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1520 void EscapeExpand(char *p, char *q)
1521 { // [HGM] initstring: routine to shape up string arguments
1522 while(*p++ = *q++) if(p[-1] == '\\')
1524 case 'n': p[-1] = '\n'; break;
1525 case 'r': p[-1] = '\r'; break;
1526 case 't': p[-1] = '\t'; break;
1527 case '\\': p[-1] = '\\'; break;
1528 case 0: *p = 0; return;
1529 default: p[-1] = q[-1]; break;
1534 show_bytes(fp, buf, count)
1540 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1541 fprintf(fp, "\\%03o", *buf & 0xff);
1550 /* Returns an errno value */
1552 OutputMaybeTelnet(pr, message, count, outError)
1558 char buf[8192], *p, *q, *buflim;
1559 int left, newcount, outcount;
1561 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1562 *appData.gateway != NULLCHAR) {
1563 if (appData.debugMode) {
1564 fprintf(debugFP, ">ICS: ");
1565 show_bytes(debugFP, message, count);
1566 fprintf(debugFP, "\n");
1568 return OutputToProcess(pr, message, count, outError);
1571 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1578 if (appData.debugMode) {
1579 fprintf(debugFP, ">ICS: ");
1580 show_bytes(debugFP, buf, newcount);
1581 fprintf(debugFP, "\n");
1583 outcount = OutputToProcess(pr, buf, newcount, outError);
1584 if (outcount < newcount) return -1; /* to be sure */
1591 } else if (((unsigned char) *p) == TN_IAC) {
1592 *q++ = (char) TN_IAC;
1599 if (appData.debugMode) {
1600 fprintf(debugFP, ">ICS: ");
1601 show_bytes(debugFP, buf, newcount);
1602 fprintf(debugFP, "\n");
1604 outcount = OutputToProcess(pr, buf, newcount, outError);
1605 if (outcount < newcount) return -1; /* to be sure */
1610 read_from_player(isr, closure, message, count, error)
1617 int outError, outCount;
1618 static int gotEof = 0;
1620 /* Pass data read from player on to ICS */
1623 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1624 if (outCount < count) {
1625 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1627 } else if (count < 0) {
1628 RemoveInputSource(isr);
1629 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1630 } else if (gotEof++ > 0) {
1631 RemoveInputSource(isr);
1632 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1638 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1639 if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
1640 connectionAlive = FALSE; // only sticks if no response to 'date' command.
1641 SendToICS("date\n");
1642 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1645 /* added routine for printf style output to ics */
1646 void ics_printf(char *format, ...)
1648 char buffer[MSG_SIZ];
1651 va_start(args, format);
1652 vsnprintf(buffer, sizeof(buffer), format, args);
1653 buffer[sizeof(buffer)-1] = '\0';
1662 int count, outCount, outError;
1664 if (icsPR == NULL) return;
1667 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1668 if (outCount < count) {
1669 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1673 /* This is used for sending logon scripts to the ICS. Sending
1674 without a delay causes problems when using timestamp on ICC
1675 (at least on my machine). */
1677 SendToICSDelayed(s,msdelay)
1681 int count, outCount, outError;
1683 if (icsPR == NULL) return;
1686 if (appData.debugMode) {
1687 fprintf(debugFP, ">ICS: ");
1688 show_bytes(debugFP, s, count);
1689 fprintf(debugFP, "\n");
1691 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1693 if (outCount < count) {
1694 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1699 /* Remove all highlighting escape sequences in s
1700 Also deletes any suffix starting with '('
1703 StripHighlightAndTitle(s)
1706 static char retbuf[MSG_SIZ];
1709 while (*s != NULLCHAR) {
1710 while (*s == '\033') {
1711 while (*s != NULLCHAR && !isalpha(*s)) s++;
1712 if (*s != NULLCHAR) s++;
1714 while (*s != NULLCHAR && *s != '\033') {
1715 if (*s == '(' || *s == '[') {
1726 /* Remove all highlighting escape sequences in s */
1731 static char retbuf[MSG_SIZ];
1734 while (*s != NULLCHAR) {
1735 while (*s == '\033') {
1736 while (*s != NULLCHAR && !isalpha(*s)) s++;
1737 if (*s != NULLCHAR) s++;
1739 while (*s != NULLCHAR && *s != '\033') {
1747 char *variantNames[] = VARIANT_NAMES;
1752 return variantNames[v];
1756 /* Identify a variant from the strings the chess servers use or the
1757 PGN Variant tag names we use. */
1764 VariantClass v = VariantNormal;
1765 int i, found = FALSE;
1771 /* [HGM] skip over optional board-size prefixes */
1772 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
1773 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
1774 while( *e++ != '_');
1777 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
1781 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1782 if (StrCaseStr(e, variantNames[i])) {
1783 v = (VariantClass) i;
1790 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
1791 || StrCaseStr(e, "wild/fr")
1792 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
1793 v = VariantFischeRandom;
1794 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
1795 (i = 1, p = StrCaseStr(e, "w"))) {
1797 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
1804 case 0: /* FICS only, actually */
1806 /* Castling legal even if K starts on d-file */
1807 v = VariantWildCastle;
1812 /* Castling illegal even if K & R happen to start in
1813 normal positions. */
1814 v = VariantNoCastle;
1827 /* Castling legal iff K & R start in normal positions */
1833 /* Special wilds for position setup; unclear what to do here */
1834 v = VariantLoadable;
1837 /* Bizarre ICC game */
1838 v = VariantTwoKings;
1841 v = VariantKriegspiel;
1847 v = VariantFischeRandom;
1850 v = VariantCrazyhouse;
1853 v = VariantBughouse;
1859 /* Not quite the same as FICS suicide! */
1860 v = VariantGiveaway;
1866 v = VariantShatranj;
1869 /* Temporary names for future ICC types. The name *will* change in
1870 the next xboard/WinBoard release after ICC defines it. */
1908 v = VariantCapablanca;
1911 v = VariantKnightmate;
1917 v = VariantCylinder;
1923 v = VariantCapaRandom;
1926 v = VariantBerolina;
1938 /* Found "wild" or "w" in the string but no number;
1939 must assume it's normal chess. */
1943 len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
1944 if( (len > MSG_SIZ) && appData.debugMode )
1945 fprintf(debugFP, "StringToVariant: buffer truncated.\n");
1947 DisplayError(buf, 0);
1953 if (appData.debugMode) {
1954 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
1955 e, wnum, VariantName(v));
1960 static int leftover_start = 0, leftover_len = 0;
1961 char star_match[STAR_MATCH_N][MSG_SIZ];
1963 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
1964 advance *index beyond it, and set leftover_start to the new value of
1965 *index; else return FALSE. If pattern contains the character '*', it
1966 matches any sequence of characters not containing '\r', '\n', or the
1967 character following the '*' (if any), and the matched sequence(s) are
1968 copied into star_match.
1971 looking_at(buf, index, pattern)
1976 char *bufp = &buf[*index], *patternp = pattern;
1978 char *matchp = star_match[0];
1981 if (*patternp == NULLCHAR) {
1982 *index = leftover_start = bufp - buf;
1986 if (*bufp == NULLCHAR) return FALSE;
1987 if (*patternp == '*') {
1988 if (*bufp == *(patternp + 1)) {
1990 matchp = star_match[++star_count];
1994 } else if (*bufp == '\n' || *bufp == '\r') {
1996 if (*patternp == NULLCHAR)
2001 *matchp++ = *bufp++;
2005 if (*patternp != *bufp) return FALSE;
2012 SendToPlayer(data, length)
2016 int error, outCount;
2017 outCount = OutputToProcess(NoProc, data, length, &error);
2018 if (outCount < length) {
2019 DisplayFatalError(_("Error writing to display"), error, 1);
2024 PackHolding(packed, holding)
2036 switch (runlength) {
2047 sprintf(q, "%d", runlength);
2059 /* Telnet protocol requests from the front end */
2061 TelnetRequest(ddww, option)
2062 unsigned char ddww, option;
2064 unsigned char msg[3];
2065 int outCount, outError;
2067 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
2069 if (appData.debugMode) {
2070 char buf1[8], buf2[8], *ddwwStr, *optionStr;
2086 snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2095 snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2098 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2103 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2105 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2112 if (!appData.icsActive) return;
2113 TelnetRequest(TN_DO, TN_ECHO);
2119 if (!appData.icsActive) return;
2120 TelnetRequest(TN_DONT, TN_ECHO);
2124 CopyHoldings(Board board, char *holdings, ChessSquare lowestPiece)
2126 /* put the holdings sent to us by the server on the board holdings area */
2127 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2131 if(gameInfo.holdingsWidth < 2) return;
2132 if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2133 return; // prevent overwriting by pre-board holdings
2135 if( (int)lowestPiece >= BlackPawn ) {
2138 holdingsStartRow = BOARD_HEIGHT-1;
2141 holdingsColumn = BOARD_WIDTH-1;
2142 countsColumn = BOARD_WIDTH-2;
2143 holdingsStartRow = 0;
2147 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
2148 board[i][holdingsColumn] = EmptySquare;
2149 board[i][countsColumn] = (ChessSquare) 0;
2151 while( (p=*holdings++) != NULLCHAR ) {
2152 piece = CharToPiece( ToUpper(p) );
2153 if(piece == EmptySquare) continue;
2154 /*j = (int) piece - (int) WhitePawn;*/
2155 j = PieceToNumber(piece);
2156 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2157 if(j < 0) continue; /* should not happen */
2158 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2159 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2160 board[holdingsStartRow+j*direction][countsColumn]++;
2166 VariantSwitch(Board board, VariantClass newVariant)
2168 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2169 static Board oldBoard;
2171 startedFromPositionFile = FALSE;
2172 if(gameInfo.variant == newVariant) return;
2174 /* [HGM] This routine is called each time an assignment is made to
2175 * gameInfo.variant during a game, to make sure the board sizes
2176 * are set to match the new variant. If that means adding or deleting
2177 * holdings, we shift the playing board accordingly
2178 * This kludge is needed because in ICS observe mode, we get boards
2179 * of an ongoing game without knowing the variant, and learn about the
2180 * latter only later. This can be because of the move list we requested,
2181 * in which case the game history is refilled from the beginning anyway,
2182 * but also when receiving holdings of a crazyhouse game. In the latter
2183 * case we want to add those holdings to the already received position.
2187 if (appData.debugMode) {
2188 fprintf(debugFP, "Switch board from %s to %s\n",
2189 VariantName(gameInfo.variant), VariantName(newVariant));
2190 setbuf(debugFP, NULL);
2192 shuffleOpenings = 0; /* [HGM] shuffle */
2193 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2197 newWidth = 9; newHeight = 9;
2198 gameInfo.holdingsSize = 7;
2199 case VariantBughouse:
2200 case VariantCrazyhouse:
2201 newHoldingsWidth = 2; break;
2205 newHoldingsWidth = 2;
2206 gameInfo.holdingsSize = 8;
2209 case VariantCapablanca:
2210 case VariantCapaRandom:
2213 newHoldingsWidth = gameInfo.holdingsSize = 0;
2216 if(newWidth != gameInfo.boardWidth ||
2217 newHeight != gameInfo.boardHeight ||
2218 newHoldingsWidth != gameInfo.holdingsWidth ) {
2220 /* shift position to new playing area, if needed */
2221 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2222 for(i=0; i<BOARD_HEIGHT; i++)
2223 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2224 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2226 for(i=0; i<newHeight; i++) {
2227 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2228 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2230 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2231 for(i=0; i<BOARD_HEIGHT; i++)
2232 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2233 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2236 gameInfo.boardWidth = newWidth;
2237 gameInfo.boardHeight = newHeight;
2238 gameInfo.holdingsWidth = newHoldingsWidth;
2239 gameInfo.variant = newVariant;
2240 InitDrawingSizes(-2, 0);
2241 } else gameInfo.variant = newVariant;
2242 CopyBoard(oldBoard, board); // remember correctly formatted board
2243 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2244 DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2247 static int loggedOn = FALSE;
2249 /*-- Game start info cache: --*/
2251 char gs_kind[MSG_SIZ];
2252 static char player1Name[128] = "";
2253 static char player2Name[128] = "";
2254 static char cont_seq[] = "\n\\ ";
2255 static int player1Rating = -1;
2256 static int player2Rating = -1;
2257 /*----------------------------*/
2259 ColorClass curColor = ColorNormal;
2260 int suppressKibitz = 0;
2263 Boolean soughtPending = FALSE;
2264 Boolean seekGraphUp;
2265 #define MAX_SEEK_ADS 200
2267 char *seekAdList[MAX_SEEK_ADS];
2268 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2269 float tcList[MAX_SEEK_ADS];
2270 char colorList[MAX_SEEK_ADS];
2271 int nrOfSeekAds = 0;
2272 int minRating = 1010, maxRating = 2800;
2273 int hMargin = 10, vMargin = 20, h, w;
2274 extern int squareSize, lineGap;
2279 int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2280 xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2281 if(r < minRating+100 && r >=0 ) r = minRating+100;
2282 if(r > maxRating) r = maxRating;
2283 if(tc < 1.) tc = 1.;
2284 if(tc > 95.) tc = 95.;
2285 x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2286 y = ((double)r - minRating)/(maxRating - minRating)
2287 * (h-vMargin-squareSize/8-1) + vMargin;
2288 if(ratingList[i] < 0) y = vMargin + squareSize/4;
2289 if(strstr(seekAdList[i], " u ")) color = 1;
2290 if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2291 !strstr(seekAdList[i], "bullet") &&
2292 !strstr(seekAdList[i], "blitz") &&
2293 !strstr(seekAdList[i], "standard") ) color = 2;
2294 if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2295 DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2299 AddAd(char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
2301 char buf[MSG_SIZ], *ext = "";
2302 VariantClass v = StringToVariant(type);
2303 if(strstr(type, "wild")) {
2304 ext = type + 4; // append wild number
2305 if(v == VariantFischeRandom) type = "chess960"; else
2306 if(v == VariantLoadable) type = "setup"; else
2307 type = VariantName(v);
2309 snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2310 if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2311 if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2312 ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2313 sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2314 tcList[nrOfSeekAds] = base + (2./3.)*inc;
2315 seekNrList[nrOfSeekAds] = nr;
2316 zList[nrOfSeekAds] = 0;
2317 seekAdList[nrOfSeekAds++] = StrSave(buf);
2318 if(plot) PlotSeekAd(nrOfSeekAds-1);
2325 int x = xList[i], y = yList[i], d=squareSize/4, k;
2326 DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2327 if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2328 // now replot every dot that overlapped
2329 for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2330 int xx = xList[k], yy = yList[k];
2331 if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2332 DrawSeekDot(xx, yy, colorList[k]);
2337 RemoveSeekAd(int nr)
2340 for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2342 if(seekAdList[i]) free(seekAdList[i]);
2343 seekAdList[i] = seekAdList[--nrOfSeekAds];
2344 seekNrList[i] = seekNrList[nrOfSeekAds];
2345 ratingList[i] = ratingList[nrOfSeekAds];
2346 colorList[i] = colorList[nrOfSeekAds];
2347 tcList[i] = tcList[nrOfSeekAds];
2348 xList[i] = xList[nrOfSeekAds];
2349 yList[i] = yList[nrOfSeekAds];
2350 zList[i] = zList[nrOfSeekAds];
2351 seekAdList[nrOfSeekAds] = NULL;
2357 MatchSoughtLine(char *line)
2359 char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2360 int nr, base, inc, u=0; char dummy;
2362 if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2363 sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2365 (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2366 sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
2367 // match: compact and save the line
2368 AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2378 if(!seekGraphUp) return FALSE;
2379 h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap;
2380 w = BOARD_WIDTH * (squareSize + lineGap) + lineGap;
2382 DrawSeekBackground(0, 0, w, h);
2383 DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2384 DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2385 for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2386 int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2388 DrawSeekAxis(hMargin+5*(i%500==0), yy, hMargin-5, yy); // rating ticks
2391 snprintf(buf, MSG_SIZ, "%d", i);
2392 DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2395 DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2396 for(i=1; i<100; i+=(i<10?1:5)) {
2397 int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2398 DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2399 if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2401 snprintf(buf, MSG_SIZ, "%d", i);
2402 DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2405 for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2409 int SeekGraphClick(ClickType click, int x, int y, int moving)
2411 static int lastDown = 0, displayed = 0, lastSecond;
2412 if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2413 if(click == Release || moving) return FALSE;
2415 soughtPending = TRUE;
2416 SendToICS(ics_prefix);
2417 SendToICS("sought\n"); // should this be "sought all"?
2418 } else { // issue challenge based on clicked ad
2419 int dist = 10000; int i, closest = 0, second = 0;
2420 for(i=0; i<nrOfSeekAds; i++) {
2421 int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
2422 if(d < dist) { dist = d; closest = i; }
2423 second += (d - zList[i] < 120); // count in-range ads
2424 if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2428 second = (second > 1);
2429 if(displayed != closest || second != lastSecond) {
2430 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2431 lastSecond = second; displayed = closest;
2433 if(click == Press) {
2434 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2437 } // on press 'hit', only show info
2438 if(moving == 2) return TRUE; // ignore right up-clicks on dot
2439 snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2440 SendToICS(ics_prefix);
2442 return TRUE; // let incoming board of started game pop down the graph
2443 } else if(click == Release) { // release 'miss' is ignored
2444 zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2445 if(moving == 2) { // right up-click
2446 nrOfSeekAds = 0; // refresh graph
2447 soughtPending = TRUE;
2448 SendToICS(ics_prefix);
2449 SendToICS("sought\n"); // should this be "sought all"?
2452 } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2453 // press miss or release hit 'pop down' seek graph
2454 seekGraphUp = FALSE;
2455 DrawPosition(TRUE, NULL);
2461 read_from_ics(isr, closure, data, count, error)
2468 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2469 #define STARTED_NONE 0
2470 #define STARTED_MOVES 1
2471 #define STARTED_BOARD 2
2472 #define STARTED_OBSERVE 3
2473 #define STARTED_HOLDINGS 4
2474 #define STARTED_CHATTER 5
2475 #define STARTED_COMMENT 6
2476 #define STARTED_MOVES_NOHIDE 7
2478 static int started = STARTED_NONE;
2479 static char parse[20000];
2480 static int parse_pos = 0;
2481 static char buf[BUF_SIZE + 1];
2482 static int firstTime = TRUE, intfSet = FALSE;
2483 static ColorClass prevColor = ColorNormal;
2484 static int savingComment = FALSE;
2485 static int cmatch = 0; // continuation sequence match
2492 int backup; /* [DM] For zippy color lines */
2494 char talker[MSG_SIZ]; // [HGM] chat
2497 connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2499 if (appData.debugMode) {
2501 fprintf(debugFP, "<ICS: ");
2502 show_bytes(debugFP, data, count);
2503 fprintf(debugFP, "\n");
2507 if (appData.debugMode) { int f = forwardMostMove;
2508 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2509 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2510 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2513 /* If last read ended with a partial line that we couldn't parse,
2514 prepend it to the new read and try again. */
2515 if (leftover_len > 0) {
2516 for (i=0; i<leftover_len; i++)
2517 buf[i] = buf[leftover_start + i];
2520 /* copy new characters into the buffer */
2521 bp = buf + leftover_len;
2522 buf_len=leftover_len;
2523 for (i=0; i<count; i++)
2526 if (data[i] == '\r')
2529 // join lines split by ICS?
2530 if (!appData.noJoin)
2533 Joining just consists of finding matches against the
2534 continuation sequence, and discarding that sequence
2535 if found instead of copying it. So, until a match
2536 fails, there's nothing to do since it might be the
2537 complete sequence, and thus, something we don't want
2540 if (data[i] == cont_seq[cmatch])
2543 if (cmatch == strlen(cont_seq))
2545 cmatch = 0; // complete match. just reset the counter
2548 it's possible for the ICS to not include the space
2549 at the end of the last word, making our [correct]
2550 join operation fuse two separate words. the server
2551 does this when the space occurs at the width setting.
2553 if (!buf_len || buf[buf_len-1] != ' ')
2564 match failed, so we have to copy what matched before
2565 falling through and copying this character. In reality,
2566 this will only ever be just the newline character, but
2567 it doesn't hurt to be precise.
2569 strncpy(bp, cont_seq, cmatch);
2581 buf[buf_len] = NULLCHAR;
2582 // next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2587 while (i < buf_len) {
2588 /* Deal with part of the TELNET option negotiation
2589 protocol. We refuse to do anything beyond the
2590 defaults, except that we allow the WILL ECHO option,
2591 which ICS uses to turn off password echoing when we are
2592 directly connected to it. We reject this option
2593 if localLineEditing mode is on (always on in xboard)
2594 and we are talking to port 23, which might be a real
2595 telnet server that will try to keep WILL ECHO on permanently.
2597 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2598 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2599 unsigned char option;
2601 switch ((unsigned char) buf[++i]) {
2603 if (appData.debugMode)
2604 fprintf(debugFP, "\n<WILL ");
2605 switch (option = (unsigned char) buf[++i]) {
2607 if (appData.debugMode)
2608 fprintf(debugFP, "ECHO ");
2609 /* Reply only if this is a change, according
2610 to the protocol rules. */
2611 if (remoteEchoOption) break;
2612 if (appData.localLineEditing &&
2613 atoi(appData.icsPort) == TN_PORT) {
2614 TelnetRequest(TN_DONT, TN_ECHO);
2617 TelnetRequest(TN_DO, TN_ECHO);
2618 remoteEchoOption = TRUE;
2622 if (appData.debugMode)
2623 fprintf(debugFP, "%d ", option);
2624 /* Whatever this is, we don't want it. */
2625 TelnetRequest(TN_DONT, option);
2630 if (appData.debugMode)
2631 fprintf(debugFP, "\n<WONT ");
2632 switch (option = (unsigned char) buf[++i]) {
2634 if (appData.debugMode)
2635 fprintf(debugFP, "ECHO ");
2636 /* Reply only if this is a change, according
2637 to the protocol rules. */
2638 if (!remoteEchoOption) break;
2640 TelnetRequest(TN_DONT, TN_ECHO);
2641 remoteEchoOption = FALSE;
2644 if (appData.debugMode)
2645 fprintf(debugFP, "%d ", (unsigned char) option);
2646 /* Whatever this is, it must already be turned
2647 off, because we never agree to turn on
2648 anything non-default, so according to the
2649 protocol rules, we don't reply. */
2654 if (appData.debugMode)
2655 fprintf(debugFP, "\n<DO ");
2656 switch (option = (unsigned char) buf[++i]) {
2658 /* Whatever this is, we refuse to do it. */
2659 if (appData.debugMode)
2660 fprintf(debugFP, "%d ", option);
2661 TelnetRequest(TN_WONT, option);
2666 if (appData.debugMode)
2667 fprintf(debugFP, "\n<DONT ");
2668 switch (option = (unsigned char) buf[++i]) {
2670 if (appData.debugMode)
2671 fprintf(debugFP, "%d ", option);
2672 /* Whatever this is, we are already not doing
2673 it, because we never agree to do anything
2674 non-default, so according to the protocol
2675 rules, we don't reply. */
2680 if (appData.debugMode)
2681 fprintf(debugFP, "\n<IAC ");
2682 /* Doubled IAC; pass it through */
2686 if (appData.debugMode)
2687 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2688 /* Drop all other telnet commands on the floor */
2691 if (oldi > next_out)
2692 SendToPlayer(&buf[next_out], oldi - next_out);
2698 /* OK, this at least will *usually* work */
2699 if (!loggedOn && looking_at(buf, &i, "ics%")) {
2703 if (loggedOn && !intfSet) {
2704 if (ics_type == ICS_ICC) {
2705 snprintf(str, MSG_SIZ,
2706 "/set-quietly interface %s\n/set-quietly style 12\n",
2708 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2709 strcat(str, "/set-2 51 1\n/set seek 1\n");
2710 } else if (ics_type == ICS_CHESSNET) {
2711 snprintf(str, MSG_SIZ, "/style 12\n");
2713 safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
2714 strcat(str, programVersion);
2715 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2716 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2717 strcat(str, "$iset seekremove 1\n$set seek 1\n");
2719 strcat(str, "$iset nohighlight 1\n");
2721 strcat(str, "$iset lock 1\n$style 12\n");
2724 NotifyFrontendLogin();
2728 if (started == STARTED_COMMENT) {
2729 /* Accumulate characters in comment */
2730 parse[parse_pos++] = buf[i];
2731 if (buf[i] == '\n') {
2732 parse[parse_pos] = NULLCHAR;
2733 if(chattingPartner>=0) {
2735 snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
2736 OutputChatMessage(chattingPartner, mess);
2737 chattingPartner = -1;
2738 next_out = i+1; // [HGM] suppress printing in ICS window
2740 if(!suppressKibitz) // [HGM] kibitz
2741 AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
2742 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2743 int nrDigit = 0, nrAlph = 0, j;
2744 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2745 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2746 parse[parse_pos] = NULLCHAR;
2747 // try to be smart: if it does not look like search info, it should go to
2748 // ICS interaction window after all, not to engine-output window.
2749 for(j=0; j<parse_pos; j++) { // count letters and digits
2750 nrDigit += (parse[j] >= '0' && parse[j] <= '9');
2751 nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
2752 nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
2754 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
2755 int depth=0; float score;
2756 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
2757 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
2758 pvInfoList[forwardMostMove-1].depth = depth;
2759 pvInfoList[forwardMostMove-1].score = 100*score;
2761 OutputKibitz(suppressKibitz, parse);
2764 snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
2765 SendToPlayer(tmp, strlen(tmp));
2767 next_out = i+1; // [HGM] suppress printing in ICS window
2769 started = STARTED_NONE;
2771 /* Don't match patterns against characters in comment */
2776 if (started == STARTED_CHATTER) {
2777 if (buf[i] != '\n') {
2778 /* Don't match patterns against characters in chatter */
2782 started = STARTED_NONE;
2783 if(suppressKibitz) next_out = i+1;
2786 /* Kludge to deal with rcmd protocol */
2787 if (firstTime && looking_at(buf, &i, "\001*")) {
2788 DisplayFatalError(&buf[1], 0, 1);
2794 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
2797 if (appData.debugMode)
2798 fprintf(debugFP, "ics_type %d\n", ics_type);
2801 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
2802 ics_type = ICS_FICS;
2804 if (appData.debugMode)
2805 fprintf(debugFP, "ics_type %d\n", ics_type);
2808 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
2809 ics_type = ICS_CHESSNET;
2811 if (appData.debugMode)
2812 fprintf(debugFP, "ics_type %d\n", ics_type);
2817 (looking_at(buf, &i, "\"*\" is *a registered name") ||
2818 looking_at(buf, &i, "Logging you in as \"*\"") ||
2819 looking_at(buf, &i, "will be \"*\""))) {
2820 safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
2824 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
2826 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
2827 DisplayIcsInteractionTitle(buf);
2828 have_set_title = TRUE;
2831 /* skip finger notes */
2832 if (started == STARTED_NONE &&
2833 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
2834 (buf[i] == '1' && buf[i+1] == '0')) &&
2835 buf[i+2] == ':' && buf[i+3] == ' ') {
2836 started = STARTED_CHATTER;
2842 // [HGM] seekgraph: recognize sought lines and end-of-sought message
2843 if(appData.seekGraph) {
2844 if(soughtPending && MatchSoughtLine(buf+i)) {
2845 i = strstr(buf+i, "rated") - buf;
2846 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2847 next_out = leftover_start = i;
2848 started = STARTED_CHATTER;
2849 suppressKibitz = TRUE;
2852 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
2853 && looking_at(buf, &i, "* ads displayed")) {
2854 soughtPending = FALSE;
2859 if(appData.autoRefresh) {
2860 if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
2861 int s = (ics_type == ICS_ICC); // ICC format differs
2863 AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
2864 star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
2865 looking_at(buf, &i, "*% "); // eat prompt
2866 if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
2867 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2868 next_out = i; // suppress
2871 if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
2872 char *p = star_match[0];
2874 if(seekGraphUp) RemoveSeekAd(atoi(p));
2875 while(*p && *p++ != ' '); // next
2877 looking_at(buf, &i, "*% "); // eat prompt
2878 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2885 /* skip formula vars */
2886 if (started == STARTED_NONE &&
2887 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
2888 started = STARTED_CHATTER;
2893 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
2894 if (appData.autoKibitz && started == STARTED_NONE &&
2895 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
2896 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
2897 if((looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
2898 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
2899 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
2900 suppressKibitz = TRUE;
2901 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2903 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
2904 && (gameMode == IcsPlayingWhite)) ||
2905 (StrStr(star_match[0], gameInfo.black) == star_match[0]
2906 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
2907 started = STARTED_CHATTER; // own kibitz we simply discard
2909 started = STARTED_COMMENT; // make sure it will be collected in parse[]
2910 parse_pos = 0; parse[0] = NULLCHAR;
2911 savingComment = TRUE;
2912 suppressKibitz = gameMode != IcsObserving ? 2 :
2913 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
2917 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
2918 looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
2919 && atoi(star_match[0])) {
2920 // suppress the acknowledgements of our own autoKibitz
2922 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2923 if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
2924 SendToPlayer(star_match[0], strlen(star_match[0]));
2925 if(looking_at(buf, &i, "*% ")) // eat prompt
2926 suppressKibitz = FALSE;
2930 } // [HGM] kibitz: end of patch
2932 // [HGM] chat: intercept tells by users for which we have an open chat window
2934 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
2935 looking_at(buf, &i, "* whispers:") ||
2936 looking_at(buf, &i, "* kibitzes:") ||
2937 looking_at(buf, &i, "* shouts:") ||
2938 looking_at(buf, &i, "* c-shouts:") ||
2939 looking_at(buf, &i, "--> * ") ||
2940 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
2941 looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
2942 looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
2943 looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
2945 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
2946 chattingPartner = -1;
2948 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
2949 for(p=0; p<MAX_CHAT; p++) {
2950 if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
2951 talker[0] = '['; strcat(talker, "] ");
2952 Colorize(channel == 1 ? ColorChannel1 : ColorChannel, FALSE);
2953 chattingPartner = p; break;
2956 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
2957 for(p=0; p<MAX_CHAT; p++) {
2958 if(!strcmp("kibitzes", chatPartner[p])) {
2959 talker[0] = '['; strcat(talker, "] ");
2960 chattingPartner = p; break;
2963 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
2964 for(p=0; p<MAX_CHAT; p++) {
2965 if(!strcmp("whispers", chatPartner[p])) {
2966 talker[0] = '['; strcat(talker, "] ");
2967 chattingPartner = p; break;
2970 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
2971 if(buf[i-8] == '-' && buf[i-3] == 't')
2972 for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
2973 if(!strcmp("c-shouts", chatPartner[p])) {
2974 talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
2975 chattingPartner = p; break;
2978 if(chattingPartner < 0)
2979 for(p=0; p<MAX_CHAT; p++) {
2980 if(!strcmp("shouts", chatPartner[p])) {
2981 if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
2982 else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
2983 else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
2984 chattingPartner = p; break;
2988 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
2989 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
2990 talker[0] = 0; Colorize(ColorTell, FALSE);
2991 chattingPartner = p; break;
2993 if(chattingPartner<0) i = oldi; else {
2994 Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
2995 if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
2996 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2997 started = STARTED_COMMENT;
2998 parse_pos = 0; parse[0] = NULLCHAR;
2999 savingComment = 3 + chattingPartner; // counts as TRUE
3000 suppressKibitz = TRUE;
3003 } // [HGM] chat: end of patch
3006 if (appData.zippyTalk || appData.zippyPlay) {
3007 /* [DM] Backup address for color zippy lines */
3009 if (loggedOn == TRUE)
3010 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
3011 (appData.zippyPlay && ZippyMatch(buf, &backup)));
3013 } // [DM] 'else { ' deleted
3015 /* Regular tells and says */
3016 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
3017 looking_at(buf, &i, "* (your partner) tells you: ") ||
3018 looking_at(buf, &i, "* says: ") ||
3019 /* Don't color "message" or "messages" output */
3020 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
3021 looking_at(buf, &i, "*. * at *:*: ") ||
3022 looking_at(buf, &i, "--* (*:*): ") ||
3023 /* Message notifications (same color as tells) */
3024 looking_at(buf, &i, "* has left a message ") ||
3025 looking_at(buf, &i, "* just sent you a message:\n") ||
3026 /* Whispers and kibitzes */
3027 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
3028 looking_at(buf, &i, "* kibitzes: ") ||
3030 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
3032 if (tkind == 1 && strchr(star_match[0], ':')) {
3033 /* Avoid "tells you:" spoofs in channels */
3036 if (star_match[0][0] == NULLCHAR ||
3037 strchr(star_match[0], ' ') ||
3038 (tkind == 3 && strchr(star_match[1], ' '))) {
3039 /* Reject bogus matches */
3042 if (appData.colorize) {
3043 if (oldi > next_out) {
3044 SendToPlayer(&buf[next_out], oldi - next_out);
3049 Colorize(ColorTell, FALSE);
3050 curColor = ColorTell;
3053 Colorize(ColorKibitz, FALSE);
3054 curColor = ColorKibitz;
3057 p = strrchr(star_match[1], '(');
3064 Colorize(ColorChannel1, FALSE);
3065 curColor = ColorChannel1;
3067 Colorize(ColorChannel, FALSE);
3068 curColor = ColorChannel;
3072 curColor = ColorNormal;
3076 if (started == STARTED_NONE && appData.autoComment &&
3077 (gameMode == IcsObserving ||
3078 gameMode == IcsPlayingWhite ||
3079 gameMode == IcsPlayingBlack)) {
3080 parse_pos = i - oldi;
3081 memcpy(parse, &buf[oldi], parse_pos);
3082 parse[parse_pos] = NULLCHAR;
3083 started = STARTED_COMMENT;
3084 savingComment = TRUE;
3086 started = STARTED_CHATTER;
3087 savingComment = FALSE;
3094 if (looking_at(buf, &i, "* s-shouts: ") ||
3095 looking_at(buf, &i, "* c-shouts: ")) {
3096 if (appData.colorize) {
3097 if (oldi > next_out) {
3098 SendToPlayer(&buf[next_out], oldi - next_out);
3101 Colorize(ColorSShout, FALSE);
3102 curColor = ColorSShout;
3105 started = STARTED_CHATTER;
3109 if (looking_at(buf, &i, "--->")) {
3114 if (looking_at(buf, &i, "* shouts: ") ||
3115 looking_at(buf, &i, "--> ")) {
3116 if (appData.colorize) {
3117 if (oldi > next_out) {
3118 SendToPlayer(&buf[next_out], oldi - next_out);
3121 Colorize(ColorShout, FALSE);
3122 curColor = ColorShout;
3125 started = STARTED_CHATTER;
3129 if (looking_at( buf, &i, "Challenge:")) {
3130 if (appData.colorize) {
3131 if (oldi > next_out) {
3132 SendToPlayer(&buf[next_out], oldi - next_out);
3135 Colorize(ColorChallenge, FALSE);
3136 curColor = ColorChallenge;
3142 if (looking_at(buf, &i, "* offers you") ||
3143 looking_at(buf, &i, "* offers to be") ||
3144 looking_at(buf, &i, "* would like to") ||
3145 looking_at(buf, &i, "* requests to") ||
3146 looking_at(buf, &i, "Your opponent offers") ||
3147 looking_at(buf, &i, "Your opponent requests")) {
3149 if (appData.colorize) {
3150 if (oldi > next_out) {
3151 SendToPlayer(&buf[next_out], oldi - next_out);
3154 Colorize(ColorRequest, FALSE);
3155 curColor = ColorRequest;
3160 if (looking_at(buf, &i, "* (*) seeking")) {
3161 if (appData.colorize) {
3162 if (oldi > next_out) {
3163 SendToPlayer(&buf[next_out], oldi - next_out);
3166 Colorize(ColorSeek, FALSE);
3167 curColor = ColorSeek;
3172 if(i < backup) { i = backup; continue; } // [HGM] for if ZippyControl matches, but the colorie code doesn't
3174 if (looking_at(buf, &i, "\\ ")) {
3175 if (prevColor != ColorNormal) {
3176 if (oldi > next_out) {
3177 SendToPlayer(&buf[next_out], oldi - next_out);
3180 Colorize(prevColor, TRUE);
3181 curColor = prevColor;
3183 if (savingComment) {
3184 parse_pos = i - oldi;
3185 memcpy(parse, &buf[oldi], parse_pos);
3186 parse[parse_pos] = NULLCHAR;
3187 started = STARTED_COMMENT;
3188 if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3189 chattingPartner = savingComment - 3; // kludge to remember the box
3191 started = STARTED_CHATTER;
3196 if (looking_at(buf, &i, "Black Strength :") ||
3197 looking_at(buf, &i, "<<< style 10 board >>>") ||
3198 looking_at(buf, &i, "<10>") ||
3199 looking_at(buf, &i, "#@#")) {
3200 /* Wrong board style */
3202 SendToICS(ics_prefix);
3203 SendToICS("set style 12\n");
3204 SendToICS(ics_prefix);
3205 SendToICS("refresh\n");
3209 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
3211 have_sent_ICS_logon = 1;
3215 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3216 (looking_at(buf, &i, "\n<12> ") ||
3217 looking_at(buf, &i, "<12> "))) {
3219 if (oldi > next_out) {
3220 SendToPlayer(&buf[next_out], oldi - next_out);
3223 started = STARTED_BOARD;
3228 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3229 looking_at(buf, &i, "<b1> ")) {
3230 if (oldi > next_out) {
3231 SendToPlayer(&buf[next_out], oldi - next_out);
3234 started = STARTED_HOLDINGS;
3239 if (looking_at(buf, &i, "* *vs. * *--- *")) {
3241 /* Header for a move list -- first line */
3243 switch (ics_getting_history) {
3247 case BeginningOfGame:
3248 /* User typed "moves" or "oldmoves" while we
3249 were idle. Pretend we asked for these
3250 moves and soak them up so user can step
3251 through them and/or save them.
3254 gameMode = IcsObserving;
3257 ics_getting_history = H_GOT_UNREQ_HEADER;
3259 case EditGame: /*?*/
3260 case EditPosition: /*?*/
3261 /* Should above feature work in these modes too? */
3262 /* For now it doesn't */
3263 ics_getting_history = H_GOT_UNWANTED_HEADER;
3266 ics_getting_history = H_GOT_UNWANTED_HEADER;
3271 /* Is this the right one? */
3272 if (gameInfo.white && gameInfo.black &&
3273 strcmp(gameInfo.white, star_match[0]) == 0 &&
3274 strcmp(gameInfo.black, star_match[2]) == 0) {
3276 ics_getting_history = H_GOT_REQ_HEADER;
3279 case H_GOT_REQ_HEADER:
3280 case H_GOT_UNREQ_HEADER:
3281 case H_GOT_UNWANTED_HEADER:
3282 case H_GETTING_MOVES:
3283 /* Should not happen */
3284 DisplayError(_("Error gathering move list: two headers"), 0);
3285 ics_getting_history = H_FALSE;
3289 /* Save player ratings into gameInfo if needed */
3290 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3291 ics_getting_history == H_GOT_UNREQ_HEADER) &&
3292 (gameInfo.whiteRating == -1 ||
3293 gameInfo.blackRating == -1)) {
3295 gameInfo.whiteRating = string_to_rating(star_match[1]);
3296 gameInfo.blackRating = string_to_rating(star_match[3]);
3297 if (appData.debugMode)
3298 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
3299 gameInfo.whiteRating, gameInfo.blackRating);
3304 if (looking_at(buf, &i,
3305 "* * match, initial time: * minute*, increment: * second")) {
3306 /* Header for a move list -- second line */
3307 /* Initial board will follow if this is a wild game */
3308 if (gameInfo.event != NULL) free(gameInfo.event);
3309 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3310 gameInfo.event = StrSave(str);
3311 /* [HGM] we switched variant. Translate boards if needed. */
3312 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3316 if (looking_at(buf, &i, "Move ")) {
3317 /* Beginning of a move list */
3318 switch (ics_getting_history) {
3320 /* Normally should not happen */
3321 /* Maybe user hit reset while we were parsing */
3324 /* Happens if we are ignoring a move list that is not
3325 * the one we just requested. Common if the user
3326 * tries to observe two games without turning off
3329 case H_GETTING_MOVES:
3330 /* Should not happen */
3331 DisplayError(_("Error gathering move list: nested"), 0);
3332 ics_getting_history = H_FALSE;
3334 case H_GOT_REQ_HEADER:
3335 ics_getting_history = H_GETTING_MOVES;
3336 started = STARTED_MOVES;
3338 if (oldi > next_out) {
3339 SendToPlayer(&buf[next_out], oldi - next_out);
3342 case H_GOT_UNREQ_HEADER:
3343 ics_getting_history = H_GETTING_MOVES;
3344 started = STARTED_MOVES_NOHIDE;
3347 case H_GOT_UNWANTED_HEADER:
3348 ics_getting_history = H_FALSE;
3354 if (looking_at(buf, &i, "% ") ||
3355 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3356 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3357 if(ics_type == ICS_ICC && soughtPending) { // [HGM] seekgraph: on ICC sought-list has no termination line
3358 soughtPending = FALSE;
3362 if(suppressKibitz) next_out = i;
3363 savingComment = FALSE;
3367 case STARTED_MOVES_NOHIDE:
3368 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3369 parse[parse_pos + i - oldi] = NULLCHAR;
3370 ParseGameHistory(parse);
3372 if (appData.zippyPlay && first.initDone) {
3373 FeedMovesToProgram(&first, forwardMostMove);
3374 if (gameMode == IcsPlayingWhite) {
3375 if (WhiteOnMove(forwardMostMove)) {
3376 if (first.sendTime) {
3377 if (first.useColors) {
3378 SendToProgram("black\n", &first);
3380 SendTimeRemaining(&first, TRUE);
3382 if (first.useColors) {
3383 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3385 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3386 first.maybeThinking = TRUE;
3388 if (first.usePlayother) {
3389 if (first.sendTime) {
3390 SendTimeRemaining(&first, TRUE);
3392 SendToProgram("playother\n", &first);
3398 } else if (gameMode == IcsPlayingBlack) {
3399 if (!WhiteOnMove(forwardMostMove)) {
3400 if (first.sendTime) {
3401 if (first.useColors) {
3402 SendToProgram("white\n", &first);
3404 SendTimeRemaining(&first, FALSE);
3406 if (first.useColors) {
3407 SendToProgram("black\n", &first);
3409 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3410 first.maybeThinking = TRUE;
3412 if (first.usePlayother) {
3413 if (first.sendTime) {
3414 SendTimeRemaining(&first, FALSE);
3416 SendToProgram("playother\n", &first);
3425 if (gameMode == IcsObserving && ics_gamenum == -1) {
3426 /* Moves came from oldmoves or moves command
3427 while we weren't doing anything else.
3429 currentMove = forwardMostMove;
3430 ClearHighlights();/*!!could figure this out*/
3431 flipView = appData.flipView;
3432 DrawPosition(TRUE, boards[currentMove]);
3433 DisplayBothClocks();
3434 snprintf(str, MSG_SIZ, "%s vs. %s",
3435 gameInfo.white, gameInfo.black);
3439 /* Moves were history of an active game */
3440 if (gameInfo.resultDetails != NULL) {
3441 free(gameInfo.resultDetails);
3442 gameInfo.resultDetails = NULL;
3445 HistorySet(parseList, backwardMostMove,
3446 forwardMostMove, currentMove-1);
3447 DisplayMove(currentMove - 1);
3448 if (started == STARTED_MOVES) next_out = i;
3449 started = STARTED_NONE;
3450 ics_getting_history = H_FALSE;
3453 case STARTED_OBSERVE:
3454 started = STARTED_NONE;
3455 SendToICS(ics_prefix);
3456 SendToICS("refresh\n");
3462 if(bookHit) { // [HGM] book: simulate book reply
3463 static char bookMove[MSG_SIZ]; // a bit generous?
3465 programStats.nodes = programStats.depth = programStats.time =
3466 programStats.score = programStats.got_only_move = 0;
3467 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3469 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3470 strcat(bookMove, bookHit);
3471 HandleMachineMove(bookMove, &first);
3476 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3477 started == STARTED_HOLDINGS ||
3478 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3479 /* Accumulate characters in move list or board */
3480 parse[parse_pos++] = buf[i];
3483 /* Start of game messages. Mostly we detect start of game
3484 when the first board image arrives. On some versions
3485 of the ICS, though, we need to do a "refresh" after starting
3486 to observe in order to get the current board right away. */
3487 if (looking_at(buf, &i, "Adding game * to observation list")) {
3488 started = STARTED_OBSERVE;
3492 /* Handle auto-observe */
3493 if (appData.autoObserve &&
3494 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3495 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3497 /* Choose the player that was highlighted, if any. */
3498 if (star_match[0][0] == '\033' ||
3499 star_match[1][0] != '\033') {
3500 player = star_match[0];
3502 player = star_match[2];
3504 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3505 ics_prefix, StripHighlightAndTitle(player));
3508 /* Save ratings from notify string */
3509 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3510 player1Rating = string_to_rating(star_match[1]);
3511 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3512 player2Rating = string_to_rating(star_match[3]);
3514 if (appData.debugMode)
3516 "Ratings from 'Game notification:' %s %d, %s %d\n",
3517 player1Name, player1Rating,
3518 player2Name, player2Rating);
3523 /* Deal with automatic examine mode after a game,
3524 and with IcsObserving -> IcsExamining transition */
3525 if (looking_at(buf, &i, "Entering examine mode for game *") ||
3526 looking_at(buf, &i, "has made you an examiner of game *")) {
3528 int gamenum = atoi(star_match[0]);
3529 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3530 gamenum == ics_gamenum) {
3531 /* We were already playing or observing this game;
3532 no need to refetch history */
3533 gameMode = IcsExamining;
3535 pauseExamForwardMostMove = forwardMostMove;
3536 } else if (currentMove < forwardMostMove) {
3537 ForwardInner(forwardMostMove);
3540 /* I don't think this case really can happen */
3541 SendToICS(ics_prefix);
3542 SendToICS("refresh\n");
3547 /* Error messages */
3548 // if (ics_user_moved) {
3549 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3550 if (looking_at(buf, &i, "Illegal move") ||
3551 looking_at(buf, &i, "Not a legal move") ||
3552 looking_at(buf, &i, "Your king is in check") ||
3553 looking_at(buf, &i, "It isn't your turn") ||
3554 looking_at(buf, &i, "It is not your move")) {
3556 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3557 currentMove = forwardMostMove-1;
3558 DisplayMove(currentMove - 1); /* before DMError */
3559 DrawPosition(FALSE, boards[currentMove]);
3560 SwitchClocks(forwardMostMove-1); // [HGM] race
3561 DisplayBothClocks();
3563 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3569 if (looking_at(buf, &i, "still have time") ||
3570 looking_at(buf, &i, "not out of time") ||
3571 looking_at(buf, &i, "either player is out of time") ||
3572 looking_at(buf, &i, "has timeseal; checking")) {
3573 /* We must have called his flag a little too soon */
3574 whiteFlag = blackFlag = FALSE;
3578 if (looking_at(buf, &i, "added * seconds to") ||
3579 looking_at(buf, &i, "seconds were added to")) {
3580 /* Update the clocks */
3581 SendToICS(ics_prefix);
3582 SendToICS("refresh\n");
3586 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3587 ics_clock_paused = TRUE;
3592 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3593 ics_clock_paused = FALSE;
3598 /* Grab player ratings from the Creating: message.
3599 Note we have to check for the special case when
3600 the ICS inserts things like [white] or [black]. */
3601 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3602 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3604 0 player 1 name (not necessarily white)
3606 2 empty, white, or black (IGNORED)
3607 3 player 2 name (not necessarily black)
3610 The names/ratings are sorted out when the game
3611 actually starts (below).
3613 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
3614 player1Rating = string_to_rating(star_match[1]);
3615 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
3616 player2Rating = string_to_rating(star_match[4]);
3618 if (appData.debugMode)
3620 "Ratings from 'Creating:' %s %d, %s %d\n",
3621 player1Name, player1Rating,
3622 player2Name, player2Rating);
3627 /* Improved generic start/end-of-game messages */
3628 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3629 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3630 /* If tkind == 0: */
3631 /* star_match[0] is the game number */
3632 /* [1] is the white player's name */
3633 /* [2] is the black player's name */
3634 /* For end-of-game: */
3635 /* [3] is the reason for the game end */
3636 /* [4] is a PGN end game-token, preceded by " " */
3637 /* For start-of-game: */
3638 /* [3] begins with "Creating" or "Continuing" */
3639 /* [4] is " *" or empty (don't care). */
3640 int gamenum = atoi(star_match[0]);
3641 char *whitename, *blackname, *why, *endtoken;
3642 ChessMove endtype = EndOfFile;
3645 whitename = star_match[1];
3646 blackname = star_match[2];
3647 why = star_match[3];
3648 endtoken = star_match[4];
3650 whitename = star_match[1];
3651 blackname = star_match[3];
3652 why = star_match[5];
3653 endtoken = star_match[6];
3656 /* Game start messages */
3657 if (strncmp(why, "Creating ", 9) == 0 ||
3658 strncmp(why, "Continuing ", 11) == 0) {
3659 gs_gamenum = gamenum;
3660 safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
3661 VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
3663 if (appData.zippyPlay) {
3664 ZippyGameStart(whitename, blackname);
3667 partnerBoardValid = FALSE; // [HGM] bughouse
3671 /* Game end messages */
3672 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3673 ics_gamenum != gamenum) {
3676 while (endtoken[0] == ' ') endtoken++;
3677 switch (endtoken[0]) {
3680 endtype = GameUnfinished;
3683 endtype = BlackWins;
3686 if (endtoken[1] == '/')
3687 endtype = GameIsDrawn;
3689 endtype = WhiteWins;
3692 GameEnds(endtype, why, GE_ICS);
3694 if (appData.zippyPlay && first.initDone) {
3695 ZippyGameEnd(endtype, why);
3696 if (first.pr == NULL) {
3697 /* Start the next process early so that we'll
3698 be ready for the next challenge */
3699 StartChessProgram(&first);
3701 /* Send "new" early, in case this command takes
3702 a long time to finish, so that we'll be ready
3703 for the next challenge. */
3704 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3708 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
3712 if (looking_at(buf, &i, "Removing game * from observation") ||
3713 looking_at(buf, &i, "no longer observing game *") ||
3714 looking_at(buf, &i, "Game * (*) has no examiners")) {
3715 if (gameMode == IcsObserving &&
3716 atoi(star_match[0]) == ics_gamenum)
3718 /* icsEngineAnalyze */
3719 if (appData.icsEngineAnalyze) {
3726 ics_user_moved = FALSE;
3731 if (looking_at(buf, &i, "no longer examining game *")) {
3732 if (gameMode == IcsExamining &&
3733 atoi(star_match[0]) == ics_gamenum)
3737 ics_user_moved = FALSE;
3742 /* Advance leftover_start past any newlines we find,
3743 so only partial lines can get reparsed */
3744 if (looking_at(buf, &i, "\n")) {
3745 prevColor = curColor;
3746 if (curColor != ColorNormal) {
3747 if (oldi > next_out) {
3748 SendToPlayer(&buf[next_out], oldi - next_out);
3751 Colorize(ColorNormal, FALSE);
3752 curColor = ColorNormal;
3754 if (started == STARTED_BOARD) {
3755 started = STARTED_NONE;
3756 parse[parse_pos] = NULLCHAR;
3757 ParseBoard12(parse);
3760 /* Send premove here */
3761 if (appData.premove) {
3763 if (currentMove == 0 &&
3764 gameMode == IcsPlayingWhite &&
3765 appData.premoveWhite) {
3766 snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
3767 if (appData.debugMode)
3768 fprintf(debugFP, "Sending premove:\n");
3770 } else if (currentMove == 1 &&
3771 gameMode == IcsPlayingBlack &&
3772 appData.premoveBlack) {
3773 snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
3774 if (appData.debugMode)
3775 fprintf(debugFP, "Sending premove:\n");
3777 } else if (gotPremove) {
3779 ClearPremoveHighlights();
3780 if (appData.debugMode)
3781 fprintf(debugFP, "Sending premove:\n");
3782 UserMoveEvent(premoveFromX, premoveFromY,
3783 premoveToX, premoveToY,
3788 /* Usually suppress following prompt */
3789 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
3790 while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
3791 if (looking_at(buf, &i, "*% ")) {
3792 savingComment = FALSE;
3797 } else if (started == STARTED_HOLDINGS) {
3799 char new_piece[MSG_SIZ];
3800 started = STARTED_NONE;
3801 parse[parse_pos] = NULLCHAR;
3802 if (appData.debugMode)
3803 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
3804 parse, currentMove);
3805 if (sscanf(parse, " game %d", &gamenum) == 1) {
3806 if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
3807 if (gameInfo.variant == VariantNormal) {
3808 /* [HGM] We seem to switch variant during a game!
3809 * Presumably no holdings were displayed, so we have
3810 * to move the position two files to the right to
3811 * create room for them!
3813 VariantClass newVariant;
3814 switch(gameInfo.boardWidth) { // base guess on board width
3815 case 9: newVariant = VariantShogi; break;
3816 case 10: newVariant = VariantGreat; break;
3817 default: newVariant = VariantCrazyhouse; break;
3819 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
3820 /* Get a move list just to see the header, which
3821 will tell us whether this is really bug or zh */
3822 if (ics_getting_history == H_FALSE) {
3823 ics_getting_history = H_REQUESTED;
3824 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
3828 new_piece[0] = NULLCHAR;
3829 sscanf(parse, "game %d white [%s black [%s <- %s",
3830 &gamenum, white_holding, black_holding,
3832 white_holding[strlen(white_holding)-1] = NULLCHAR;
3833 black_holding[strlen(black_holding)-1] = NULLCHAR;
3834 /* [HGM] copy holdings to board holdings area */
3835 CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
3836 CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
3837 boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
3839 if (appData.zippyPlay && first.initDone) {
3840 ZippyHoldings(white_holding, black_holding,
3844 if (tinyLayout || smallLayout) {
3845 char wh[16], bh[16];
3846 PackHolding(wh, white_holding);
3847 PackHolding(bh, black_holding);
3848 snprintf(str, MSG_SIZ,"[%s-%s] %s-%s", wh, bh,
3849 gameInfo.white, gameInfo.black);
3851 snprintf(str, MSG_SIZ, "%s [%s] vs. %s [%s]",
3852 gameInfo.white, white_holding,
3853 gameInfo.black, black_holding);
3855 if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
3856 DrawPosition(FALSE, boards[currentMove]);
3858 } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
3859 sscanf(parse, "game %d white [%s black [%s <- %s",
3860 &gamenum, white_holding, black_holding,
3862 white_holding[strlen(white_holding)-1] = NULLCHAR;
3863 black_holding[strlen(black_holding)-1] = NULLCHAR;
3864 /* [HGM] copy holdings to partner-board holdings area */
3865 CopyHoldings(partnerBoard, white_holding, WhitePawn);
3866 CopyHoldings(partnerBoard, black_holding, BlackPawn);
3867 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
3868 if(partnerUp) DrawPosition(FALSE, partnerBoard);
3869 if(twoBoards) { partnerUp = 0; flipView = !flipView; }
3872 /* Suppress following prompt */
3873 if (looking_at(buf, &i, "*% ")) {
3874 if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
3875 savingComment = FALSE;
3883 i++; /* skip unparsed character and loop back */
3886 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
3887 // started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
3888 // SendToPlayer(&buf[next_out], i - next_out);
3889 started != STARTED_HOLDINGS && leftover_start > next_out) {
3890 SendToPlayer(&buf[next_out], leftover_start - next_out);
3894 leftover_len = buf_len - leftover_start;
3895 /* if buffer ends with something we couldn't parse,
3896 reparse it after appending the next read */
3898 } else if (count == 0) {
3899 RemoveInputSource(isr);
3900 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
3902 DisplayFatalError(_("Error reading from ICS"), error, 1);
3907 /* Board style 12 looks like this:
3909 <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
3911 * The "<12> " is stripped before it gets to this routine. The two
3912 * trailing 0's (flip state and clock ticking) are later addition, and
3913 * some chess servers may not have them, or may have only the first.
3914 * Additional trailing fields may be added in the future.
3917 #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"
3919 #define RELATION_OBSERVING_PLAYED 0
3920 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
3921 #define RELATION_PLAYING_MYMOVE 1
3922 #define RELATION_PLAYING_NOTMYMOVE -1
3923 #define RELATION_EXAMINING 2
3924 #define RELATION_ISOLATED_BOARD -3
3925 #define RELATION_STARTING_POSITION -4 /* FICS only */
3928 ParseBoard12(string)
3931 GameMode newGameMode;
3932 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0, i;
3933 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time, takeback;
3934 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
3935 char to_play, board_chars[200];
3936 char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
3937 char black[32], white[32];
3939 int prevMove = currentMove;
3942 int fromX, fromY, toX, toY;
3944 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
3945 char *bookHit = NULL; // [HGM] book
3946 Boolean weird = FALSE, reqFlag = FALSE;
3948 fromX = fromY = toX = toY = -1;
3952 if (appData.debugMode)
3953 fprintf(debugFP, _("Parsing board: %s\n"), string);
3955 move_str[0] = NULLCHAR;
3956 elapsed_time[0] = NULLCHAR;
3957 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
3959 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
3960 if(string[i] == ' ') { ranks++; files = 0; }
3962 if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
3965 for(j = 0; j <i; j++) board_chars[j] = string[j];
3966 board_chars[i] = '\0';
3969 n = sscanf(string, PATTERN, &to_play, &double_push,
3970 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
3971 &gamenum, white, black, &relation, &basetime, &increment,
3972 &white_stren, &black_stren, &white_time, &black_time,
3973 &moveNum, str, elapsed_time, move_str, &ics_flip,
3977 snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
3978 DisplayError(str, 0);
3982 /* Convert the move number to internal form */
3983 moveNum = (moveNum - 1) * 2;
3984 if (to_play == 'B') moveNum++;
3985 if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
3986 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
3992 case RELATION_OBSERVING_PLAYED:
3993 case RELATION_OBSERVING_STATIC:
3994 if (gamenum == -1) {
3995 /* Old ICC buglet */
3996 relation = RELATION_OBSERVING_STATIC;
3998 newGameMode = IcsObserving;
4000 case RELATION_PLAYING_MYMOVE:
4001 case RELATION_PLAYING_NOTMYMOVE:
4003 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
4004 IcsPlayingWhite : IcsPlayingBlack;
4006 case RELATION_EXAMINING:
4007 newGameMode = IcsExamining;
4009 case RELATION_ISOLATED_BOARD:
4011 /* Just display this board. If user was doing something else,
4012 we will forget about it until the next board comes. */
4013 newGameMode = IcsIdle;
4015 case RELATION_STARTING_POSITION:
4016 newGameMode = gameMode;
4020 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
4021 && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
4022 // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
4024 for (k = 0; k < ranks; k++) {
4025 for (j = 0; j < files; j++)
4026 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4027 if(gameInfo.holdingsWidth > 1) {
4028 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4029 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4032 CopyBoard(partnerBoard, board);
4033 if(toSqr = strchr(str, '/')) { // extract highlights from long move
4034 partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
4035 partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
4036 } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
4037 if(toSqr = strchr(str, '-')) {
4038 partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
4039 partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
4040 } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
4041 if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
4042 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
4043 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4044 if(twoBoards) { partnerUp = 0; flipView = !flipView; } // [HGM] dual
4045 snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time/60000, (white_time%60000)/1000,
4046 (black_time/60000), (black_time%60000)/1000, white_stren, black_stren, to_play);
4047 DisplayMessage(partnerStatus, "");
4048 partnerBoardValid = TRUE;
4052 /* Modify behavior for initial board display on move listing
4055 switch (ics_getting_history) {
4059 case H_GOT_REQ_HEADER:
4060 case H_GOT_UNREQ_HEADER:
4061 /* This is the initial position of the current game */
4062 gamenum = ics_gamenum;
4063 moveNum = 0; /* old ICS bug workaround */
4064 if (to_play == 'B') {
4065 startedFromSetupPosition = TRUE;
4066 blackPlaysFirst = TRUE;
4068 if (forwardMostMove == 0) forwardMostMove = 1;
4069 if (backwardMostMove == 0) backwardMostMove = 1;
4070 if (currentMove == 0) currentMove = 1;
4072 newGameMode = gameMode;
4073 relation = RELATION_STARTING_POSITION; /* ICC needs this */
4075 case H_GOT_UNWANTED_HEADER:
4076 /* This is an initial board that we don't want */
4078 case H_GETTING_MOVES:
4079 /* Should not happen */
4080 DisplayError(_("Error gathering move list: extra board"), 0);
4081 ics_getting_history = H_FALSE;
4085 if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4086 weird && (int)gameInfo.variant < (int)VariantShogi) {
4087 /* [HGM] We seem to have switched variant unexpectedly
4088 * Try to guess new variant from board size
4090 VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4091 if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4092 if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4093 if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4094 if(ranks == 9 && files == 9) newVariant = VariantShogi; else
4095 if(!weird) newVariant = VariantNormal;
4096 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4097 /* Get a move list just to see the header, which
4098 will tell us whether this is really bug or zh */
4099 if (ics_getting_history == H_FALSE) {
4100 ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4101 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4106 /* Take action if this is the first board of a new game, or of a
4107 different game than is currently being displayed. */
4108 if (gamenum != ics_gamenum || newGameMode != gameMode ||
4109 relation == RELATION_ISOLATED_BOARD) {
4111 /* Forget the old game and get the history (if any) of the new one */
4112 if (gameMode != BeginningOfGame) {
4116 if (appData.autoRaiseBoard) BoardToTop();
4118 if (gamenum == -1) {
4119 newGameMode = IcsIdle;
4120 } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4121 appData.getMoveList && !reqFlag) {
4122 /* Need to get game history */
4123 ics_getting_history = H_REQUESTED;
4124 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4128 /* Initially flip the board to have black on the bottom if playing
4129 black or if the ICS flip flag is set, but let the user change
4130 it with the Flip View button. */
4131 flipView = appData.autoFlipView ?
4132 (newGameMode == IcsPlayingBlack) || ics_flip :
4135 /* Done with values from previous mode; copy in new ones */
4136 gameMode = newGameMode;
4138 ics_gamenum = gamenum;
4139 if (gamenum == gs_gamenum) {
4140 int klen = strlen(gs_kind);
4141 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4142 snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4143 gameInfo.event = StrSave(str);
4145 gameInfo.event = StrSave("ICS game");
4147 gameInfo.site = StrSave(appData.icsHost);
4148 gameInfo.date = PGNDate();
4149 gameInfo.round = StrSave("-");
4150 gameInfo.white = StrSave(white);
4151 gameInfo.black = StrSave(black);
4152 timeControl = basetime * 60 * 1000;
4154 timeIncrement = increment * 1000;
4155 movesPerSession = 0;
4156 gameInfo.timeControl = TimeControlTagValue();
4157 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4158 if (appData.debugMode) {
4159 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4160 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4161 setbuf(debugFP, NULL);
4164 gameInfo.outOfBook = NULL;
4166 /* Do we have the ratings? */
4167 if (strcmp(player1Name, white) == 0 &&
4168 strcmp(player2Name, black) == 0) {
4169 if (appData.debugMode)
4170 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4171 player1Rating, player2Rating);
4172 gameInfo.whiteRating = player1Rating;
4173 gameInfo.blackRating = player2Rating;
4174 } else if (strcmp(player2Name, white) == 0 &&
4175 strcmp(player1Name, black) == 0) {
4176 if (appData.debugMode)
4177 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4178 player2Rating, player1Rating);
4179 gameInfo.whiteRating = player2Rating;
4180 gameInfo.blackRating = player1Rating;
4182 player1Name[0] = player2Name[0] = NULLCHAR;
4184 /* Silence shouts if requested */
4185 if (appData.quietPlay &&
4186 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4187 SendToICS(ics_prefix);
4188 SendToICS("set shout 0\n");
4192 /* Deal with midgame name changes */
4194 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4195 if (gameInfo.white) free(gameInfo.white);
4196 gameInfo.white = StrSave(white);
4198 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4199 if (gameInfo.black) free(gameInfo.black);
4200 gameInfo.black = StrSave(black);
4204 /* Throw away game result if anything actually changes in examine mode */
4205 if (gameMode == IcsExamining && !newGame) {
4206 gameInfo.result = GameUnfinished;
4207 if (gameInfo.resultDetails != NULL) {
4208 free(gameInfo.resultDetails);
4209 gameInfo.resultDetails = NULL;
4213 /* In pausing && IcsExamining mode, we ignore boards coming
4214 in if they are in a different variation than we are. */
4215 if (pauseExamInvalid) return;
4216 if (pausing && gameMode == IcsExamining) {
4217 if (moveNum <= pauseExamForwardMostMove) {
4218 pauseExamInvalid = TRUE;
4219 forwardMostMove = pauseExamForwardMostMove;
4224 if (appData.debugMode) {
4225 fprintf(debugFP, "load %dx%d board\n", files, ranks);
4227 /* Parse the board */
4228 for (k = 0; k < ranks; k++) {
4229 for (j = 0; j < files; j++)
4230 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4231 if(gameInfo.holdingsWidth > 1) {
4232 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4233 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4236 CopyBoard(boards[moveNum], board);
4237 boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4239 startedFromSetupPosition =
4240 !CompareBoards(board, initialPosition);
4241 if(startedFromSetupPosition)
4242 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4245 /* [HGM] Set castling rights. Take the outermost Rooks,
4246 to make it also work for FRC opening positions. Note that board12
4247 is really defective for later FRC positions, as it has no way to
4248 indicate which Rook can castle if they are on the same side of King.
4249 For the initial position we grant rights to the outermost Rooks,
4250 and remember thos rights, and we then copy them on positions
4251 later in an FRC game. This means WB might not recognize castlings with
4252 Rooks that have moved back to their original position as illegal,
4253 but in ICS mode that is not its job anyway.
4255 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4256 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4258 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4259 if(board[0][i] == WhiteRook) j = i;
4260 initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4261 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4262 if(board[0][i] == WhiteRook) j = i;
4263 initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4264 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4265 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4266 initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4267 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4268 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4269 initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4271 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4272 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4273 if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4274 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4275 if(board[BOARD_HEIGHT-1][k] == bKing)
4276 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4277 if(gameInfo.variant == VariantTwoKings) {
4278 // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4279 if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4280 if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4283 r = boards[moveNum][CASTLING][0] = initialRights[0];
4284 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4285 r = boards[moveNum][CASTLING][1] = initialRights[1];
4286 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4287 r = boards[moveNum][CASTLING][3] = initialRights[3];
4288 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4289 r = boards[moveNum][CASTLING][4] = initialRights[4];
4290 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4291 /* wildcastle kludge: always assume King has rights */
4292 r = boards[moveNum][CASTLING][2] = initialRights[2];
4293 r = boards[moveNum][CASTLING][5] = initialRights[5];
4295 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4296 boards[moveNum][EP_STATUS] = double_push == -1 ? EP_NONE : double_push + BOARD_LEFT;
4299 if (ics_getting_history == H_GOT_REQ_HEADER ||
4300 ics_getting_history == H_GOT_UNREQ_HEADER) {
4301 /* This was an initial position from a move list, not
4302 the current position */
4306 /* Update currentMove and known move number limits */
4307 newMove = newGame || moveNum > forwardMostMove;
4310 forwardMostMove = backwardMostMove = currentMove = moveNum;
4311 if (gameMode == IcsExamining && moveNum == 0) {
4312 /* Workaround for ICS limitation: we are not told the wild
4313 type when starting to examine a game. But if we ask for
4314 the move list, the move list header will tell us */
4315 ics_getting_history = H_REQUESTED;
4316 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4319 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4320 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4322 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4323 /* [HGM] applied this also to an engine that is silently watching */
4324 if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4325 (gameMode == IcsObserving || gameMode == IcsExamining) &&
4326 gameInfo.variant == currentlyInitializedVariant) {
4327 takeback = forwardMostMove - moveNum;
4328 for (i = 0; i < takeback; i++) {
4329 if (appData.debugMode) fprintf(debugFP, "take back move\n");
4330 SendToProgram("undo\n", &first);
4335 forwardMostMove = moveNum;
4336 if (!pausing || currentMove > forwardMostMove)
4337 currentMove = forwardMostMove;
4339 /* New part of history that is not contiguous with old part */
4340 if (pausing && gameMode == IcsExamining) {
4341 pauseExamInvalid = TRUE;
4342 forwardMostMove = pauseExamForwardMostMove;
4345 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4347 if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4348 // [HGM] when we will receive the move list we now request, it will be
4349 // fed to the engine from the first move on. So if the engine is not
4350 // in the initial position now, bring it there.
4351 InitChessProgram(&first, 0);
4354 ics_getting_history = H_REQUESTED;
4355 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4358 forwardMostMove = backwardMostMove = currentMove = moveNum;
4361 /* Update the clocks */
4362 if (strchr(elapsed_time, '.')) {
4364 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4365 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4367 /* Time is in seconds */
4368 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4369 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4374 if (appData.zippyPlay && newGame &&
4375 gameMode != IcsObserving && gameMode != IcsIdle &&
4376 gameMode != IcsExamining)
4377 ZippyFirstBoard(moveNum, basetime, increment);
4380 /* Put the move on the move list, first converting
4381 to canonical algebraic form. */
4383 if (appData.debugMode) {
4384 if (appData.debugMode) { int f = forwardMostMove;
4385 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4386 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4387 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4389 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4390 fprintf(debugFP, "moveNum = %d\n", moveNum);
4391 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4392 setbuf(debugFP, NULL);
4394 if (moveNum <= backwardMostMove) {
4395 /* We don't know what the board looked like before
4397 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4398 strcat(parseList[moveNum - 1], " ");
4399 strcat(parseList[moveNum - 1], elapsed_time);
4400 moveList[moveNum - 1][0] = NULLCHAR;
4401 } else if (strcmp(move_str, "none") == 0) {
4402 // [HGM] long SAN: swapped order; test for 'none' before parsing move
4403 /* Again, we don't know what the board looked like;
4404 this is really the start of the game. */
4405 parseList[moveNum - 1][0] = NULLCHAR;
4406 moveList[moveNum - 1][0] = NULLCHAR;
4407 backwardMostMove = moveNum;
4408 startedFromSetupPosition = TRUE;
4409 fromX = fromY = toX = toY = -1;
4411 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4412 // So we parse the long-algebraic move string in stead of the SAN move
4413 int valid; char buf[MSG_SIZ], *prom;
4415 if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4416 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4417 // str looks something like "Q/a1-a2"; kill the slash
4419 snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4420 else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4421 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4422 strcat(buf, prom); // long move lacks promo specification!
4423 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4424 if(appData.debugMode)
4425 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4426 safeStrCpy(move_str, buf, MSG_SIZ);
4428 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4429 &fromX, &fromY, &toX, &toY, &promoChar)
4430 || ParseOneMove(buf, moveNum - 1, &moveType,
4431 &fromX, &fromY, &toX, &toY, &promoChar);
4432 // end of long SAN patch
4434 (void) CoordsToAlgebraic(boards[moveNum - 1],
4435 PosFlags(moveNum - 1),
4436 fromY, fromX, toY, toX, promoChar,
4437 parseList[moveNum-1]);
4438 switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4444 if(gameInfo.variant != VariantShogi)
4445 strcat(parseList[moveNum - 1], "+");
4448 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4449 strcat(parseList[moveNum - 1], "#");
4452 strcat(parseList[moveNum - 1], " ");
4453 strcat(parseList[moveNum - 1], elapsed_time);
4454 /* currentMoveString is set as a side-effect of ParseOneMove */
4455 if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4456 safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4457 strcat(moveList[moveNum - 1], "\n");
4459 if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper
4460 && gameInfo.variant != VariantGreat) // inherit info that ICS does not give from previous board
4461 for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4462 ChessSquare old, new = boards[moveNum][k][j];
4463 if(fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4464 old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4465 if(old == new) continue;
4466 if(old == PROMOTED new) boards[moveNum][k][j] = old; // prevent promoted pieces to revert to primordial ones
4467 else if(new == WhiteWazir || new == BlackWazir) {
4468 if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4469 boards[moveNum][k][j] = PROMOTED old; // choose correct type of Gold in promotion
4470 else boards[moveNum][k][j] = old; // preserve type of Gold
4471 } else if((old == WhitePawn || old == BlackPawn) && new != EmptySquare) // Pawn promotions (but not e.p.capture!)
4472 boards[moveNum][k][j] = PROMOTED new; // use non-primordial representation of chosen piece
4475 /* Move from ICS was illegal!? Punt. */
4476 if (appData.debugMode) {
4477 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4478 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4480 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4481 strcat(parseList[moveNum - 1], " ");
4482 strcat(parseList[moveNum - 1], elapsed_time);
4483 moveList[moveNum - 1][0] = NULLCHAR;
4484 fromX = fromY = toX = toY = -1;
4487 if (appData.debugMode) {
4488 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4489 setbuf(debugFP, NULL);
4493 /* Send move to chess program (BEFORE animating it). */
4494 if (appData.zippyPlay && !newGame && newMove &&
4495 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4497 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4498 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4499 if (moveList[moveNum - 1][0] == NULLCHAR) {
4500 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4502 DisplayError(str, 0);
4504 if (first.sendTime) {
4505 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4507 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4508 if (firstMove && !bookHit) {
4510 if (first.useColors) {
4511 SendToProgram(gameMode == IcsPlayingWhite ?
4513 "black\ngo\n", &first);
4515 SendToProgram("go\n", &first);
4517 first.maybeThinking = TRUE;
4520 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4521 if (moveList[moveNum - 1][0] == NULLCHAR) {
4522 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4523 DisplayError(str, 0);
4525 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4526 SendMoveToProgram(moveNum - 1, &first);
4533 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
4534 /* If move comes from a remote source, animate it. If it
4535 isn't remote, it will have already been animated. */
4536 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
4537 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
4539 if (!pausing && appData.highlightLastMove) {
4540 SetHighlights(fromX, fromY, toX, toY);
4544 /* Start the clocks */
4545 whiteFlag = blackFlag = FALSE;
4546 appData.clockMode = !(basetime == 0 && increment == 0);
4548 ics_clock_paused = TRUE;
4550 } else if (ticking == 1) {
4551 ics_clock_paused = FALSE;
4553 if (gameMode == IcsIdle ||
4554 relation == RELATION_OBSERVING_STATIC ||
4555 relation == RELATION_EXAMINING ||
4557 DisplayBothClocks();
4561 /* Display opponents and material strengths */
4562 if (gameInfo.variant != VariantBughouse &&
4563 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
4564 if (tinyLayout || smallLayout) {
4565 if(gameInfo.variant == VariantNormal)
4566 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
4567 gameInfo.white, white_stren, gameInfo.black, black_stren,
4568 basetime, increment);
4570 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
4571 gameInfo.white, white_stren, gameInfo.black, black_stren,
4572 basetime, increment, (int) gameInfo.variant);
4574 if(gameInfo.variant == VariantNormal)
4575 snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d}",
4576 gameInfo.white, white_stren, gameInfo.black, black_stren,
4577 basetime, increment);
4579 snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d %s}",
4580 gameInfo.white, white_stren, gameInfo.black, black_stren,
4581 basetime, increment, VariantName(gameInfo.variant));
4584 if (appData.debugMode) {
4585 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
4590 /* Display the board */
4591 if (!pausing && !appData.noGUI) {
4593 if (appData.premove)
4595 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
4596 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
4597 ClearPremoveHighlights();
4599 j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
4600 if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
4601 DrawPosition(j, boards[currentMove]);
4603 DisplayMove(moveNum - 1);
4604 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
4605 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
4606 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
4607 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
4611 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
4613 if(bookHit) { // [HGM] book: simulate book reply
4614 static char bookMove[MSG_SIZ]; // a bit generous?
4616 programStats.nodes = programStats.depth = programStats.time =
4617 programStats.score = programStats.got_only_move = 0;
4618 sprintf(programStats.movelist, "%s (xbook)", bookHit);
4620 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
4621 strcat(bookMove, bookHit);
4622 HandleMachineMove(bookMove, &first);
4631 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
4632 ics_getting_history = H_REQUESTED;
4633 snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
4639 AnalysisPeriodicEvent(force)
4642 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
4643 && !force) || !appData.periodicUpdates)
4646 /* Send . command to Crafty to collect stats */
4647 SendToProgram(".\n", &first);
4649 /* Don't send another until we get a response (this makes
4650 us stop sending to old Crafty's which don't understand
4651 the "." command (sending illegal cmds resets node count & time,
4652 which looks bad)) */
4653 programStats.ok_to_send = 0;
4656 void ics_update_width(new_width)
4659 ics_printf("set width %d\n", new_width);
4663 SendMoveToProgram(moveNum, cps)
4665 ChessProgramState *cps;
4669 if (cps->useUsermove) {
4670 SendToProgram("usermove ", cps);
4674 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
4675 int len = space - parseList[moveNum];
4676 memcpy(buf, parseList[moveNum], len);
4678 buf[len] = NULLCHAR;
4680 snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
4682 SendToProgram(buf, cps);
4684 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
4685 AlphaRank(moveList[moveNum], 4);
4686 SendToProgram(moveList[moveNum], cps);
4687 AlphaRank(moveList[moveNum], 4); // and back
4689 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
4690 * the engine. It would be nice to have a better way to identify castle
4692 if((gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom)
4693 && cps->useOOCastle) {
4694 int fromX = moveList[moveNum][0] - AAA;
4695 int fromY = moveList[moveNum][1] - ONE;
4696 int toX = moveList[moveNum][2] - AAA;
4697 int toY = moveList[moveNum][3] - ONE;
4698 if((boards[moveNum][fromY][fromX] == WhiteKing
4699 && boards[moveNum][toY][toX] == WhiteRook)
4700 || (boards[moveNum][fromY][fromX] == BlackKing
4701 && boards[moveNum][toY][toX] == BlackRook)) {
4702 if(toX > fromX) SendToProgram("O-O\n", cps);
4703 else SendToProgram("O-O-O\n", cps);
4705 else SendToProgram(moveList[moveNum], cps);
4707 else SendToProgram(moveList[moveNum], cps);
4708 /* End of additions by Tord */
4711 /* [HGM] setting up the opening has brought engine in force mode! */
4712 /* Send 'go' if we are in a mode where machine should play. */
4713 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
4714 (gameMode == TwoMachinesPlay ||
4716 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
4718 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
4719 SendToProgram("go\n", cps);
4720 if (appData.debugMode) {
4721 fprintf(debugFP, "(extra)\n");
4724 setboardSpoiledMachineBlack = 0;
4728 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar)
4730 int fromX, fromY, toX, toY;
4733 char user_move[MSG_SIZ];
4737 snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
4738 (int)moveType, fromX, fromY, toX, toY);
4739 DisplayError(user_move + strlen("say "), 0);
4741 case WhiteKingSideCastle:
4742 case BlackKingSideCastle:
4743 case WhiteQueenSideCastleWild:
4744 case BlackQueenSideCastleWild:
4746 case WhiteHSideCastleFR:
4747 case BlackHSideCastleFR:
4749 snprintf(user_move, MSG_SIZ, "o-o\n");
4751 case WhiteQueenSideCastle:
4752 case BlackQueenSideCastle:
4753 case WhiteKingSideCastleWild:
4754 case BlackKingSideCastleWild:
4756 case WhiteASideCastleFR:
4757 case BlackASideCastleFR:
4759 snprintf(user_move, MSG_SIZ, "o-o-o\n");
4761 case WhiteNonPromotion:
4762 case BlackNonPromotion:
4763 sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4765 case WhitePromotion:
4766 case BlackPromotion:
4767 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
4768 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
4769 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4770 PieceToChar(WhiteFerz));
4771 else if(gameInfo.variant == VariantGreat)
4772 snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
4773 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4774 PieceToChar(WhiteMan));
4776 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
4777 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4783 snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
4784 ToUpper(PieceToChar((ChessSquare) fromX)),
4785 AAA + toX, ONE + toY);
4787 case IllegalMove: /* could be a variant we don't quite understand */
4788 if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
4790 case WhiteCapturesEnPassant:
4791 case BlackCapturesEnPassant:
4792 snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
4793 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4796 SendToICS(user_move);
4797 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
4798 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
4803 { // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
4804 int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
4805 static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
4806 if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
4807 DisplayError("You cannot do this while you are playing or observing", 0);
4810 if(gameMode != IcsExamining) { // is this ever not the case?
4811 char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
4813 if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
4814 snprintf(command,MSG_SIZ, "match %s", ics_handle);
4815 } else { // on FICS we must first go to general examine mode
4816 safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
4818 if(gameInfo.variant != VariantNormal) {
4819 // try figure out wild number, as xboard names are not always valid on ICS
4820 for(i=1; i<=36; i++) {
4821 snprintf(buf, MSG_SIZ, "wild/%d", i);
4822 if(StringToVariant(buf) == gameInfo.variant) break;
4824 if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
4825 else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
4826 else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
4827 } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
4828 SendToICS(ics_prefix);
4830 if(startedFromSetupPosition || backwardMostMove != 0) {
4831 fen = PositionToFEN(backwardMostMove, NULL);
4832 if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
4833 snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
4835 } else { // FICS: everything has to set by separate bsetup commands
4836 p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
4837 snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
4839 if(!WhiteOnMove(backwardMostMove)) {
4840 SendToICS("bsetup tomove black\n");
4842 i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
4843 snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
4845 i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
4846 snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
4848 i = boards[backwardMostMove][EP_STATUS];
4849 if(i >= 0) { // set e.p.
4850 snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
4856 if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
4857 SendToICS("bsetup done\n"); // switch to normal examining.
4859 for(i = backwardMostMove; i<last; i++) {
4861 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
4864 SendToICS(ics_prefix);
4865 SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
4869 CoordsToComputerAlgebraic(rf, ff, rt, ft, promoChar, move)
4874 if (rf == DROP_RANK) {
4875 sprintf(move, "%c@%c%c\n",
4876 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
4878 if (promoChar == 'x' || promoChar == NULLCHAR) {
4879 sprintf(move, "%c%c%c%c\n",
4880 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
4882 sprintf(move, "%c%c%c%c%c\n",
4883 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
4889 ProcessICSInitScript(f)
4894 while (fgets(buf, MSG_SIZ, f)) {
4895 SendToICSDelayed(buf,(long)appData.msLoginDelay);
4902 static int lastX, lastY, selectFlag, dragging;
4907 ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
4908 if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
4909 if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
4910 if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
4911 if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
4912 if(fromY != BOARD_HEIGHT-2 && fromY != 1) pawn = EmptySquare;
4915 if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
4916 else if((int)promoSweep == -1) promoSweep = WhiteKing;
4917 else if(promoSweep == BlackPawn && step < 0) promoSweep = WhitePawn;
4918 else if(promoSweep == WhiteKing && step > 0) promoSweep = BlackKing;
4920 } while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' || promoSweep == pawn ||
4921 appData.testLegality && (promoSweep == king ||
4922 gameInfo.variant == VariantShogi && promoSweep != PROMOTED last && last != PROMOTED promoSweep && last != promoSweep));
4923 ChangeDragPiece(promoSweep);
4926 int PromoScroll(int x, int y)
4930 if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
4931 if(abs(x - lastX) < 15 && abs(y - lastY) < 15) return FALSE;
4932 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
4933 if(!step) return FALSE;
4934 lastX = x; lastY = y;
4935 if((promoSweep < BlackPawn) == flipView) step = -step;
4936 if(step > 0) selectFlag = 1;
4937 if(!selectFlag) Sweep(step);
4944 ChessSquare piece = boards[currentMove][toY][toX];
4947 if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
4948 if((int)pieceSweep == -1) pieceSweep = BlackKing;
4949 if(!step) step = -1;
4950 } while(PieceToChar(pieceSweep) == '.');
4951 boards[currentMove][toY][toX] = pieceSweep;
4952 DrawPosition(FALSE, boards[currentMove]);
4953 boards[currentMove][toY][toX] = piece;
4955 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
4957 AlphaRank(char *move, int n)
4959 // char *p = move, c; int x, y;
4961 if (appData.debugMode) {
4962 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
4966 move[2]>='0' && move[2]<='9' &&
4967 move[3]>='a' && move[3]<='x' ) {
4969 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4970 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4972 if(move[0]>='0' && move[0]<='9' &&
4973 move[1]>='a' && move[1]<='x' &&
4974 move[2]>='0' && move[2]<='9' &&
4975 move[3]>='a' && move[3]<='x' ) {
4976 /* input move, Shogi -> normal */
4977 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
4978 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
4979 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4980 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4983 move[3]>='0' && move[3]<='9' &&
4984 move[2]>='a' && move[2]<='x' ) {
4986 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4987 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4990 move[0]>='a' && move[0]<='x' &&
4991 move[3]>='0' && move[3]<='9' &&
4992 move[2]>='a' && move[2]<='x' ) {
4993 /* output move, normal -> Shogi */
4994 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
4995 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
4996 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4997 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4998 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
5000 if (appData.debugMode) {
5001 fprintf(debugFP, " out = '%s'\n", move);
5005 char yy_textstr[8000];
5007 /* Parser for moves from gnuchess, ICS, or user typein box */
5009 ParseOneMove(move, moveNum, moveType, fromX, fromY, toX, toY, promoChar)
5012 ChessMove *moveType;
5013 int *fromX, *fromY, *toX, *toY;
5016 *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
5018 switch (*moveType) {
5019 case WhitePromotion:
5020 case BlackPromotion:
5021 case WhiteNonPromotion:
5022 case BlackNonPromotion:
5024 case WhiteCapturesEnPassant:
5025 case BlackCapturesEnPassant:
5026 case WhiteKingSideCastle:
5027 case WhiteQueenSideCastle:
5028 case BlackKingSideCastle:
5029 case BlackQueenSideCastle:
5030 case WhiteKingSideCastleWild:
5031 case WhiteQueenSideCastleWild:
5032 case BlackKingSideCastleWild:
5033 case BlackQueenSideCastleWild:
5034 /* Code added by Tord: */
5035 case WhiteHSideCastleFR:
5036 case WhiteASideCastleFR:
5037 case BlackHSideCastleFR:
5038 case BlackASideCastleFR:
5039 /* End of code added by Tord */
5040 case IllegalMove: /* bug or odd chess variant */
5041 *fromX = currentMoveString[0] - AAA;
5042 *fromY = currentMoveString[1] - ONE;
5043 *toX = currentMoveString[2] - AAA;
5044 *toY = currentMoveString[3] - ONE;
5045 *promoChar = currentMoveString[4];
5046 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
5047 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
5048 if (appData.debugMode) {
5049 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
5051 *fromX = *fromY = *toX = *toY = 0;
5054 if (appData.testLegality) {
5055 return (*moveType != IllegalMove);
5057 return !(*fromX == *toX && *fromY == *toY) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
5058 WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
5063 *fromX = *moveType == WhiteDrop ?
5064 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5065 (int) CharToPiece(ToLower(currentMoveString[0]));
5067 *toX = currentMoveString[2] - AAA;
5068 *toY = currentMoveString[3] - ONE;
5069 *promoChar = NULLCHAR;
5073 case ImpossibleMove:
5083 if (appData.debugMode) {
5084 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
5087 *fromX = *fromY = *toX = *toY = 0;
5088 *promoChar = NULLCHAR;
5095 ParsePV(char *pv, Boolean storeComments)
5096 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
5097 int fromX, fromY, toX, toY; char promoChar;
5102 endPV = forwardMostMove;
5104 while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
5105 if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
5106 valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
5107 if(appData.debugMode){
5108 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);
5110 if(!valid && nr == 0 &&
5111 ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
5112 nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
5113 // Hande case where played move is different from leading PV move
5114 CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
5115 CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
5116 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
5117 if(!CompareBoards(boards[endPV], boards[endPV+2])) {
5118 endPV += 2; // if position different, keep this
5119 moveList[endPV-1][0] = fromX + AAA;
5120 moveList[endPV-1][1] = fromY + ONE;
5121 moveList[endPV-1][2] = toX + AAA;
5122 moveList[endPV-1][3] = toY + ONE;
5123 parseList[endPV-1][0] = NULLCHAR;
5124 safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
5127 pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
5128 if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5129 if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5130 if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5131 valid++; // allow comments in PV
5135 if(endPV+1 > framePtr) break; // no space, truncate
5138 CopyBoard(boards[endPV], boards[endPV-1]);
5139 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5140 moveList[endPV-1][0] = fromX + AAA;
5141 moveList[endPV-1][1] = fromY + ONE;
5142 moveList[endPV-1][2] = toX + AAA;
5143 moveList[endPV-1][3] = toY + ONE;
5144 moveList[endPV-1][4] = promoChar;
5145 moveList[endPV-1][5] = NULLCHAR;
5146 strncat(moveList[endPV-1], "\n", MOVE_LEN);
5148 CoordsToAlgebraic(boards[endPV - 1],
5149 PosFlags(endPV - 1),
5150 fromY, fromX, toY, toX, promoChar,
5151 parseList[endPV - 1]);
5153 parseList[endPV-1][0] = NULLCHAR;
5155 currentMove = endPV;
5156 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5157 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5158 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5159 DrawPosition(TRUE, boards[currentMove]);
5163 LoadMultiPV(int x, int y, char *buf, int index, int *start, int *end)
5168 if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5169 lastX = x; lastY = y;
5170 while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5172 while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5173 if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5175 do{ while(buf[index] && buf[index] != '\n') index++;
5176 } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5178 ParsePV(buf+startPV, FALSE);
5179 *start = startPV; *end = index-1;
5184 LoadPV(int x, int y)
5185 { // called on right mouse click to load PV
5186 int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5187 lastX = x; lastY = y;
5188 ParsePV(lastPV[which], FALSE); // load the PV of the thinking engine in the boards array.
5195 if(endPV < 0) return;
5197 currentMove = forwardMostMove;
5198 ClearPremoveHighlights();
5199 DrawPosition(TRUE, boards[currentMove]);
5203 MovePV(int x, int y, int h)
5204 { // step through PV based on mouse coordinates (called on mouse move)
5205 int margin = h>>3, step = 0;
5207 // we must somehow check if right button is still down (might be released off board!)
5208 if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
5209 if(abs(x - lastX) < 7 && abs(y - lastY) < 7) return;
5210 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5212 lastX = x; lastY = y;
5214 if(pieceSweep != EmptySquare) { NextPiece(step); return; }
5215 if(endPV < 0) return;
5216 if(y < margin) step = 1; else
5217 if(y > h - margin) step = -1;
5218 if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5219 currentMove += step;
5220 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5221 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5222 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5223 DrawPosition(FALSE, boards[currentMove]);
5227 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5228 // All positions will have equal probability, but the current method will not provide a unique
5229 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5235 int piecesLeft[(int)BlackPawn];
5236 int seed, nrOfShuffles;
5238 void GetPositionNumber()
5239 { // sets global variable seed
5242 seed = appData.defaultFrcPosition;
5243 if(seed < 0) { // randomize based on time for negative FRC position numbers
5244 for(i=0; i<50; i++) seed += random();
5245 seed = random() ^ random() >> 8 ^ random() << 8;
5246 if(seed<0) seed = -seed;
5250 int put(Board board, int pieceType, int rank, int n, int shade)
5251 // put the piece on the (n-1)-th empty squares of the given shade
5255 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5256 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5257 board[rank][i] = (ChessSquare) pieceType;
5258 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5260 piecesLeft[pieceType]--;
5268 void AddOnePiece(Board board, int pieceType, int rank, int shade)
5269 // calculate where the next piece goes, (any empty square), and put it there
5273 i = seed % squaresLeft[shade];
5274 nrOfShuffles *= squaresLeft[shade];
5275 seed /= squaresLeft[shade];
5276 put(board, pieceType, rank, i, shade);
5279 void AddTwoPieces(Board board, int pieceType, int rank)
5280 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5282 int i, n=squaresLeft[ANY], j=n-1, k;
5284 k = n*(n-1)/2; // nr of possibilities, not counting permutations
5285 i = seed % k; // pick one
5288 while(i >= j) i -= j--;
5289 j = n - 1 - j; i += j;
5290 put(board, pieceType, rank, j, ANY);
5291 put(board, pieceType, rank, i, ANY);
5294 void SetUpShuffle(Board board, int number)
5298 GetPositionNumber(); nrOfShuffles = 1;
5300 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5301 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
5302 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5304 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5306 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5307 p = (int) board[0][i];
5308 if(p < (int) BlackPawn) piecesLeft[p] ++;
5309 board[0][i] = EmptySquare;
5312 if(PosFlags(0) & F_ALL_CASTLE_OK) {
5313 // shuffles restricted to allow normal castling put KRR first
5314 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5315 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5316 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5317 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5318 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5319 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5320 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
5321 put(board, WhiteRook, 0, 0, ANY);
5322 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
5325 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
5326 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
5327 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
5328 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
5329 while(piecesLeft[p] >= 2) {
5330 AddOnePiece(board, p, 0, LITE);
5331 AddOnePiece(board, p, 0, DARK);
5333 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
5336 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
5337 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
5338 // but we leave King and Rooks for last, to possibly obey FRC restriction
5339 if(p == (int)WhiteRook) continue;
5340 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
5341 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
5344 // now everything is placed, except perhaps King (Unicorn) and Rooks
5346 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
5347 // Last King gets castling rights
5348 while(piecesLeft[(int)WhiteUnicorn]) {
5349 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5350 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5353 while(piecesLeft[(int)WhiteKing]) {
5354 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5355 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5360 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
5361 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
5364 // Only Rooks can be left; simply place them all
5365 while(piecesLeft[(int)WhiteRook]) {
5366 i = put(board, WhiteRook, 0, 0, ANY);
5367 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
5370 initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
5372 initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
5375 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
5376 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
5379 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
5382 int SetCharTable( char *table, const char * map )
5383 /* [HGM] moved here from winboard.c because of its general usefulness */
5384 /* Basically a safe strcpy that uses the last character as King */
5386 int result = FALSE; int NrPieces;
5388 if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
5389 && NrPieces >= 12 && !(NrPieces&1)) {
5390 int i; /* [HGM] Accept even length from 12 to 34 */
5392 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
5393 for( i=0; i<NrPieces/2-1; i++ ) {
5395 table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
5397 table[(int) WhiteKing] = map[NrPieces/2-1];
5398 table[(int) BlackKing] = map[NrPieces-1];
5406 void Prelude(Board board)
5407 { // [HGM] superchess: random selection of exo-pieces
5408 int i, j, k; ChessSquare p;
5409 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
5411 GetPositionNumber(); // use FRC position number
5413 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
5414 SetCharTable(pieceToChar, appData.pieceToCharTable);
5415 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
5416 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
5419 j = seed%4; seed /= 4;
5420 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5421 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5422 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5423 j = seed%3 + (seed%3 >= j); seed /= 3;
5424 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5425 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5426 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5427 j = seed%3; seed /= 3;
5428 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5429 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5430 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5431 j = seed%2 + (seed%2 >= j); seed /= 2;
5432 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5433 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5434 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5435 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
5436 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
5437 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
5438 put(board, exoPieces[0], 0, 0, ANY);
5439 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
5443 InitPosition(redraw)
5446 ChessSquare (* pieces)[BOARD_FILES];
5447 int i, j, pawnRow, overrule,
5448 oldx = gameInfo.boardWidth,
5449 oldy = gameInfo.boardHeight,
5450 oldh = gameInfo.holdingsWidth;
5453 if(appData.icsActive) shuffleOpenings = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
5455 /* [AS] Initialize pv info list [HGM] and game status */
5457 for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
5458 pvInfoList[i].depth = 0;
5459 boards[i][EP_STATUS] = EP_NONE;
5460 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
5463 initialRulePlies = 0; /* 50-move counter start */
5465 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
5466 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
5470 /* [HGM] logic here is completely changed. In stead of full positions */
5471 /* the initialized data only consist of the two backranks. The switch */
5472 /* selects which one we will use, which is than copied to the Board */
5473 /* initialPosition, which for the rest is initialized by Pawns and */
5474 /* empty squares. This initial position is then copied to boards[0], */
5475 /* possibly after shuffling, so that it remains available. */
5477 gameInfo.holdingsWidth = 0; /* default board sizes */
5478 gameInfo.boardWidth = 8;
5479 gameInfo.boardHeight = 8;
5480 gameInfo.holdingsSize = 0;
5481 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
5482 for(i=0; i<BOARD_FILES-2; i++)
5483 initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
5484 initialPosition[EP_STATUS] = EP_NONE;
5485 SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
5486 if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
5487 SetCharTable(pieceNickName, appData.pieceNickNames);
5488 else SetCharTable(pieceNickName, "............");
5491 switch (gameInfo.variant) {
5492 case VariantFischeRandom:
5493 shuffleOpenings = TRUE;
5496 case VariantShatranj:
5497 pieces = ShatranjArray;
5498 nrCastlingRights = 0;
5499 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
5502 pieces = makrukArray;
5503 nrCastlingRights = 0;
5504 startedFromSetupPosition = TRUE;
5505 SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
5507 case VariantTwoKings:
5508 pieces = twoKingsArray;
5510 case VariantCapaRandom:
5511 shuffleOpenings = TRUE;
5512 case VariantCapablanca:
5513 pieces = CapablancaArray;
5514 gameInfo.boardWidth = 10;
5515 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5518 pieces = GothicArray;
5519 gameInfo.boardWidth = 10;
5520 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5523 SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
5524 gameInfo.holdingsSize = 7;
5527 pieces = JanusArray;
5528 gameInfo.boardWidth = 10;
5529 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
5530 nrCastlingRights = 6;
5531 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5532 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5533 initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
5534 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5535 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5536 initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
5539 pieces = FalconArray;
5540 gameInfo.boardWidth = 10;
5541 SetCharTable(pieceToChar, "PNBRQ.............FKpnbrq.............fk");
5543 case VariantXiangqi:
5544 pieces = XiangqiArray;
5545 gameInfo.boardWidth = 9;
5546 gameInfo.boardHeight = 10;
5547 nrCastlingRights = 0;
5548 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
5551 pieces = ShogiArray;
5552 gameInfo.boardWidth = 9;
5553 gameInfo.boardHeight = 9;
5554 gameInfo.holdingsSize = 7;
5555 nrCastlingRights = 0;
5556 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
5558 case VariantCourier:
5559 pieces = CourierArray;
5560 gameInfo.boardWidth = 12;
5561 nrCastlingRights = 0;
5562 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
5564 case VariantKnightmate:
5565 pieces = KnightmateArray;
5566 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
5568 case VariantSpartan:
5569 pieces = SpartanArray;
5570 SetCharTable(pieceToChar, "PNBRQ................K......lwg.....c...h..k");
5573 pieces = fairyArray;
5574 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
5577 pieces = GreatArray;
5578 gameInfo.boardWidth = 10;
5579 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
5580 gameInfo.holdingsSize = 8;
5584 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
5585 gameInfo.holdingsSize = 8;
5586 startedFromSetupPosition = TRUE;
5588 case VariantCrazyhouse:
5589 case VariantBughouse:
5591 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
5592 gameInfo.holdingsSize = 5;
5594 case VariantWildCastle:
5596 /* !!?shuffle with kings guaranteed to be on d or e file */
5597 shuffleOpenings = 1;
5599 case VariantNoCastle:
5601 nrCastlingRights = 0;
5602 /* !!?unconstrained back-rank shuffle */
5603 shuffleOpenings = 1;
5608 if(appData.NrFiles >= 0) {
5609 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
5610 gameInfo.boardWidth = appData.NrFiles;
5612 if(appData.NrRanks >= 0) {
5613 gameInfo.boardHeight = appData.NrRanks;
5615 if(appData.holdingsSize >= 0) {
5616 i = appData.holdingsSize;
5617 if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
5618 gameInfo.holdingsSize = i;
5620 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
5621 if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
5622 DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
5624 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
5625 if(pawnRow < 1) pawnRow = 1;
5626 if(gameInfo.variant == VariantMakruk) pawnRow = 2;
5628 /* User pieceToChar list overrules defaults */
5629 if(appData.pieceToCharTable != NULL)
5630 SetCharTable(pieceToChar, appData.pieceToCharTable);
5632 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
5634 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
5635 s = (ChessSquare) 0; /* account holding counts in guard band */
5636 for( i=0; i<BOARD_HEIGHT; i++ )
5637 initialPosition[i][j] = s;
5639 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
5640 initialPosition[0][j] = pieces[0][j-gameInfo.holdingsWidth];
5641 initialPosition[pawnRow][j] = WhitePawn;
5642 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
5643 if(gameInfo.variant == VariantXiangqi) {
5645 initialPosition[pawnRow][j] =
5646 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
5647 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
5648 initialPosition[2][j] = WhiteCannon;
5649 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
5653 initialPosition[BOARD_HEIGHT-1][j] = pieces[1][j-gameInfo.holdingsWidth];
5655 if( (gameInfo.variant == VariantShogi) && !overrule ) {
5658 initialPosition[1][j] = WhiteBishop;
5659 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
5661 initialPosition[1][j] = WhiteRook;
5662 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
5665 if( nrCastlingRights == -1) {
5666 /* [HGM] Build normal castling rights (must be done after board sizing!) */
5667 /* This sets default castling rights from none to normal corners */
5668 /* Variants with other castling rights must set them themselves above */
5669 nrCastlingRights = 6;
5671 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5672 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5673 initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
5674 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5675 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5676 initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
5679 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
5680 if(gameInfo.variant == VariantGreat) { // promotion commoners
5681 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
5682 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
5683 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
5684 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
5686 if( gameInfo.variant == VariantSChess ) {
5687 initialPosition[1][0] = BlackMarshall;
5688 initialPosition[2][0] = BlackAngel;
5689 initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
5690 initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
5691 initialPosition[1][1] = initialPosition[2][1] =
5692 initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
5694 if (appData.debugMode) {
5695 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
5697 if(shuffleOpenings) {
5698 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
5699 startedFromSetupPosition = TRUE;
5701 if(startedFromPositionFile) {
5702 /* [HGM] loadPos: use PositionFile for every new game */
5703 CopyBoard(initialPosition, filePosition);
5704 for(i=0; i<nrCastlingRights; i++)
5705 initialRights[i] = filePosition[CASTLING][i];
5706 startedFromSetupPosition = TRUE;
5709 CopyBoard(boards[0], initialPosition);
5711 if(oldx != gameInfo.boardWidth ||
5712 oldy != gameInfo.boardHeight ||
5713 oldv != gameInfo.variant ||
5714 oldh != gameInfo.holdingsWidth
5716 InitDrawingSizes(-2 ,0);
5718 oldv = gameInfo.variant;
5720 DrawPosition(TRUE, boards[currentMove]);
5724 SendBoard(cps, moveNum)
5725 ChessProgramState *cps;
5728 char message[MSG_SIZ];
5730 if (cps->useSetboard) {
5731 char* fen = PositionToFEN(moveNum, cps->fenOverride);
5732 snprintf(message, MSG_SIZ,"setboard %s\n", fen);
5733 SendToProgram(message, cps);
5739 /* Kludge to set black to move, avoiding the troublesome and now
5740 * deprecated "black" command.
5742 if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
5743 SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn ? "a2a3\n" : "black\n", cps);
5745 SendToProgram("edit\n", cps);
5746 SendToProgram("#\n", cps);
5747 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
5748 bp = &boards[moveNum][i][BOARD_LEFT];
5749 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
5750 if ((int) *bp < (int) BlackPawn) {
5751 snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp),
5753 if(message[0] == '+' || message[0] == '~') {
5754 snprintf(message, MSG_SIZ,"%c%c%c+\n",
5755 PieceToChar((ChessSquare)(DEMOTED *bp)),
5758 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
5759 message[1] = BOARD_RGHT - 1 - j + '1';
5760 message[2] = BOARD_HEIGHT - 1 - i + 'a';
5762 SendToProgram(message, cps);
5767 SendToProgram("c\n", cps);
5768 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
5769 bp = &boards[moveNum][i][BOARD_LEFT];
5770 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
5771 if (((int) *bp != (int) EmptySquare)
5772 && ((int) *bp >= (int) BlackPawn)) {
5773 snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
5775 if(message[0] == '+' || message[0] == '~') {
5776 snprintf(message, MSG_SIZ,"%c%c%c+\n",
5777 PieceToChar((ChessSquare)(DEMOTED *bp)),
5780 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
5781 message[1] = BOARD_RGHT - 1 - j + '1';
5782 message[2] = BOARD_HEIGHT - 1 - i + 'a';
5784 SendToProgram(message, cps);
5789 SendToProgram(".\n", cps);
5791 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
5795 DefaultPromoChoice(int white)
5798 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
5799 result = WhiteFerz; // no choice
5800 else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
5801 result= WhiteKing; // in Suicide Q is the last thing we want
5802 else if(gameInfo.variant == VariantSpartan)
5803 result = white ? WhiteQueen : WhiteAngel;
5804 else result = WhiteQueen;
5805 if(!white) result = WHITE_TO_BLACK result;
5809 static int autoQueen; // [HGM] oneclick
5812 HasPromotionChoice(int fromX, int fromY, int toX, int toY, char *promoChoice)
5814 /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
5815 /* [HGM] add Shogi promotions */
5816 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
5821 if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
5822 if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
5824 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
5825 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
5828 piece = boards[currentMove][fromY][fromX];
5829 if(gameInfo.variant == VariantShogi) {
5830 promotionZoneSize = BOARD_HEIGHT/3;
5831 highestPromotingPiece = (int)WhiteFerz;
5832 } else if(gameInfo.variant == VariantMakruk) {
5833 promotionZoneSize = 3;
5836 // Treat Lance as Pawn when it is not representing Amazon
5837 if(gameInfo.variant != VariantSuper) {
5838 if(piece == WhiteLance) piece = WhitePawn; else
5839 if(piece == BlackLance) piece = BlackPawn;
5842 // next weed out all moves that do not touch the promotion zone at all
5843 if((int)piece >= BlackPawn) {
5844 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
5846 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
5848 if( toY < BOARD_HEIGHT - promotionZoneSize &&
5849 fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
5852 if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
5854 // weed out mandatory Shogi promotions
5855 if(gameInfo.variant == VariantShogi) {
5856 if(piece >= BlackPawn) {
5857 if(toY == 0 && piece == BlackPawn ||
5858 toY == 0 && piece == BlackQueen ||
5859 toY <= 1 && piece == BlackKnight) {
5864 if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
5865 toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
5866 toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
5873 // weed out obviously illegal Pawn moves
5874 if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
5875 if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
5876 if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
5877 if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
5878 if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
5879 // note we are not allowed to test for valid (non-)capture, due to premove
5882 // we either have a choice what to promote to, or (in Shogi) whether to promote
5883 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk) {
5884 *promoChoice = PieceToChar(BlackFerz); // no choice
5887 // no sense asking what we must promote to if it is going to explode...
5888 if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
5889 *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
5892 // give caller the default choice even if we will not make it
5893 *promoChoice = ToLower(PieceToChar(defaultPromoChoice));
5894 if(gameInfo.variant == VariantShogi) *promoChoice = '+';
5895 if(appData.sweepSelect && gameInfo.variant != VariantGreat
5896 && gameInfo.variant != VariantShogi
5897 && gameInfo.variant != VariantSuper) return FALSE;
5898 if(autoQueen) return FALSE; // predetermined
5900 // suppress promotion popup on illegal moves that are not premoves
5901 premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
5902 gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
5903 if(appData.testLegality && !premove) {
5904 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
5905 fromY, fromX, toY, toX, gameInfo.variant == VariantShogi ? '+' : NULLCHAR);
5906 if(moveType != WhitePromotion && moveType != BlackPromotion)
5914 InPalace(row, column)
5916 { /* [HGM] for Xiangqi */
5917 if( (row < 3 || row > BOARD_HEIGHT-4) &&
5918 column < (BOARD_WIDTH + 4)/2 &&
5919 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
5924 PieceForSquare (x, y)
5928 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
5931 return boards[currentMove][y][x];
5935 OKToStartUserMove(x, y)
5938 ChessSquare from_piece;
5941 if (matchMode) return FALSE;
5942 if (gameMode == EditPosition) return TRUE;
5944 if (x >= 0 && y >= 0)
5945 from_piece = boards[currentMove][y][x];
5947 from_piece = EmptySquare;
5949 if (from_piece == EmptySquare) return FALSE;
5951 white_piece = (int)from_piece >= (int)WhitePawn &&
5952 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
5955 case PlayFromGameFile:
5957 case TwoMachinesPlay:
5965 case MachinePlaysWhite:
5966 case IcsPlayingBlack:
5967 if (appData.zippyPlay) return FALSE;
5969 DisplayMoveError(_("You are playing Black"));
5974 case MachinePlaysBlack:
5975 case IcsPlayingWhite:
5976 if (appData.zippyPlay) return FALSE;
5978 DisplayMoveError(_("You are playing White"));
5984 if (!white_piece && WhiteOnMove(currentMove)) {
5985 DisplayMoveError(_("It is White's turn"));
5988 if (white_piece && !WhiteOnMove(currentMove)) {
5989 DisplayMoveError(_("It is Black's turn"));
5992 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
5993 /* Editing correspondence game history */
5994 /* Could disallow this or prompt for confirmation */
5999 case BeginningOfGame:
6000 if (appData.icsActive) return FALSE;
6001 if (!appData.noChessProgram) {
6003 DisplayMoveError(_("You are playing White"));
6010 if (!white_piece && WhiteOnMove(currentMove)) {
6011 DisplayMoveError(_("It is White's turn"));
6014 if (white_piece && !WhiteOnMove(currentMove)) {
6015 DisplayMoveError(_("It is Black's turn"));
6024 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
6025 && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
6026 && gameMode != AnalyzeFile && gameMode != Training) {
6027 DisplayMoveError(_("Displayed position is not current"));
6034 OnlyMove(int *x, int *y, Boolean captures) {
6035 DisambiguateClosure cl;
6036 if (appData.zippyPlay) return FALSE;
6038 case MachinePlaysBlack:
6039 case IcsPlayingWhite:
6040 case BeginningOfGame:
6041 if(!WhiteOnMove(currentMove)) return FALSE;
6043 case MachinePlaysWhite:
6044 case IcsPlayingBlack:
6045 if(WhiteOnMove(currentMove)) return FALSE;
6052 cl.pieceIn = EmptySquare;
6057 cl.promoCharIn = NULLCHAR;
6058 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6059 if( cl.kind == NormalMove ||
6060 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6061 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6062 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6069 if(cl.kind != ImpossibleMove) return FALSE;
6070 cl.pieceIn = EmptySquare;
6075 cl.promoCharIn = NULLCHAR;
6076 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6077 if( cl.kind == NormalMove ||
6078 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6079 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6080 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6085 autoQueen = TRUE; // act as if autoQueen on when we click to-square
6091 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
6092 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
6093 int lastLoadGameUseList = FALSE;
6094 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
6095 ChessMove lastLoadGameStart = EndOfFile;
6098 UserMoveEvent(fromX, fromY, toX, toY, promoChar)
6099 int fromX, fromY, toX, toY;
6103 ChessSquare pdown, pup;
6105 /* Check if the user is playing in turn. This is complicated because we
6106 let the user "pick up" a piece before it is his turn. So the piece he
6107 tried to pick up may have been captured by the time he puts it down!
6108 Therefore we use the color the user is supposed to be playing in this
6109 test, not the color of the piece that is currently on the starting
6110 square---except in EditGame mode, where the user is playing both
6111 sides; fortunately there the capture race can't happen. (It can
6112 now happen in IcsExamining mode, but that's just too bad. The user
6113 will get a somewhat confusing message in that case.)
6117 case PlayFromGameFile:
6119 case TwoMachinesPlay:
6123 /* We switched into a game mode where moves are not accepted,
6124 perhaps while the mouse button was down. */
6127 case MachinePlaysWhite:
6128 /* User is moving for Black */
6129 if (WhiteOnMove(currentMove)) {
6130 DisplayMoveError(_("It is White's turn"));
6135 case MachinePlaysBlack:
6136 /* User is moving for White */
6137 if (!WhiteOnMove(currentMove)) {
6138 DisplayMoveError(_("It is Black's turn"));
6145 case BeginningOfGame:
6148 if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
6149 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
6150 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
6151 /* User is moving for Black */
6152 if (WhiteOnMove(currentMove)) {
6153 DisplayMoveError(_("It is White's turn"));
6157 /* User is moving for White */
6158 if (!WhiteOnMove(currentMove)) {
6159 DisplayMoveError(_("It is Black's turn"));
6165 case IcsPlayingBlack:
6166 /* User is moving for Black */
6167 if (WhiteOnMove(currentMove)) {
6168 if (!appData.premove) {
6169 DisplayMoveError(_("It is White's turn"));
6170 } else if (toX >= 0 && toY >= 0) {
6173 premoveFromX = fromX;
6174 premoveFromY = fromY;
6175 premovePromoChar = promoChar;
6177 if (appData.debugMode)
6178 fprintf(debugFP, "Got premove: fromX %d,"
6179 "fromY %d, toX %d, toY %d\n",
6180 fromX, fromY, toX, toY);
6186 case IcsPlayingWhite:
6187 /* User is moving for White */
6188 if (!WhiteOnMove(currentMove)) {
6189 if (!appData.premove) {
6190 DisplayMoveError(_("It is Black's turn"));
6191 } else if (toX >= 0 && toY >= 0) {
6194 premoveFromX = fromX;
6195 premoveFromY = fromY;
6196 premovePromoChar = promoChar;
6198 if (appData.debugMode)
6199 fprintf(debugFP, "Got premove: fromX %d,"
6200 "fromY %d, toX %d, toY %d\n",
6201 fromX, fromY, toX, toY);
6211 /* EditPosition, empty square, or different color piece;
6212 click-click move is possible */
6213 if (toX == -2 || toY == -2) {
6214 boards[0][fromY][fromX] = EmptySquare;
6215 DrawPosition(FALSE, boards[currentMove]);
6217 } else if (toX >= 0 && toY >= 0) {
6218 boards[0][toY][toX] = boards[0][fromY][fromX];
6219 if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
6220 if(boards[0][fromY][0] != EmptySquare) {
6221 if(boards[0][fromY][1]) boards[0][fromY][1]--;
6222 if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
6225 if(fromX == BOARD_RGHT+1) {
6226 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
6227 if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
6228 if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
6231 boards[0][fromY][fromX] = EmptySquare;
6232 DrawPosition(FALSE, boards[currentMove]);
6238 if(toX < 0 || toY < 0) return;
6239 pdown = boards[currentMove][fromY][fromX];
6240 pup = boards[currentMove][toY][toX];
6242 /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
6243 if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
6244 if( pup != EmptySquare ) return;
6245 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
6246 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
6247 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
6248 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
6249 if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
6250 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
6251 while(PieceToChar(fromX) == '.' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
6255 /* [HGM] always test for legality, to get promotion info */
6256 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6257 fromY, fromX, toY, toX, promoChar);
6258 /* [HGM] but possibly ignore an IllegalMove result */
6259 if (appData.testLegality) {
6260 if (moveType == IllegalMove || moveType == ImpossibleMove) {
6261 DisplayMoveError(_("Illegal move"));
6266 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
6269 /* Common tail of UserMoveEvent and DropMenuEvent */
6271 FinishMove(moveType, fromX, fromY, toX, toY, promoChar)
6273 int fromX, fromY, toX, toY;
6274 /*char*/int promoChar;
6278 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) && promoChar != NULLCHAR) {
6279 // [HGM] superchess: suppress promotions to non-available piece
6280 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
6281 if(WhiteOnMove(currentMove)) {
6282 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
6284 if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
6288 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
6289 move type in caller when we know the move is a legal promotion */
6290 if(moveType == NormalMove && promoChar)
6291 moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
6293 /* [HGM] <popupFix> The following if has been moved here from
6294 UserMoveEvent(). Because it seemed to belong here (why not allow
6295 piece drops in training games?), and because it can only be
6296 performed after it is known to what we promote. */
6297 if (gameMode == Training) {
6298 /* compare the move played on the board to the next move in the
6299 * game. If they match, display the move and the opponent's response.
6300 * If they don't match, display an error message.
6304 CopyBoard(testBoard, boards[currentMove]);
6305 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
6307 if (CompareBoards(testBoard, boards[currentMove+1])) {
6308 ForwardInner(currentMove+1);
6310 /* Autoplay the opponent's response.
6311 * if appData.animate was TRUE when Training mode was entered,
6312 * the response will be animated.
6314 saveAnimate = appData.animate;
6315 appData.animate = animateTraining;
6316 ForwardInner(currentMove+1);
6317 appData.animate = saveAnimate;
6319 /* check for the end of the game */
6320 if (currentMove >= forwardMostMove) {
6321 gameMode = PlayFromGameFile;
6323 SetTrainingModeOff();
6324 DisplayInformation(_("End of game"));
6327 DisplayError(_("Incorrect move"), 0);
6332 /* Ok, now we know that the move is good, so we can kill
6333 the previous line in Analysis Mode */
6334 if ((gameMode == AnalyzeMode || gameMode == EditGame)
6335 && currentMove < forwardMostMove) {
6336 if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
6337 else forwardMostMove = currentMove;
6340 /* If we need the chess program but it's dead, restart it */
6341 ResurrectChessProgram();
6343 /* A user move restarts a paused game*/
6347 thinkOutput[0] = NULLCHAR;
6349 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
6351 if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
6352 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6356 if (gameMode == BeginningOfGame) {
6357 if (appData.noChessProgram) {
6358 gameMode = EditGame;
6362 gameMode = MachinePlaysBlack;
6365 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
6367 if (first.sendName) {
6368 snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
6369 SendToProgram(buf, &first);
6376 /* Relay move to ICS or chess engine */
6377 if (appData.icsActive) {
6378 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
6379 gameMode == IcsExamining) {
6380 if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
6381 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
6383 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6385 // also send plain move, in case ICS does not understand atomic claims
6386 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6390 if (first.sendTime && (gameMode == BeginningOfGame ||
6391 gameMode == MachinePlaysWhite ||
6392 gameMode == MachinePlaysBlack)) {
6393 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
6395 if (gameMode != EditGame && gameMode != PlayFromGameFile) {
6396 // [HGM] book: if program might be playing, let it use book
6397 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
6398 first.maybeThinking = TRUE;
6399 } else SendMoveToProgram(forwardMostMove-1, &first);
6400 if (currentMove == cmailOldMove + 1) {
6401 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
6405 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6409 if(appData.testLegality)
6410 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
6416 if (WhiteOnMove(currentMove)) {
6417 GameEnds(BlackWins, "Black mates", GE_PLAYER);
6419 GameEnds(WhiteWins, "White mates", GE_PLAYER);
6423 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
6428 case MachinePlaysBlack:
6429 case MachinePlaysWhite:
6430 /* disable certain menu options while machine is thinking */
6431 SetMachineThinkingEnables();
6438 userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
6439 promoDefaultAltered = FALSE; // [HGM] fall back on default choice
6441 if(bookHit) { // [HGM] book: simulate book reply
6442 static char bookMove[MSG_SIZ]; // a bit generous?
6444 programStats.nodes = programStats.depth = programStats.time =
6445 programStats.score = programStats.got_only_move = 0;
6446 sprintf(programStats.movelist, "%s (xbook)", bookHit);
6448 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
6449 strcat(bookMove, bookHit);
6450 HandleMachineMove(bookMove, &first);
6456 Mark(board, flags, kind, rf, ff, rt, ft, closure)
6463 typedef char Markers[BOARD_RANKS][BOARD_FILES];
6464 Markers *m = (Markers *) closure;
6465 if(rf == fromY && ff == fromX)
6466 (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
6467 || kind == WhiteCapturesEnPassant
6468 || kind == BlackCapturesEnPassant);
6469 else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3;
6473 MarkTargetSquares(int clear)
6476 if(!appData.markers || !appData.highlightDragging ||
6477 !appData.testLegality || gameMode == EditPosition) return;
6479 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) marker[y][x] = 0;
6482 GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker);
6483 if(PosFlags(0) & F_MANDATORY_CAPTURE) {
6484 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
6486 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
6489 DrawPosition(TRUE, NULL);
6493 Explode(Board board, int fromX, int fromY, int toX, int toY)
6495 if(gameInfo.variant == VariantAtomic &&
6496 (board[toY][toX] != EmptySquare || // capture?
6497 toX != fromX && (board[fromY][fromX] == WhitePawn || // e.p. ?
6498 board[fromY][fromX] == BlackPawn )
6500 AnimateAtomicCapture(board, fromX, fromY, toX, toY);
6506 ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
6508 int CanPromote(ChessSquare piece, int y)
6510 if(gameMode == EditPosition) return FALSE; // no promotions when editing position
6511 // some variants have fixed promotion piece, no promotion at all, or another selection mechanism
6512 if(gameInfo.variant == VariantShogi || gameInfo.variant == VariantXiangqi ||
6513 gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat ||
6514 gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6515 gameInfo.variant == VariantMakruk) return FALSE;
6516 return (piece == BlackPawn && y == 1 ||
6517 piece == WhitePawn && y == BOARD_HEIGHT-2 ||
6518 piece == BlackLance && y == 1 ||
6519 piece == WhiteLance && y == BOARD_HEIGHT-2 );
6522 void LeftClick(ClickType clickType, int xPix, int yPix)
6525 Boolean saveAnimate;
6526 static int second = 0, promotionChoice = 0, clearFlag = 0;
6527 char promoChoice = NULLCHAR;
6530 if(appData.seekGraph && appData.icsActive && loggedOn &&
6531 (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
6532 SeekGraphClick(clickType, xPix, yPix, 0);
6536 if (clickType == Press) ErrorPopDown();
6537 MarkTargetSquares(1);
6539 x = EventToSquare(xPix, BOARD_WIDTH);
6540 y = EventToSquare(yPix, BOARD_HEIGHT);
6541 if (!flipView && y >= 0) {
6542 y = BOARD_HEIGHT - 1 - y;
6544 if (flipView && x >= 0) {
6545 x = BOARD_WIDTH - 1 - x;
6548 if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
6549 defaultPromoChoice = promoSweep;
6550 promoSweep = EmptySquare; // terminate sweep
6551 promoDefaultAltered = TRUE;
6552 if(!selectFlag) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
6555 if(promotionChoice) { // we are waiting for a click to indicate promotion piece
6556 if(clickType == Release) return; // ignore upclick of click-click destination
6557 promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
6558 if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
6559 if(gameInfo.holdingsWidth &&
6560 (WhiteOnMove(currentMove)
6561 ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y > 0
6562 : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT-1) ) {
6563 // click in right holdings, for determining promotion piece
6564 ChessSquare p = boards[currentMove][y][x];
6565 if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
6566 if(p != EmptySquare) {
6567 FinishMove(NormalMove, fromX, fromY, toX, toY, ToLower(PieceToChar(p)));
6572 DrawPosition(FALSE, boards[currentMove]);
6576 /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
6577 if(clickType == Press
6578 && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
6579 || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
6580 || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
6583 if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered)
6584 fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
6586 if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
6587 int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
6588 gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
6589 defaultPromoChoice = DefaultPromoChoice(side);
6592 autoQueen = appData.alwaysPromoteToQueen;
6596 gatingPiece = EmptySquare;
6597 if (clickType != Press) {
6598 if(dragging) { // [HGM] from-square must have been reset due to game end since last press
6599 DragPieceEnd(xPix, yPix); dragging = 0;
6600 DrawPosition(FALSE, NULL);
6604 fromX = x; fromY = y;
6605 if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
6606 // even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
6607 appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
6609 if (OKToStartUserMove(fromX, fromY)) {
6611 MarkTargetSquares(0);
6612 DragPieceBegin(xPix, yPix); dragging = 1;
6613 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
6614 promoSweep = defaultPromoChoice;
6615 selectFlag = 0; lastX = xPix; lastY = yPix;
6616 Sweep(0); // Pawn that is going to promote: preview promotion piece
6617 DisplayMessage("", _("Pull pawn backwards to under-promote"));
6619 if (appData.highlightDragging) {
6620 SetHighlights(fromX, fromY, -1, -1);
6622 } else fromX = fromY = -1;
6628 if (clickType == Press && gameMode != EditPosition) {
6633 // ignore off-board to clicks
6634 if(y < 0 || x < 0) return;
6636 /* Check if clicking again on the same color piece */
6637 fromP = boards[currentMove][fromY][fromX];
6638 toP = boards[currentMove][y][x];
6639 frc = gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom || gameInfo.variant == VariantSChess;
6640 if ((WhitePawn <= fromP && fromP <= WhiteKing &&
6641 WhitePawn <= toP && toP <= WhiteKing &&
6642 !(fromP == WhiteKing && toP == WhiteRook && frc) &&
6643 !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
6644 (BlackPawn <= fromP && fromP <= BlackKing &&
6645 BlackPawn <= toP && toP <= BlackKing &&
6646 !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
6647 !(fromP == BlackKing && toP == BlackRook && frc))) {
6648 /* Clicked again on same color piece -- changed his mind */
6649 second = (x == fromX && y == fromY);
6650 promoDefaultAltered = FALSE;
6651 if(!second || appData.oneClick && !OnlyMove(&x, &y, TRUE)) {
6652 if (appData.highlightDragging) {
6653 SetHighlights(x, y, -1, -1);
6657 if (OKToStartUserMove(x, y)) {
6658 if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
6659 (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
6660 y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
6661 gatingPiece = boards[currentMove][fromY][fromX];
6662 else gatingPiece = EmptySquare;
6664 fromY = y; dragging = 1;
6665 MarkTargetSquares(0);
6666 DragPieceBegin(xPix, yPix);
6667 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
6668 promoSweep = defaultPromoChoice;
6669 selectFlag = 0; lastX = xPix; lastY = yPix;
6670 Sweep(0); // Pawn that is going to promote: preview promotion piece
6674 if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
6677 // ignore clicks on holdings
6678 if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
6681 if (clickType == Release && x == fromX && y == fromY) {
6682 DragPieceEnd(xPix, yPix); dragging = 0;
6684 // a deferred attempt to click-click move an empty square on top of a piece
6685 boards[currentMove][y][x] = EmptySquare;
6687 DrawPosition(FALSE, boards[currentMove]);
6688 fromX = fromY = -1; clearFlag = 0;
6691 if (appData.animateDragging) {
6692 /* Undo animation damage if any */
6693 DrawPosition(FALSE, NULL);
6696 /* Second up/down in same square; just abort move */
6699 gatingPiece = EmptySquare;
6702 ClearPremoveHighlights();
6704 /* First upclick in same square; start click-click mode */
6705 SetHighlights(x, y, -1, -1);
6712 /* we now have a different from- and (possibly off-board) to-square */
6713 /* Completed move */
6716 saveAnimate = appData.animate;
6717 if (clickType == Press) {
6718 if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
6719 // must be Edit Position mode with empty-square selected
6720 fromX = x; fromY = y; DragPieceBegin(xPix, yPix); dragging = 1; // consider this a new attempt to drag
6721 if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
6724 /* Finish clickclick move */
6725 if (appData.animate || appData.highlightLastMove) {
6726 SetHighlights(fromX, fromY, toX, toY);
6731 /* Finish drag move */
6732 if (appData.highlightLastMove) {
6733 SetHighlights(fromX, fromY, toX, toY);
6737 DragPieceEnd(xPix, yPix); dragging = 0;
6738 /* Don't animate move and drag both */
6739 appData.animate = FALSE;
6742 // moves into holding are invalid for now (except in EditPosition, adapting to-square)
6743 if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
6744 ChessSquare piece = boards[currentMove][fromY][fromX];
6745 if(gameMode == EditPosition && piece != EmptySquare &&
6746 fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
6749 if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
6750 n = PieceToNumber(piece - (int)BlackPawn);
6751 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
6752 boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
6753 boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
6755 if(x == BOARD_RGHT+1 && piece < BlackPawn) {
6756 n = PieceToNumber(piece);
6757 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
6758 boards[currentMove][n][BOARD_WIDTH-1] = piece;
6759 boards[currentMove][n][BOARD_WIDTH-2]++;
6761 boards[currentMove][fromY][fromX] = EmptySquare;
6765 DrawPosition(TRUE, boards[currentMove]);
6769 // off-board moves should not be highlighted
6770 if(x < 0 || y < 0) ClearHighlights();
6772 if(gatingPiece != EmptySquare) promoChoice = ToLower(PieceToChar(gatingPiece));
6774 if (HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice)) {
6775 SetHighlights(fromX, fromY, toX, toY);
6776 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
6777 // [HGM] super: promotion to captured piece selected from holdings
6778 ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
6779 promotionChoice = TRUE;
6780 // kludge follows to temporarily execute move on display, without promoting yet
6781 boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
6782 boards[currentMove][toY][toX] = p;
6783 DrawPosition(FALSE, boards[currentMove]);
6784 boards[currentMove][fromY][fromX] = p; // take back, but display stays
6785 boards[currentMove][toY][toX] = q;
6786 DisplayMessage("Click in holdings to choose piece", "");
6791 int oldMove = currentMove;
6792 UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
6793 if (!appData.highlightLastMove || gotPremove) ClearHighlights();
6794 if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
6795 if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
6796 Explode(boards[currentMove-1], fromX, fromY, toX, toY))
6797 DrawPosition(TRUE, boards[currentMove]);
6800 appData.animate = saveAnimate;
6801 if (appData.animate || appData.animateDragging) {
6802 /* Undo animation damage if needed */
6803 DrawPosition(FALSE, NULL);
6807 int RightClick(ClickType action, int x, int y, int *fromX, int *fromY)
6808 { // front-end-free part taken out of PieceMenuPopup
6809 int whichMenu; int xSqr, ySqr;
6811 if(seekGraphUp) { // [HGM] seekgraph
6812 if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
6813 if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
6817 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
6818 && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
6819 if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
6820 if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
6821 if(action == Press) {
6822 originalFlip = flipView;
6823 flipView = !flipView; // temporarily flip board to see game from partners perspective
6824 DrawPosition(TRUE, partnerBoard);
6825 DisplayMessage(partnerStatus, "");
6827 } else if(action == Release) {
6828 flipView = originalFlip;
6829 DrawPosition(TRUE, boards[currentMove]);
6835 xSqr = EventToSquare(x, BOARD_WIDTH);
6836 ySqr = EventToSquare(y, BOARD_HEIGHT);
6837 if (action == Release) {
6838 if(pieceSweep != EmptySquare) {
6839 EditPositionMenuEvent(pieceSweep, toX, toY);
6840 pieceSweep = EmptySquare;
6841 } else UnLoadPV(); // [HGM] pv
6843 if (action != Press) return -2; // return code to be ignored
6846 if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
\r
6848 if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
\r
6849 if (xSqr < 0 || ySqr < 0) return -1;
6850 if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
6851 pieceSweep = shiftKey ? BlackPawn : WhitePawn; // [HGM] sweep: prepare selecting piece by mouse sweep
6852 toX = xSqr; toY = ySqr; lastX = x, lastY = y;
6853 if(flipView) toX = BOARD_WIDTH - 1 - toX; else toY = BOARD_HEIGHT - 1 - toY;
6857 if(!appData.icsEngineAnalyze) return -1;
6858 case IcsPlayingWhite:
6859 case IcsPlayingBlack:
6860 if(!appData.zippyPlay) goto noZip;
6863 case MachinePlaysWhite:
6864 case MachinePlaysBlack:
6865 case TwoMachinesPlay: // [HGM] pv: use for showing PV
6866 if (!appData.dropMenu) {
6868 return 2; // flag front-end to grab mouse events
6870 if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
6871 gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
6874 if (xSqr < 0 || ySqr < 0) return -1;
6875 if (!appData.dropMenu || appData.testLegality &&
6876 gameInfo.variant != VariantBughouse &&
6877 gameInfo.variant != VariantCrazyhouse) return -1;
6878 whichMenu = 1; // drop menu
6884 if (((*fromX = xSqr) < 0) ||
6885 ((*fromY = ySqr) < 0)) {
6886 *fromX = *fromY = -1;
6890 *fromX = BOARD_WIDTH - 1 - *fromX;
6892 *fromY = BOARD_HEIGHT - 1 - *fromY;
6897 void SendProgramStatsToFrontend( ChessProgramState * cps, ChessProgramStats * cpstats )
6899 // char * hint = lastHint;
6900 FrontEndProgramStats stats;
6902 stats.which = cps == &first ? 0 : 1;
6903 stats.depth = cpstats->depth;
6904 stats.nodes = cpstats->nodes;
6905 stats.score = cpstats->score;
6906 stats.time = cpstats->time;
6907 stats.pv = cpstats->movelist;
6908 stats.hint = lastHint;
6909 stats.an_move_index = 0;
6910 stats.an_move_count = 0;
6912 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
6913 stats.hint = cpstats->move_name;
6914 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
6915 stats.an_move_count = cpstats->nr_moves;
6918 if(stats.pv && stats.pv[0]) safeStrCpy(lastPV[stats.which], stats.pv, sizeof(lastPV[stats.which])/sizeof(lastPV[stats.which][0])); // [HGM] pv: remember last PV of each
6920 SetProgramStats( &stats );
6924 Count(Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
6925 { // count all piece types
6927 *nB = *nW = *wStale = *bStale = *bishopColor = 0;
6928 for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
6929 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
6932 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
6933 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
6934 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
6935 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
6936 p == BlackBishop || p == BlackFerz || p == BlackAlfil )
6937 *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
6942 SufficientDefence(int pCnt[], int side, int nMine, int nHis)
6944 int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
6945 int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
6947 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
6948 if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
6949 if(myPawns == 2 && nMine == 3) // KPP
6950 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
6951 if(myPawns == 1 && nMine == 2) // KP
6952 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
6953 if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
6954 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
6955 if(myPawns) return FALSE;
6956 if(pCnt[WhiteRook+side])
6957 return pCnt[BlackRook-side] ||
6958 pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
6959 pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
6960 pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
6961 if(pCnt[WhiteCannon+side]) {
6962 if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
6963 return majorDefense || pCnt[BlackAlfil-side] >= 2;
6965 if(pCnt[WhiteKnight+side])
6966 return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
6971 MatingPotential(int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
6973 VariantClass v = gameInfo.variant;
6975 if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
6976 if(v == VariantShatranj) return TRUE; // always winnable through baring
6977 if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
6978 if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
6980 if(v == VariantXiangqi) {
6981 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
6983 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
6984 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
6985 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
6986 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
6987 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
6988 if(stale) // we have at least one last-rank P plus perhaps C
6989 return majors // KPKX
6990 || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
6992 return pCnt[WhiteFerz+side] // KCAK
6993 || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
6994 || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
6995 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
6997 } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
6998 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
7000 if(nMine == 1) return FALSE; // bare King
7001 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
7002 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
7003 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
7004 // by now we have King + 1 piece (or multiple Bishops on the same color)
7005 if(pCnt[WhiteKnight+side])
7006 return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
7007 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
7008 || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
7010 return (pCnt[BlackKnight-side]); // KBKN, KFKN
7011 if(pCnt[WhiteAlfil+side])
7012 return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
7013 if(pCnt[WhiteWazir+side])
7014 return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
7021 Adjudicate(ChessProgramState *cps)
7022 { // [HGM] some adjudications useful with buggy engines
7023 // [HGM] adjudicate: made into separate routine, which now can be called after every move
7024 // In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
7025 // Actually ending the game is now based on the additional internal condition canAdjudicate.
7026 // Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
7027 int k, count = 0; static int bare = 1;
7028 ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
7029 Boolean canAdjudicate = !appData.icsActive;
7031 // most tests only when we understand the game, i.e. legality-checking on
7032 if( appData.testLegality )
7033 { /* [HGM] Some more adjudications for obstinate engines */
7034 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+1], i;
7035 static int moveCount = 6;
7037 char *reason = NULL;
7039 /* Count what is on board. */
7040 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
7042 /* Some material-based adjudications that have to be made before stalemate test */
7043 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
7044 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
7045 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
7046 if(canAdjudicate && appData.checkMates) {
7048 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7049 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
7050 "Xboard adjudication: King destroyed", GE_XBOARD );
7055 /* Bare King in Shatranj (loses) or Losers (wins) */
7056 if( nrW == 1 || nrB == 1) {
7057 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
7058 boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
7059 if(canAdjudicate && appData.checkMates) {
7061 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
7062 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7063 "Xboard adjudication: Bare king", GE_XBOARD );
7067 if( gameInfo.variant == VariantShatranj && --bare < 0)
7069 boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
7070 if(canAdjudicate && appData.checkMates) {
7071 /* but only adjudicate if adjudication enabled */
7073 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7074 GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
7075 "Xboard adjudication: Bare king", GE_XBOARD );
7082 // don't wait for engine to announce game end if we can judge ourselves
7083 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
7085 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
7086 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
7087 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
7088 if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
7091 reason = "Xboard adjudication: 3rd check";
7092 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
7102 reason = "Xboard adjudication: Stalemate";
7103 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
7104 boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
7105 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
7106 boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
7107 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
7108 boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
7109 ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
7110 EP_CHECKMATE : EP_WINS);
7111 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi)
7112 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
7116 reason = "Xboard adjudication: Checkmate";
7117 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
7121 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
7123 result = GameIsDrawn; break;
7125 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
7127 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
7131 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
7133 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7134 GameEnds( result, reason, GE_XBOARD );
7138 /* Next absolutely insufficient mating material. */
7139 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
7140 !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
7141 { /* includes KBK, KNK, KK of KBKB with like Bishops */
7143 /* always flag draws, for judging claims */
7144 boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
7146 if(canAdjudicate && appData.materialDraws) {
7147 /* but only adjudicate them if adjudication enabled */
7148 if(engineOpponent) {
7149 SendToProgram("force\n", engineOpponent); // suppress reply
7150 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
7152 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
7157 /* Then some trivial draws (only adjudicate, cannot be claimed) */
7158 if(gameInfo.variant == VariantXiangqi ?
7159 SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
7161 ( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
7162 || nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
7163 || nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
7164 || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
7166 if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
7167 { /* if the first 3 moves do not show a tactical win, declare draw */
7168 if(engineOpponent) {
7169 SendToProgram("force\n", engineOpponent); // suppress reply
7170 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7172 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
7175 } else moveCount = 6;
7177 if (appData.debugMode) { int i;
7178 fprintf(debugFP, "repeat test fmm=%d bmm=%d ep=%d, reps=%d\n",
7179 forwardMostMove, backwardMostMove, boards[backwardMostMove][EP_STATUS],
7180 appData.drawRepeats);
7181 for( i=forwardMostMove; i>=backwardMostMove; i-- )
7182 fprintf(debugFP, "%d ep=%d\n", i, (signed char)boards[i][EP_STATUS]);
7186 // Repetition draws and 50-move rule can be applied independently of legality testing
7188 /* Check for rep-draws */
7190 for(k = forwardMostMove-2;
7191 k>=backwardMostMove && k>=forwardMostMove-100 &&
7192 (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
7193 (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE;
7196 if(CompareBoards(boards[k], boards[forwardMostMove])) {
7197 /* compare castling rights */
7198 if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
7199 (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
7200 rights++; /* King lost rights, while rook still had them */
7201 if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
7202 if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
7203 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
7204 rights++; /* but at least one rook lost them */
7206 if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
7207 (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
7209 if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
7210 if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
7211 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
7214 if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
7215 && appData.drawRepeats > 1) {
7216 /* adjudicate after user-specified nr of repeats */
7217 int result = GameIsDrawn;
7218 char *details = "XBoard adjudication: repetition draw";
7219 if(gameInfo.variant == VariantXiangqi && appData.testLegality) {
7220 // [HGM] xiangqi: check for forbidden perpetuals
7221 int m, ourPerpetual = 1, hisPerpetual = 1;
7222 for(m=forwardMostMove; m>k; m-=2) {
7223 if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
7224 ourPerpetual = 0; // the current mover did not always check
7225 if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
7226 hisPerpetual = 0; // the opponent did not always check
7228 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
7229 ourPerpetual, hisPerpetual);
7230 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
7231 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7232 details = "Xboard adjudication: perpetual checking";
7234 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
7235 break; // (or we would have caught him before). Abort repetition-checking loop.
7237 // Now check for perpetual chases
7238 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
7239 hisPerpetual = PerpetualChase(k, forwardMostMove);
7240 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
7241 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
7242 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7243 details = "Xboard adjudication: perpetual chasing";
7245 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
7246 break; // Abort repetition-checking loop.
7248 // if neither of us is checking or chasing all the time, or both are, it is draw
7250 if(engineOpponent) {
7251 SendToProgram("force\n", engineOpponent); // suppress reply
7252 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7254 GameEnds( result, details, GE_XBOARD );
7257 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
7258 boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
7262 /* Now we test for 50-move draws. Determine ply count */
7263 count = forwardMostMove;
7264 /* look for last irreversble move */
7265 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
7267 /* if we hit starting position, add initial plies */
7268 if( count == backwardMostMove )
7269 count -= initialRulePlies;
7270 count = forwardMostMove - count;
7271 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
7272 // adjust reversible move counter for checks in Xiangqi
7273 int i = forwardMostMove - count, inCheck = 0, lastCheck;
7274 if(i < backwardMostMove) i = backwardMostMove;
7275 while(i <= forwardMostMove) {
7276 lastCheck = inCheck; // check evasion does not count
7277 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
7278 if(inCheck || lastCheck) count--; // check does not count
7283 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
7284 /* this is used to judge if draw claims are legal */
7285 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
7286 if(engineOpponent) {
7287 SendToProgram("force\n", engineOpponent); // suppress reply
7288 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7290 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
7294 /* if draw offer is pending, treat it as a draw claim
7295 * when draw condition present, to allow engines a way to
7296 * claim draws before making their move to avoid a race
7297 * condition occurring after their move
7299 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
7301 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
7302 p = "Draw claim: 50-move rule";
7303 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
7304 p = "Draw claim: 3-fold repetition";
7305 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
7306 p = "Draw claim: insufficient mating material";
7307 if( p != NULL && canAdjudicate) {
7308 if(engineOpponent) {
7309 SendToProgram("force\n", engineOpponent); // suppress reply
7310 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7312 GameEnds( GameIsDrawn, p, GE_XBOARD );
7317 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
7318 if(engineOpponent) {
7319 SendToProgram("force\n", engineOpponent); // suppress reply
7320 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7322 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
7328 char *SendMoveToBookUser(int moveNr, ChessProgramState *cps, int initial)
7329 { // [HGM] book: this routine intercepts moves to simulate book replies
7330 char *bookHit = NULL;
7332 //first determine if the incoming move brings opponent into his book
7333 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
7334 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
7335 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
7336 if(bookHit != NULL && !cps->bookSuspend) {
7337 // make sure opponent is not going to reply after receiving move to book position
7338 SendToProgram("force\n", cps);
7339 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
7341 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
7342 // now arrange restart after book miss
7344 // after a book hit we never send 'go', and the code after the call to this routine
7345 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
7347 snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), bookHit); // force book move into program supposed to play it
7348 SendToProgram(buf, cps);
7349 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
7350 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
7351 SendToProgram("go\n", cps);
7352 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
7353 } else { // 'go' might be sent based on 'firstMove' after this routine returns
7354 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
7355 SendToProgram("go\n", cps);
7356 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
7358 return bookHit; // notify caller of hit, so it can take action to send move to opponent
7362 ChessProgramState *savedState;
7363 void DeferredBookMove(void)
7365 if(savedState->lastPing != savedState->lastPong)
7366 ScheduleDelayedEvent(DeferredBookMove, 10);
7368 HandleMachineMove(savedMessage, savedState);
7372 HandleMachineMove(message, cps)
7374 ChessProgramState *cps;
7376 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
7377 char realname[MSG_SIZ];
7378 int fromX, fromY, toX, toY;
7387 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
7389 * Kludge to ignore BEL characters
7391 while (*message == '\007') message++;
7394 * [HGM] engine debug message: ignore lines starting with '#' character
7396 if(cps->debug && *message == '#') return;
7399 * Look for book output
7401 if (cps == &first && bookRequested) {
7402 if (message[0] == '\t' || message[0] == ' ') {
7403 /* Part of the book output is here; append it */
7404 strcat(bookOutput, message);
7405 strcat(bookOutput, " \n");
7407 } else if (bookOutput[0] != NULLCHAR) {
7408 /* All of book output has arrived; display it */
7409 char *p = bookOutput;
7410 while (*p != NULLCHAR) {
7411 if (*p == '\t') *p = ' ';
7414 DisplayInformation(bookOutput);
7415 bookRequested = FALSE;
7416 /* Fall through to parse the current output */
7421 * Look for machine move.
7423 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
7424 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
7426 /* This method is only useful on engines that support ping */
7427 if (cps->lastPing != cps->lastPong) {
7428 if (gameMode == BeginningOfGame) {
7429 /* Extra move from before last new; ignore */
7430 if (appData.debugMode) {
7431 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7434 if (appData.debugMode) {
7435 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7436 cps->which, gameMode);
7439 SendToProgram("undo\n", cps);
7445 case BeginningOfGame:
7446 /* Extra move from before last reset; ignore */
7447 if (appData.debugMode) {
7448 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7455 /* Extra move after we tried to stop. The mode test is
7456 not a reliable way of detecting this problem, but it's
7457 the best we can do on engines that don't support ping.
7459 if (appData.debugMode) {
7460 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7461 cps->which, gameMode);
7463 SendToProgram("undo\n", cps);
7466 case MachinePlaysWhite:
7467 case IcsPlayingWhite:
7468 machineWhite = TRUE;
7471 case MachinePlaysBlack:
7472 case IcsPlayingBlack:
7473 machineWhite = FALSE;
7476 case TwoMachinesPlay:
7477 machineWhite = (cps->twoMachinesColor[0] == 'w');
7480 if (WhiteOnMove(forwardMostMove) != machineWhite) {
7481 if (appData.debugMode) {
7483 "Ignoring move out of turn by %s, gameMode %d"
7484 ", forwardMost %d\n",
7485 cps->which, gameMode, forwardMostMove);
7490 if (appData.debugMode) { int f = forwardMostMove;
7491 fprintf(debugFP, "machine move %d, castling = %d %d %d %d %d %d\n", f,
7492 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
7493 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
7495 if(cps->alphaRank) AlphaRank(machineMove, 4);
7496 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
7497 &fromX, &fromY, &toX, &toY, &promoChar)) {
7498 /* Machine move could not be parsed; ignore it. */
7499 snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
7500 machineMove, _(cps->which));
7501 DisplayError(buf1, 0);
7502 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
7503 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType);
7504 if (gameMode == TwoMachinesPlay) {
7505 GameEnds(machineWhite ? BlackWins : WhiteWins,
7511 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
7512 /* So we have to redo legality test with true e.p. status here, */
7513 /* to make sure an illegal e.p. capture does not slip through, */
7514 /* to cause a forfeit on a justified illegal-move complaint */
7515 /* of the opponent. */
7516 if( gameMode==TwoMachinesPlay && appData.testLegality ) {
7518 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
7519 fromY, fromX, toY, toX, promoChar);
7520 if (appData.debugMode) {
7522 for(i=0; i< nrCastlingRights; i++) fprintf(debugFP, "(%d,%d) ",
7523 boards[forwardMostMove][CASTLING][i], castlingRank[i]);
7524 fprintf(debugFP, "castling rights\n");
7526 if(moveType == IllegalMove) {
7527 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
7528 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
7529 GameEnds(machineWhite ? BlackWins : WhiteWins,
7532 } else if(gameInfo.variant != VariantFischeRandom && gameInfo.variant != VariantCapaRandom)
7533 /* [HGM] Kludge to handle engines that send FRC-style castling
7534 when they shouldn't (like TSCP-Gothic) */
7536 case WhiteASideCastleFR:
7537 case BlackASideCastleFR:
7539 currentMoveString[2]++;
7541 case WhiteHSideCastleFR:
7542 case BlackHSideCastleFR:
7544 currentMoveString[2]--;
7546 default: ; // nothing to do, but suppresses warning of pedantic compilers
7549 hintRequested = FALSE;
7550 lastHint[0] = NULLCHAR;
7551 bookRequested = FALSE;
7552 /* Program may be pondering now */
7553 cps->maybeThinking = TRUE;
7554 if (cps->sendTime == 2) cps->sendTime = 1;
7555 if (cps->offeredDraw) cps->offeredDraw--;
7557 /* [AS] Save move info*/
7558 pvInfoList[ forwardMostMove ].score = programStats.score;
7559 pvInfoList[ forwardMostMove ].depth = programStats.depth;
7560 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
7562 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
7564 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
7565 if( gameMode == TwoMachinesPlay && adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
7568 while( count < adjudicateLossPlies ) {
7569 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
7572 score = -score; /* Flip score for winning side */
7575 if( score > adjudicateLossThreshold ) {
7582 if( count >= adjudicateLossPlies ) {
7583 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7585 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7586 "Xboard adjudication",
7593 if(Adjudicate(cps)) {
7594 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7595 return; // [HGM] adjudicate: for all automatic game ends
7599 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
7601 if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
7602 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
7604 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7606 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7608 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
7609 char buf[3*MSG_SIZ];
7611 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
7612 programStats.score / 100.,
7614 programStats.time / 100.,
7615 (unsigned int)programStats.nodes,
7616 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
7617 programStats.movelist);
7619 if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.nodes, programStats.nodes);
7624 /* [AS] Clear stats for next move */
7625 ClearProgramStats();
7626 thinkOutput[0] = NULLCHAR;
7627 hiddenThinkOutputState = 0;
7630 if (gameMode == TwoMachinesPlay) {
7631 /* [HGM] relaying draw offers moved to after reception of move */
7632 /* and interpreting offer as claim if it brings draw condition */
7633 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
7634 SendToProgram("draw\n", cps->other);
7636 if (cps->other->sendTime) {
7637 SendTimeRemaining(cps->other,
7638 cps->other->twoMachinesColor[0] == 'w');
7640 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
7641 if (firstMove && !bookHit) {
7643 if (cps->other->useColors) {
7644 SendToProgram(cps->other->twoMachinesColor, cps->other);
7646 SendToProgram("go\n", cps->other);
7648 cps->other->maybeThinking = TRUE;
7651 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7653 if (!pausing && appData.ringBellAfterMoves) {
7658 * Reenable menu items that were disabled while
7659 * machine was thinking
7661 if (gameMode != TwoMachinesPlay)
7662 SetUserThinkingEnables();
7664 // [HGM] book: after book hit opponent has received move and is now in force mode
7665 // force the book reply into it, and then fake that it outputted this move by jumping
7666 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
7668 static char bookMove[MSG_SIZ]; // a bit generous?
7670 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
7671 strcat(bookMove, bookHit);
7674 programStats.nodes = programStats.depth = programStats.time =
7675 programStats.score = programStats.got_only_move = 0;
7676 sprintf(programStats.movelist, "%s (xbook)", bookHit);
7678 if(cps->lastPing != cps->lastPong) {
7679 savedMessage = message; // args for deferred call
7681 ScheduleDelayedEvent(DeferredBookMove, 10);
7690 /* Set special modes for chess engines. Later something general
7691 * could be added here; for now there is just one kludge feature,
7692 * needed because Crafty 15.10 and earlier don't ignore SIGINT
7693 * when "xboard" is given as an interactive command.
7695 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
7696 cps->useSigint = FALSE;
7697 cps->useSigterm = FALSE;
7699 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
7700 ParseFeatures(message+8, cps);
7701 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
7704 if (!appData.testLegality && !strncmp(message, "setup ", 6)) { // [HGM] allow first engine to define opening position
7705 int dummy, s=6; char buf[MSG_SIZ];
7706 if(appData.icsActive || forwardMostMove != 0 || cps != &first || startedFromSetupPosition) return;
7707 if(sscanf(message, "setup (%s", buf) == 1) s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTable(pieceToChar, buf);
7708 ParseFEN(boards[0], &dummy, message+s);
7709 DrawPosition(TRUE, boards[0]);
7710 startedFromSetupPosition = TRUE;
7713 /* [HGM] Allow engine to set up a position. Don't ask me why one would
7714 * want this, I was asked to put it in, and obliged.
7716 if (!strncmp(message, "setboard ", 9)) {
7717 Board initial_position;
7719 GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
7721 if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9)) {
7722 DisplayError(_("Bad FEN received from engine"), 0);
7726 CopyBoard(boards[0], initial_position);
7727 initialRulePlies = FENrulePlies;
7728 if(blackPlaysFirst) gameMode = MachinePlaysWhite;
7729 else gameMode = MachinePlaysBlack;
7730 DrawPosition(FALSE, boards[currentMove]);
7736 * Look for communication commands
7738 if (!strncmp(message, "telluser ", 9)) {
7739 if(message[9] == '\\' && message[10] == '\\')
7740 EscapeExpand(message+9, message+11); // [HGM] esc: allow escape sequences in popup box
7741 DisplayNote(message + 9);
7744 if (!strncmp(message, "tellusererror ", 14)) {
7746 if(message[14] == '\\' && message[15] == '\\')
7747 EscapeExpand(message+14, message+16); // [HGM] esc: allow escape sequences in popup box
7748 DisplayError(message + 14, 0);
7751 if (!strncmp(message, "tellopponent ", 13)) {
7752 if (appData.icsActive) {
7754 snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
7758 DisplayNote(message + 13);
7762 if (!strncmp(message, "tellothers ", 11)) {
7763 if (appData.icsActive) {
7765 snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
7771 if (!strncmp(message, "tellall ", 8)) {
7772 if (appData.icsActive) {
7774 snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
7778 DisplayNote(message + 8);
7782 if (strncmp(message, "warning", 7) == 0) {
7783 /* Undocumented feature, use tellusererror in new code */
7784 DisplayError(message, 0);
7787 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
7788 safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
7789 strcat(realname, " query");
7790 AskQuestion(realname, buf2, buf1, cps->pr);
7793 /* Commands from the engine directly to ICS. We don't allow these to be
7794 * sent until we are logged on. Crafty kibitzes have been known to
7795 * interfere with the login process.
7798 if (!strncmp(message, "tellics ", 8)) {
7799 SendToICS(message + 8);
7803 if (!strncmp(message, "tellicsnoalias ", 15)) {
7804 SendToICS(ics_prefix);
7805 SendToICS(message + 15);
7809 /* The following are for backward compatibility only */
7810 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
7811 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
7812 SendToICS(ics_prefix);
7818 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
7822 * If the move is illegal, cancel it and redraw the board.
7823 * Also deal with other error cases. Matching is rather loose
7824 * here to accommodate engines written before the spec.
7826 if (strncmp(message + 1, "llegal move", 11) == 0 ||
7827 strncmp(message, "Error", 5) == 0) {
7828 if (StrStr(message, "name") ||
7829 StrStr(message, "rating") || StrStr(message, "?") ||
7830 StrStr(message, "result") || StrStr(message, "board") ||
7831 StrStr(message, "bk") || StrStr(message, "computer") ||
7832 StrStr(message, "variant") || StrStr(message, "hint") ||
7833 StrStr(message, "random") || StrStr(message, "depth") ||
7834 StrStr(message, "accepted")) {
7837 if (StrStr(message, "protover")) {
7838 /* Program is responding to input, so it's apparently done
7839 initializing, and this error message indicates it is
7840 protocol version 1. So we don't need to wait any longer
7841 for it to initialize and send feature commands. */
7842 FeatureDone(cps, 1);
7843 cps->protocolVersion = 1;
7846 cps->maybeThinking = FALSE;
7848 if (StrStr(message, "draw")) {
7849 /* Program doesn't have "draw" command */
7850 cps->sendDrawOffers = 0;
7853 if (cps->sendTime != 1 &&
7854 (StrStr(message, "time") || StrStr(message, "otim"))) {
7855 /* Program apparently doesn't have "time" or "otim" command */
7859 if (StrStr(message, "analyze")) {
7860 cps->analysisSupport = FALSE;
7861 cps->analyzing = FALSE;
7863 snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
7864 DisplayError(buf2, 0);
7867 if (StrStr(message, "(no matching move)st")) {
7868 /* Special kludge for GNU Chess 4 only */
7869 cps->stKludge = TRUE;
7870 SendTimeControl(cps, movesPerSession, timeControl,
7871 timeIncrement, appData.searchDepth,
7875 if (StrStr(message, "(no matching move)sd")) {
7876 /* Special kludge for GNU Chess 4 only */
7877 cps->sdKludge = TRUE;
7878 SendTimeControl(cps, movesPerSession, timeControl,
7879 timeIncrement, appData.searchDepth,
7883 if (!StrStr(message, "llegal")) {
7886 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
7887 gameMode == IcsIdle) return;
7888 if (forwardMostMove <= backwardMostMove) return;
7889 if (pausing) PauseEvent();
7890 if(appData.forceIllegal) {
7891 // [HGM] illegal: machine refused move; force position after move into it
7892 SendToProgram("force\n", cps);
7893 if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
7894 // we have a real problem now, as SendBoard will use the a2a3 kludge
7895 // when black is to move, while there might be nothing on a2 or black
7896 // might already have the move. So send the board as if white has the move.
7897 // But first we must change the stm of the engine, as it refused the last move
7898 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
7899 if(WhiteOnMove(forwardMostMove)) {
7900 SendToProgram("a7a6\n", cps); // for the engine black still had the move
7901 SendBoard(cps, forwardMostMove); // kludgeless board
7903 SendToProgram("a2a3\n", cps); // for the engine white still had the move
7904 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
7905 SendBoard(cps, forwardMostMove+1); // kludgeless board
7907 } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
7908 if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
7909 gameMode == TwoMachinesPlay)
7910 SendToProgram("go\n", cps);
7913 if (gameMode == PlayFromGameFile) {
7914 /* Stop reading this game file */
7915 gameMode = EditGame;
7918 /* [HGM] illegal-move claim should forfeit game when Xboard */
7919 /* only passes fully legal moves */
7920 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
7921 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
7922 "False illegal-move claim", GE_XBOARD );
7923 return; // do not take back move we tested as valid
7925 currentMove = forwardMostMove-1;
7926 DisplayMove(currentMove-1); /* before DisplayMoveError */
7927 SwitchClocks(forwardMostMove-1); // [HGM] race
7928 DisplayBothClocks();
7929 snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
7930 parseList[currentMove], _(cps->which));
7931 DisplayMoveError(buf1);
7932 DrawPosition(FALSE, boards[currentMove]);
7935 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
7936 /* Program has a broken "time" command that
7937 outputs a string not ending in newline.
7943 * If chess program startup fails, exit with an error message.
7944 * Attempts to recover here are futile.
7946 if ((StrStr(message, "unknown host") != NULL)
7947 || (StrStr(message, "No remote directory") != NULL)
7948 || (StrStr(message, "not found") != NULL)
7949 || (StrStr(message, "No such file") != NULL)
7950 || (StrStr(message, "can't alloc") != NULL)
7951 || (StrStr(message, "Permission denied") != NULL)) {
7953 cps->maybeThinking = FALSE;
7954 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
7955 _(cps->which), cps->program, cps->host, message);
7956 RemoveInputSource(cps->isr);
7957 if(appData.icsActive) DisplayFatalError(buf1, 0, 1); else {
7958 if(cps == &first) appData.noChessProgram = TRUE;
7959 DisplayError(buf1, 0);
7965 * Look for hint output
7967 if (sscanf(message, "Hint: %s", buf1) == 1) {
7968 if (cps == &first && hintRequested) {
7969 hintRequested = FALSE;
7970 if (ParseOneMove(buf1, forwardMostMove, &moveType,
7971 &fromX, &fromY, &toX, &toY, &promoChar)) {
7972 (void) CoordsToAlgebraic(boards[forwardMostMove],
7973 PosFlags(forwardMostMove),
7974 fromY, fromX, toY, toX, promoChar, buf1);
7975 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
7976 DisplayInformation(buf2);
7978 /* Hint move could not be parsed!? */
7979 snprintf(buf2, sizeof(buf2),
7980 _("Illegal hint move \"%s\"\nfrom %s chess program"),
7981 buf1, _(cps->which));
7982 DisplayError(buf2, 0);
7985 safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
7991 * Ignore other messages if game is not in progress
7993 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
7994 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
7997 * look for win, lose, draw, or draw offer
7999 if (strncmp(message, "1-0", 3) == 0) {
8000 char *p, *q, *r = "";
8001 p = strchr(message, '{');
8009 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
8011 } else if (strncmp(message, "0-1", 3) == 0) {
8012 char *p, *q, *r = "";
8013 p = strchr(message, '{');
8021 /* Kludge for Arasan 4.1 bug */
8022 if (strcmp(r, "Black resigns") == 0) {
8023 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
8026 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
8028 } else if (strncmp(message, "1/2", 3) == 0) {
8029 char *p, *q, *r = "";
8030 p = strchr(message, '{');
8039 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
8042 } else if (strncmp(message, "White resign", 12) == 0) {
8043 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8045 } else if (strncmp(message, "Black resign", 12) == 0) {
8046 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8048 } else if (strncmp(message, "White matches", 13) == 0 ||
8049 strncmp(message, "Black matches", 13) == 0 ) {
8050 /* [HGM] ignore GNUShogi noises */
8052 } else if (strncmp(message, "White", 5) == 0 &&
8053 message[5] != '(' &&
8054 StrStr(message, "Black") == NULL) {
8055 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8057 } else if (strncmp(message, "Black", 5) == 0 &&
8058 message[5] != '(') {
8059 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8061 } else if (strcmp(message, "resign") == 0 ||
8062 strcmp(message, "computer resigns") == 0) {
8064 case MachinePlaysBlack:
8065 case IcsPlayingBlack:
8066 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
8068 case MachinePlaysWhite:
8069 case IcsPlayingWhite:
8070 GameEnds(BlackWins, "White resigns", GE_ENGINE);
8072 case TwoMachinesPlay:
8073 if (cps->twoMachinesColor[0] == 'w')
8074 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8076 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8083 } else if (strncmp(message, "opponent mates", 14) == 0) {
8085 case MachinePlaysBlack:
8086 case IcsPlayingBlack:
8087 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8089 case MachinePlaysWhite:
8090 case IcsPlayingWhite:
8091 GameEnds(BlackWins, "Black mates", GE_ENGINE);
8093 case TwoMachinesPlay:
8094 if (cps->twoMachinesColor[0] == 'w')
8095 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8097 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8104 } else if (strncmp(message, "computer mates", 14) == 0) {
8106 case MachinePlaysBlack:
8107 case IcsPlayingBlack:
8108 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
8110 case MachinePlaysWhite:
8111 case IcsPlayingWhite:
8112 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8114 case TwoMachinesPlay:
8115 if (cps->twoMachinesColor[0] == 'w')
8116 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8118 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8125 } else if (strncmp(message, "checkmate", 9) == 0) {
8126 if (WhiteOnMove(forwardMostMove)) {
8127 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8129 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8132 } else if (strstr(message, "Draw") != NULL ||
8133 strstr(message, "game is a draw") != NULL) {
8134 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
8136 } else if (strstr(message, "offer") != NULL &&
8137 strstr(message, "draw") != NULL) {
8139 if (appData.zippyPlay && first.initDone) {
8140 /* Relay offer to ICS */
8141 SendToICS(ics_prefix);
8142 SendToICS("draw\n");
8145 cps->offeredDraw = 2; /* valid until this engine moves twice */
8146 if (gameMode == TwoMachinesPlay) {
8147 if (cps->other->offeredDraw) {
8148 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8149 /* [HGM] in two-machine mode we delay relaying draw offer */
8150 /* until after we also have move, to see if it is really claim */
8152 } else if (gameMode == MachinePlaysWhite ||
8153 gameMode == MachinePlaysBlack) {
8154 if (userOfferedDraw) {
8155 DisplayInformation(_("Machine accepts your draw offer"));
8156 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8158 DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
8165 * Look for thinking output
8167 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
8168 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
8170 int plylev, mvleft, mvtot, curscore, time;
8171 char mvname[MOVE_LEN];
8175 int prefixHint = FALSE;
8176 mvname[0] = NULLCHAR;
8179 case MachinePlaysBlack:
8180 case IcsPlayingBlack:
8181 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8183 case MachinePlaysWhite:
8184 case IcsPlayingWhite:
8185 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8190 case IcsObserving: /* [DM] icsEngineAnalyze */
8191 if (!appData.icsEngineAnalyze) ignore = TRUE;
8193 case TwoMachinesPlay:
8194 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
8204 ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
8206 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8207 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
8209 if (plyext != ' ' && plyext != '\t') {
8213 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8214 if( cps->scoreIsAbsolute &&
8215 ( gameMode == MachinePlaysBlack ||
8216 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
8217 gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
8218 (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
8219 !WhiteOnMove(currentMove)
8222 curscore = -curscore;
8226 tempStats.depth = plylev;
8227 tempStats.nodes = nodes;
8228 tempStats.time = time;
8229 tempStats.score = curscore;
8230 tempStats.got_only_move = 0;
8232 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
8235 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
8236 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
8237 if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
8238 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
8239 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
8240 if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
8241 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
8242 blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
8245 /* Buffer overflow protection */
8246 if (buf1[0] != NULLCHAR) {
8247 if (strlen(buf1) >= sizeof(tempStats.movelist)
8248 && appData.debugMode) {
8250 "PV is too long; using the first %u bytes.\n",
8251 (unsigned) sizeof(tempStats.movelist) - 1);
8254 safeStrCpy( tempStats.movelist, buf1, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
8256 sprintf(tempStats.movelist, " no PV\n");
8259 if (tempStats.seen_stat) {
8260 tempStats.ok_to_send = 1;
8263 if (strchr(tempStats.movelist, '(') != NULL) {
8264 tempStats.line_is_book = 1;
8265 tempStats.nr_moves = 0;
8266 tempStats.moves_left = 0;
8268 tempStats.line_is_book = 0;
8271 if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
8272 programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
8274 SendProgramStatsToFrontend( cps, &tempStats );
8277 [AS] Protect the thinkOutput buffer from overflow... this
8278 is only useful if buf1 hasn't overflowed first!
8280 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s",
8282 (gameMode == TwoMachinesPlay ?
8283 ToUpper(cps->twoMachinesColor[0]) : ' '),
8284 ((double) curscore) / 100.0,
8285 prefixHint ? lastHint : "",
8286 prefixHint ? " " : "" );
8288 if( buf1[0] != NULLCHAR ) {
8289 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
8291 if( strlen(buf1) > max_len ) {
8292 if( appData.debugMode) {
8293 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
8295 buf1[max_len+1] = '\0';
8298 strcat( thinkOutput, buf1 );
8301 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
8302 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8303 DisplayMove(currentMove - 1);
8307 } else if ((p=StrStr(message, "(only move)")) != NULL) {
8308 /* crafty (9.25+) says "(only move) <move>"
8309 * if there is only 1 legal move
8311 sscanf(p, "(only move) %s", buf1);
8312 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
8313 sprintf(programStats.movelist, "%s (only move)", buf1);
8314 programStats.depth = 1;
8315 programStats.nr_moves = 1;
8316 programStats.moves_left = 1;
8317 programStats.nodes = 1;
8318 programStats.time = 1;
8319 programStats.got_only_move = 1;
8321 /* Not really, but we also use this member to
8322 mean "line isn't going to change" (Crafty
8323 isn't searching, so stats won't change) */
8324 programStats.line_is_book = 1;
8326 SendProgramStatsToFrontend( cps, &programStats );
8328 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8329 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8330 DisplayMove(currentMove - 1);
8333 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
8334 &time, &nodes, &plylev, &mvleft,
8335 &mvtot, mvname) >= 5) {
8336 /* The stat01: line is from Crafty (9.29+) in response
8337 to the "." command */
8338 programStats.seen_stat = 1;
8339 cps->maybeThinking = TRUE;
8341 if (programStats.got_only_move || !appData.periodicUpdates)
8344 programStats.depth = plylev;
8345 programStats.time = time;
8346 programStats.nodes = nodes;
8347 programStats.moves_left = mvleft;
8348 programStats.nr_moves = mvtot;
8349 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
8350 programStats.ok_to_send = 1;
8351 programStats.movelist[0] = '\0';
8353 SendProgramStatsToFrontend( cps, &programStats );
8357 } else if (strncmp(message,"++",2) == 0) {
8358 /* Crafty 9.29+ outputs this */
8359 programStats.got_fail = 2;
8362 } else if (strncmp(message,"--",2) == 0) {
8363 /* Crafty 9.29+ outputs this */
8364 programStats.got_fail = 1;
8367 } else if (thinkOutput[0] != NULLCHAR &&
8368 strncmp(message, " ", 4) == 0) {
8369 unsigned message_len;
8372 while (*p && *p == ' ') p++;
8374 message_len = strlen( p );
8376 /* [AS] Avoid buffer overflow */
8377 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
8378 strcat(thinkOutput, " ");
8379 strcat(thinkOutput, p);
8382 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
8383 strcat(programStats.movelist, " ");
8384 strcat(programStats.movelist, p);
8387 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8388 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8389 DisplayMove(currentMove - 1);
8397 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8398 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
8400 ChessProgramStats cpstats;
8402 if (plyext != ' ' && plyext != '\t') {
8406 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8407 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
8408 curscore = -curscore;
8411 cpstats.depth = plylev;
8412 cpstats.nodes = nodes;
8413 cpstats.time = time;
8414 cpstats.score = curscore;
8415 cpstats.got_only_move = 0;
8416 cpstats.movelist[0] = '\0';
8418 if (buf1[0] != NULLCHAR) {
8419 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
8422 cpstats.ok_to_send = 0;
8423 cpstats.line_is_book = 0;
8424 cpstats.nr_moves = 0;
8425 cpstats.moves_left = 0;
8427 SendProgramStatsToFrontend( cps, &cpstats );
8434 /* Parse a game score from the character string "game", and
8435 record it as the history of the current game. The game
8436 score is NOT assumed to start from the standard position.
8437 The display is not updated in any way.
8440 ParseGameHistory(game)
8444 int fromX, fromY, toX, toY, boardIndex;
8449 if (appData.debugMode)
8450 fprintf(debugFP, "Parsing game history: %s\n", game);
8452 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
8453 gameInfo.site = StrSave(appData.icsHost);
8454 gameInfo.date = PGNDate();
8455 gameInfo.round = StrSave("-");
8457 /* Parse out names of players */
8458 while (*game == ' ') game++;
8460 while (*game != ' ') *p++ = *game++;
8462 gameInfo.white = StrSave(buf);
8463 while (*game == ' ') game++;
8465 while (*game != ' ' && *game != '\n') *p++ = *game++;
8467 gameInfo.black = StrSave(buf);
8470 boardIndex = blackPlaysFirst ? 1 : 0;
8473 yyboardindex = boardIndex;
8474 moveType = (ChessMove) Myylex();
8476 case IllegalMove: /* maybe suicide chess, etc. */
8477 if (appData.debugMode) {
8478 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
8479 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8480 setbuf(debugFP, NULL);
8482 case WhitePromotion:
8483 case BlackPromotion:
8484 case WhiteNonPromotion:
8485 case BlackNonPromotion:
8487 case WhiteCapturesEnPassant:
8488 case BlackCapturesEnPassant:
8489 case WhiteKingSideCastle:
8490 case WhiteQueenSideCastle:
8491 case BlackKingSideCastle:
8492 case BlackQueenSideCastle:
8493 case WhiteKingSideCastleWild:
8494 case WhiteQueenSideCastleWild:
8495 case BlackKingSideCastleWild:
8496 case BlackQueenSideCastleWild:
8498 case WhiteHSideCastleFR:
8499 case WhiteASideCastleFR:
8500 case BlackHSideCastleFR:
8501 case BlackASideCastleFR:
8503 fromX = currentMoveString[0] - AAA;
8504 fromY = currentMoveString[1] - ONE;
8505 toX = currentMoveString[2] - AAA;
8506 toY = currentMoveString[3] - ONE;
8507 promoChar = currentMoveString[4];
8511 fromX = moveType == WhiteDrop ?
8512 (int) CharToPiece(ToUpper(currentMoveString[0])) :
8513 (int) CharToPiece(ToLower(currentMoveString[0]));
8515 toX = currentMoveString[2] - AAA;
8516 toY = currentMoveString[3] - ONE;
8517 promoChar = NULLCHAR;
8521 snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
8522 if (appData.debugMode) {
8523 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
8524 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8525 setbuf(debugFP, NULL);
8527 DisplayError(buf, 0);
8529 case ImpossibleMove:
8531 snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
8532 if (appData.debugMode) {
8533 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
8534 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8535 setbuf(debugFP, NULL);
8537 DisplayError(buf, 0);
8540 if (boardIndex < backwardMostMove) {
8541 /* Oops, gap. How did that happen? */
8542 DisplayError(_("Gap in move list"), 0);
8545 backwardMostMove = blackPlaysFirst ? 1 : 0;
8546 if (boardIndex > forwardMostMove) {
8547 forwardMostMove = boardIndex;
8551 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
8552 strcat(parseList[boardIndex-1], " ");
8553 strcat(parseList[boardIndex-1], yy_text);
8565 case GameUnfinished:
8566 if (gameMode == IcsExamining) {
8567 if (boardIndex < backwardMostMove) {
8568 /* Oops, gap. How did that happen? */
8571 backwardMostMove = blackPlaysFirst ? 1 : 0;
8574 gameInfo.result = moveType;
8575 p = strchr(yy_text, '{');
8576 if (p == NULL) p = strchr(yy_text, '(');
8579 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
8581 q = strchr(p, *p == '{' ? '}' : ')');
8582 if (q != NULL) *q = NULLCHAR;
8585 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
8586 gameInfo.resultDetails = StrSave(p);
8589 if (boardIndex >= forwardMostMove &&
8590 !(gameMode == IcsObserving && ics_gamenum == -1)) {
8591 backwardMostMove = blackPlaysFirst ? 1 : 0;
8594 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
8595 fromY, fromX, toY, toX, promoChar,
8596 parseList[boardIndex]);
8597 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
8598 /* currentMoveString is set as a side-effect of yylex */
8599 safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
8600 strcat(moveList[boardIndex], "\n");
8602 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
8603 switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
8609 if(gameInfo.variant != VariantShogi)
8610 strcat(parseList[boardIndex - 1], "+");
8614 strcat(parseList[boardIndex - 1], "#");
8621 /* Apply a move to the given board */
8623 ApplyMove(fromX, fromY, toX, toY, promoChar, board)
8624 int fromX, fromY, toX, toY;
8628 ChessSquare captured = board[toY][toX], piece, king; int p, oldEP = EP_NONE, berolina = 0;
8629 int promoRank = gameInfo.variant == VariantMakruk ? 3 : 1;
8631 /* [HGM] compute & store e.p. status and castling rights for new position */
8632 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
8634 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
8635 oldEP = (signed char)board[EP_STATUS];
8636 board[EP_STATUS] = EP_NONE;
8638 if( board[toY][toX] != EmptySquare )
8639 board[EP_STATUS] = EP_CAPTURE;
8641 if (fromY == DROP_RANK) {
8643 piece = board[toY][toX] = (ChessSquare) fromX;
8647 if( board[fromY][fromX] == WhiteLance || board[fromY][fromX] == BlackLance ) {
8648 if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi )
8649 board[EP_STATUS] = EP_PAWN_MOVE; // Lance is Pawn-like in most variants
8651 if( board[fromY][fromX] == WhitePawn ) {
8652 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
8653 board[EP_STATUS] = EP_PAWN_MOVE;
8655 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
8656 gameInfo.variant != VariantBerolina || toX < fromX)
8657 board[EP_STATUS] = toX | berolina;
8658 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
8659 gameInfo.variant != VariantBerolina || toX > fromX)
8660 board[EP_STATUS] = toX;
8663 if( board[fromY][fromX] == BlackPawn ) {
8664 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
8665 board[EP_STATUS] = EP_PAWN_MOVE;
8666 if( toY-fromY== -2) {
8667 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
8668 gameInfo.variant != VariantBerolina || toX < fromX)
8669 board[EP_STATUS] = toX | berolina;
8670 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
8671 gameInfo.variant != VariantBerolina || toX > fromX)
8672 board[EP_STATUS] = toX;
8676 for(i=0; i<nrCastlingRights; i++) {
8677 if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
8678 board[CASTLING][i] == toX && castlingRank[i] == toY
8679 ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
8682 if (fromX == toX && fromY == toY) return;
8684 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
8685 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
8686 if(gameInfo.variant == VariantKnightmate)
8687 king += (int) WhiteUnicorn - (int) WhiteKing;
8689 /* Code added by Tord: */
8690 /* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
8691 if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
8692 board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
8693 board[fromY][fromX] = EmptySquare;
8694 board[toY][toX] = EmptySquare;
8695 if((toX > fromX) != (piece == WhiteRook)) {
8696 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
8698 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
8700 } else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
8701 board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
8702 board[fromY][fromX] = EmptySquare;
8703 board[toY][toX] = EmptySquare;
8704 if((toX > fromX) != (piece == BlackRook)) {
8705 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
8707 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
8709 /* End of code added by Tord */
8711 } else if (board[fromY][fromX] == king
8712 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8713 && toY == fromY && toX > fromX+1) {
8714 board[fromY][fromX] = EmptySquare;
8715 board[toY][toX] = king;
8716 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
8717 board[fromY][BOARD_RGHT-1] = EmptySquare;
8718 } else if (board[fromY][fromX] == king
8719 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8720 && toY == fromY && toX < fromX-1) {
8721 board[fromY][fromX] = EmptySquare;
8722 board[toY][toX] = king;
8723 board[toY][toX+1] = board[fromY][BOARD_LEFT];
8724 board[fromY][BOARD_LEFT] = EmptySquare;
8725 } else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
8726 board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
8727 && toY >= BOARD_HEIGHT-promoRank
8729 /* white pawn promotion */
8730 board[toY][toX] = CharToPiece(ToUpper(promoChar));
8731 if (board[toY][toX] == EmptySquare) {
8732 board[toY][toX] = WhiteQueen;
8734 if(gameInfo.variant==VariantBughouse ||
8735 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
8736 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
8737 board[fromY][fromX] = EmptySquare;
8738 } else if ((fromY == BOARD_HEIGHT-4)
8740 && gameInfo.variant != VariantXiangqi
8741 && gameInfo.variant != VariantBerolina
8742 && (board[fromY][fromX] == WhitePawn)
8743 && (board[toY][toX] == EmptySquare)) {
8744 board[fromY][fromX] = EmptySquare;
8745 board[toY][toX] = WhitePawn;
8746 captured = board[toY - 1][toX];
8747 board[toY - 1][toX] = EmptySquare;
8748 } else if ((fromY == BOARD_HEIGHT-4)
8750 && gameInfo.variant == VariantBerolina
8751 && (board[fromY][fromX] == WhitePawn)
8752 && (board[toY][toX] == EmptySquare)) {
8753 board[fromY][fromX] = EmptySquare;
8754 board[toY][toX] = WhitePawn;
8755 if(oldEP & EP_BEROLIN_A) {
8756 captured = board[fromY][fromX-1];
8757 board[fromY][fromX-1] = EmptySquare;
8758 }else{ captured = board[fromY][fromX+1];
8759 board[fromY][fromX+1] = EmptySquare;
8761 } else if (board[fromY][fromX] == king
8762 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8763 && toY == fromY && toX > fromX+1) {
8764 board[fromY][fromX] = EmptySquare;
8765 board[toY][toX] = king;
8766 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
8767 board[fromY][BOARD_RGHT-1] = EmptySquare;
8768 } else if (board[fromY][fromX] == king
8769 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8770 && toY == fromY && toX < fromX-1) {
8771 board[fromY][fromX] = EmptySquare;
8772 board[toY][toX] = king;
8773 board[toY][toX+1] = board[fromY][BOARD_LEFT];
8774 board[fromY][BOARD_LEFT] = EmptySquare;
8775 } else if (fromY == 7 && fromX == 3
8776 && board[fromY][fromX] == BlackKing
8777 && toY == 7 && toX == 5) {
8778 board[fromY][fromX] = EmptySquare;
8779 board[toY][toX] = BlackKing;
8780 board[fromY][7] = EmptySquare;
8781 board[toY][4] = BlackRook;
8782 } else if (fromY == 7 && fromX == 3
8783 && board[fromY][fromX] == BlackKing
8784 && toY == 7 && toX == 1) {
8785 board[fromY][fromX] = EmptySquare;
8786 board[toY][toX] = BlackKing;
8787 board[fromY][0] = EmptySquare;
8788 board[toY][2] = BlackRook;
8789 } else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
8790 board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
8793 /* black pawn promotion */
8794 board[toY][toX] = CharToPiece(ToLower(promoChar));
8795 if (board[toY][toX] == EmptySquare) {
8796 board[toY][toX] = BlackQueen;
8798 if(gameInfo.variant==VariantBughouse ||
8799 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
8800 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
8801 board[fromY][fromX] = EmptySquare;
8802 } else if ((fromY == 3)
8804 && gameInfo.variant != VariantXiangqi
8805 && gameInfo.variant != VariantBerolina
8806 && (board[fromY][fromX] == BlackPawn)
8807 && (board[toY][toX] == EmptySquare)) {
8808 board[fromY][fromX] = EmptySquare;
8809 board[toY][toX] = BlackPawn;
8810 captured = board[toY + 1][toX];
8811 board[toY + 1][toX] = EmptySquare;
8812 } else if ((fromY == 3)
8814 && gameInfo.variant == VariantBerolina
8815 && (board[fromY][fromX] == BlackPawn)
8816 && (board[toY][toX] == EmptySquare)) {
8817 board[fromY][fromX] = EmptySquare;
8818 board[toY][toX] = BlackPawn;
8819 if(oldEP & EP_BEROLIN_A) {
8820 captured = board[fromY][fromX-1];
8821 board[fromY][fromX-1] = EmptySquare;
8822 }else{ captured = board[fromY][fromX+1];
8823 board[fromY][fromX+1] = EmptySquare;
8826 board[toY][toX] = board[fromY][fromX];
8827 board[fromY][fromX] = EmptySquare;
8831 if (gameInfo.holdingsWidth != 0) {
8833 /* !!A lot more code needs to be written to support holdings */
8834 /* [HGM] OK, so I have written it. Holdings are stored in the */
8835 /* penultimate board files, so they are automaticlly stored */
8836 /* in the game history. */
8837 if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
8838 && promoChar && piece != WhitePawn && piece != BlackPawn) {
8839 /* Delete from holdings, by decreasing count */
8840 /* and erasing image if necessary */
8841 p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
8842 if(p < (int) BlackPawn) { /* white drop */
8843 p -= (int)WhitePawn;
8844 p = PieceToNumber((ChessSquare)p);
8845 if(p >= gameInfo.holdingsSize) p = 0;
8846 if(--board[p][BOARD_WIDTH-2] <= 0)
8847 board[p][BOARD_WIDTH-1] = EmptySquare;
8848 if((int)board[p][BOARD_WIDTH-2] < 0)
8849 board[p][BOARD_WIDTH-2] = 0;
8850 } else { /* black drop */
8851 p -= (int)BlackPawn;
8852 p = PieceToNumber((ChessSquare)p);
8853 if(p >= gameInfo.holdingsSize) p = 0;
8854 if(--board[BOARD_HEIGHT-1-p][1] <= 0)
8855 board[BOARD_HEIGHT-1-p][0] = EmptySquare;
8856 if((int)board[BOARD_HEIGHT-1-p][1] < 0)
8857 board[BOARD_HEIGHT-1-p][1] = 0;
8860 if (captured != EmptySquare && gameInfo.holdingsSize > 0
8861 && gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess ) {
8862 /* [HGM] holdings: Add to holdings, if holdings exist */
8863 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
8864 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
8865 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
8868 if (p >= (int) BlackPawn) {
8869 p -= (int)BlackPawn;
8870 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
8871 /* in Shogi restore piece to its original first */
8872 captured = (ChessSquare) (DEMOTED captured);
8875 p = PieceToNumber((ChessSquare)p);
8876 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
8877 board[p][BOARD_WIDTH-2]++;
8878 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
8880 p -= (int)WhitePawn;
8881 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
8882 captured = (ChessSquare) (DEMOTED captured);
8885 p = PieceToNumber((ChessSquare)p);
8886 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
8887 board[BOARD_HEIGHT-1-p][1]++;
8888 board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
8891 } else if (gameInfo.variant == VariantAtomic) {
8892 if (captured != EmptySquare) {
8894 for (y = toY-1; y <= toY+1; y++) {
8895 for (x = toX-1; x <= toX+1; x++) {
8896 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
8897 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
8898 board[y][x] = EmptySquare;
8902 board[toY][toX] = EmptySquare;
8905 if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
8906 board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
8908 if(promoChar == '+') {
8909 /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite orinary Pawn promotion) */
8910 board[toY][toX] = (ChessSquare) (PROMOTED piece);
8911 } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
8912 board[toY][toX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
8914 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
8915 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
8916 // [HGM] superchess: take promotion piece out of holdings
8917 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
8918 if((int)piece < (int)BlackPawn) { // determine stm from piece color
8919 if(!--board[k][BOARD_WIDTH-2])
8920 board[k][BOARD_WIDTH-1] = EmptySquare;
8922 if(!--board[BOARD_HEIGHT-1-k][1])
8923 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
8929 /* Updates forwardMostMove */
8931 MakeMove(fromX, fromY, toX, toY, promoChar)
8932 int fromX, fromY, toX, toY;
8935 // forwardMostMove++; // [HGM] bare: moved downstream
8937 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
8938 int timeLeft; static int lastLoadFlag=0; int king, piece;
8939 piece = boards[forwardMostMove][fromY][fromX];
8940 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
8941 if(gameInfo.variant == VariantKnightmate)
8942 king += (int) WhiteUnicorn - (int) WhiteKing;
8943 if(forwardMostMove == 0) {
8945 fprintf(serverMoves, "%s;", second.tidy);
8946 fprintf(serverMoves, "%s;", first.tidy);
8947 if(!blackPlaysFirst)
8948 fprintf(serverMoves, "%s;", second.tidy);
8949 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
8950 lastLoadFlag = loadFlag;
8952 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
8953 // print castling suffix
8954 if( toY == fromY && piece == king ) {
8956 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
8958 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
8961 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
8962 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
8963 boards[forwardMostMove][toY][toX] == EmptySquare
8964 && fromX != toX && fromY != toY)
8965 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
8967 if(promoChar != NULLCHAR)
8968 fprintf(serverMoves, ":%c:%c%c", promoChar, AAA+toX, ONE+toY);
8970 fprintf(serverMoves, "/%d/%d",
8971 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
8972 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
8973 else timeLeft = blackTimeRemaining/1000;
8974 fprintf(serverMoves, "/%d", timeLeft);
8976 fflush(serverMoves);
8979 if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations
8980 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
8984 UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
8985 if (commentList[forwardMostMove+1] != NULL) {
8986 free(commentList[forwardMostMove+1]);
8987 commentList[forwardMostMove+1] = NULL;
8989 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
8990 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
8991 // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
8992 SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
8993 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
8994 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
8995 gameInfo.result = GameUnfinished;
8996 if (gameInfo.resultDetails != NULL) {
8997 free(gameInfo.resultDetails);
8998 gameInfo.resultDetails = NULL;
9000 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
9001 moveList[forwardMostMove - 1]);
9002 (void) CoordsToAlgebraic(boards[forwardMostMove - 1],
9003 PosFlags(forwardMostMove - 1),
9004 fromY, fromX, toY, toX, promoChar,
9005 parseList[forwardMostMove - 1]);
9006 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
9012 if(gameInfo.variant != VariantShogi)
9013 strcat(parseList[forwardMostMove - 1], "+");
9017 strcat(parseList[forwardMostMove - 1], "#");
9020 if (appData.debugMode) {
9021 fprintf(debugFP, "move: %s, parse: %s (%c)\n", moveList[forwardMostMove-1], parseList[forwardMostMove-1], moveList[forwardMostMove-1][4]);
9026 /* Updates currentMove if not pausing */
9028 ShowMove(fromX, fromY, toX, toY)
9030 int instant = (gameMode == PlayFromGameFile) ?
9031 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
9032 if(appData.noGUI) return;
9033 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
9035 if (forwardMostMove == currentMove + 1) {
9036 AnimateMove(boards[forwardMostMove - 1],
9037 fromX, fromY, toX, toY);
9039 if (appData.highlightLastMove) {
9040 SetHighlights(fromX, fromY, toX, toY);
9043 currentMove = forwardMostMove;
9046 if (instant) return;
9048 DisplayMove(currentMove - 1);
9049 DrawPosition(FALSE, boards[currentMove]);
9050 DisplayBothClocks();
9051 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
9054 void SendEgtPath(ChessProgramState *cps)
9055 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
9056 char buf[MSG_SIZ], name[MSG_SIZ], *p;
9058 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
9061 char c, *q = name+1, *r, *s;
9063 name[0] = ','; // extract next format name from feature and copy with prefixed ','
9064 while(*p && *p != ',') *q++ = *p++;
9066 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
9067 strcmp(name, ",nalimov:") == 0 ) {
9068 // take nalimov path from the menu-changeable option first, if it is defined
9069 snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
9070 SendToProgram(buf,cps); // send egtbpath command for nalimov
9072 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
9073 (s = StrStr(appData.egtFormats, name)) != NULL) {
9074 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
9075 s = r = StrStr(s, ":") + 1; // beginning of path info
9076 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
9077 c = *r; *r = 0; // temporarily null-terminate path info
9078 *--q = 0; // strip of trailig ':' from name
9079 snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
9081 SendToProgram(buf,cps); // send egtbpath command for this format
9083 if(*p == ',') p++; // read away comma to position for next format name
9088 InitChessProgram(cps, setup)
9089 ChessProgramState *cps;
9090 int setup; /* [HGM] needed to setup FRC opening position */
9092 char buf[MSG_SIZ], b[MSG_SIZ]; int overruled;
9093 if (appData.noChessProgram) return;
9094 hintRequested = FALSE;
9095 bookRequested = FALSE;
9097 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
9098 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
9099 if(cps->memSize) { /* [HGM] memory */
9100 snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
9101 SendToProgram(buf, cps);
9103 SendEgtPath(cps); /* [HGM] EGT */
9104 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
9105 snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
9106 SendToProgram(buf, cps);
9109 SendToProgram(cps->initString, cps);
9110 if (gameInfo.variant != VariantNormal &&
9111 gameInfo.variant != VariantLoadable
9112 /* [HGM] also send variant if board size non-standard */
9113 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0
9115 char *v = VariantName(gameInfo.variant);
9116 if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) {
9117 /* [HGM] in protocol 1 we have to assume all variants valid */
9118 snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), v, cps->tidy);
9119 DisplayFatalError(buf, 0, 1);
9123 /* [HGM] make prefix for non-standard board size. Awkward testing... */
9124 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9125 if( gameInfo.variant == VariantXiangqi )
9126 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 0;
9127 if( gameInfo.variant == VariantShogi )
9128 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 9 || gameInfo.holdingsSize != 7;
9129 if( gameInfo.variant == VariantBughouse || gameInfo.variant == VariantCrazyhouse )
9130 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 5;
9131 if( gameInfo.variant == VariantCapablanca || gameInfo.variant == VariantCapaRandom ||
9132 gameInfo.variant == VariantGothic || gameInfo.variant == VariantFalcon || gameInfo.variant == VariantJanus )
9133 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9134 if( gameInfo.variant == VariantCourier )
9135 overruled = gameInfo.boardWidth != 12 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9136 if( gameInfo.variant == VariantSuper )
9137 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9138 if( gameInfo.variant == VariantGreat )
9139 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9140 if( gameInfo.variant == VariantSChess )
9141 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 7;
9144 snprintf(b, MSG_SIZ, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
9145 gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
9146 /* [HGM] varsize: try first if this defiant size variant is specifically known */
9147 if(StrStr(cps->variants, b) == NULL) {
9148 // specific sized variant not known, check if general sizing allowed
9149 if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best
9150 if(StrStr(cps->variants, "boardsize") == NULL) {
9151 snprintf(buf, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
9152 gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy);
9153 DisplayFatalError(buf, 0, 1);
9156 /* [HGM] here we really should compare with the maximum supported board size */
9159 } else snprintf(b, MSG_SIZ,"%s", VariantName(gameInfo.variant));
9160 snprintf(buf, MSG_SIZ, "variant %s\n", b);
9161 SendToProgram(buf, cps);
9163 currentlyInitializedVariant = gameInfo.variant;
9165 /* [HGM] send opening position in FRC to first engine */
9167 SendToProgram("force\n", cps);
9169 /* engine is now in force mode! Set flag to wake it up after first move. */
9170 setboardSpoiledMachineBlack = 1;
9174 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
9175 SendToProgram(buf, cps);
9177 cps->maybeThinking = FALSE;
9178 cps->offeredDraw = 0;
9179 if (!appData.icsActive) {
9180 SendTimeControl(cps, movesPerSession, timeControl,
9181 timeIncrement, appData.searchDepth,
9184 if (appData.showThinking
9185 // [HGM] thinking: four options require thinking output to be sent
9186 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
9188 SendToProgram("post\n", cps);
9190 SendToProgram("hard\n", cps);
9191 if (!appData.ponderNextMove) {
9192 /* Warning: "easy" is a toggle in GNU Chess, so don't send
9193 it without being sure what state we are in first. "hard"
9194 is not a toggle, so that one is OK.
9196 SendToProgram("easy\n", cps);
9199 snprintf(buf, MSG_SIZ, "ping %d\n", ++cps->lastPing);
9200 SendToProgram(buf, cps);
9202 cps->initDone = TRUE;
9207 StartChessProgram(cps)
9208 ChessProgramState *cps;
9213 if (appData.noChessProgram) return;
9214 cps->initDone = FALSE;
9216 if (strcmp(cps->host, "localhost") == 0) {
9217 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
9218 } else if (*appData.remoteShell == NULLCHAR) {
9219 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
9221 if (*appData.remoteUser == NULLCHAR) {
9222 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
9225 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
9226 cps->host, appData.remoteUser, cps->program);
9228 err = StartChildProcess(buf, "", &cps->pr);
9232 snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
9233 DisplayFatalError(buf, err, 1);
9239 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
9240 if (cps->protocolVersion > 1) {
9241 snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
9242 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
9243 cps->comboCnt = 0; // and values of combo boxes
9244 SendToProgram(buf, cps);
9246 SendToProgram("xboard\n", cps);
9251 TwoMachinesEventIfReady P((void))
9253 if (first.lastPing != first.lastPong) {
9254 DisplayMessage("", _("Waiting for first chess program"));
9255 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9258 if (second.lastPing != second.lastPong) {
9259 DisplayMessage("", _("Waiting for second chess program"));
9260 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9268 NextMatchGame P((void))
9271 LoadGameOrPosition(matchGame);
9272 TwoMachinesEventIfReady();
9275 void UserAdjudicationEvent( int result )
9277 ChessMove gameResult = GameIsDrawn;
9280 gameResult = WhiteWins;
9282 else if( result < 0 ) {
9283 gameResult = BlackWins;
9286 if( gameMode == TwoMachinesPlay ) {
9287 GameEnds( gameResult, "User adjudication", GE_XBOARD );
9292 // [HGM] save: calculate checksum of game to make games easily identifiable
9293 int StringCheckSum(char *s)
9296 if(s==NULL) return 0;
9297 while(*s) i = i*259 + *s++;
9304 for(i=backwardMostMove; i<forwardMostMove; i++) {
9305 sum += pvInfoList[i].depth;
9306 sum += StringCheckSum(parseList[i]);
9307 sum += StringCheckSum(commentList[i]);
9310 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
9311 return sum + StringCheckSum(commentList[i]);
9312 } // end of save patch
9315 GameEnds(result, resultDetails, whosays)
9317 char *resultDetails;
9320 GameMode nextGameMode;
9322 char buf[MSG_SIZ], popupRequested = 0;
9324 if(endingGame) return; /* [HGM] crash: forbid recursion */
9326 if(twoBoards) { // [HGM] dual: switch back to one board
9327 twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
9328 DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
9330 if (appData.debugMode) {
9331 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
9332 result, resultDetails ? resultDetails : "(null)", whosays);
9335 fromX = fromY = -1; // [HGM] abort any move the user is entering.
9337 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
9338 /* If we are playing on ICS, the server decides when the
9339 game is over, but the engine can offer to draw, claim
9343 if (appData.zippyPlay && first.initDone) {
9344 if (result == GameIsDrawn) {
9345 /* In case draw still needs to be claimed */
9346 SendToICS(ics_prefix);
9347 SendToICS("draw\n");
9348 } else if (StrCaseStr(resultDetails, "resign")) {
9349 SendToICS(ics_prefix);
9350 SendToICS("resign\n");
9354 endingGame = 0; /* [HGM] crash */
9358 /* If we're loading the game from a file, stop */
9359 if (whosays == GE_FILE) {
9360 (void) StopLoadGameTimer();
9364 /* Cancel draw offers */
9365 first.offeredDraw = second.offeredDraw = 0;
9367 /* If this is an ICS game, only ICS can really say it's done;
9368 if not, anyone can. */
9369 isIcsGame = (gameMode == IcsPlayingWhite ||
9370 gameMode == IcsPlayingBlack ||
9371 gameMode == IcsObserving ||
9372 gameMode == IcsExamining);
9374 if (!isIcsGame || whosays == GE_ICS) {
9375 /* OK -- not an ICS game, or ICS said it was done */
9377 if (!isIcsGame && !appData.noChessProgram)
9378 SetUserThinkingEnables();
9380 /* [HGM] if a machine claims the game end we verify this claim */
9381 if(gameMode == TwoMachinesPlay && appData.testClaims) {
9382 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
9384 ChessMove trueResult = (ChessMove) -1;
9386 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
9387 first.twoMachinesColor[0] :
9388 second.twoMachinesColor[0] ;
9390 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
9391 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
9392 /* [HGM] verify: engine mate claims accepted if they were flagged */
9393 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
9395 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
9396 /* [HGM] verify: engine mate claims accepted if they were flagged */
9397 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
9399 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
9400 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
9403 // now verify win claims, but not in drop games, as we don't understand those yet
9404 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
9405 || gameInfo.variant == VariantGreat) &&
9406 (result == WhiteWins && claimer == 'w' ||
9407 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
9408 if (appData.debugMode) {
9409 fprintf(debugFP, "result=%d sp=%d move=%d\n",
9410 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
9412 if(result != trueResult) {
9413 snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
9414 result = claimer == 'w' ? BlackWins : WhiteWins;
9415 resultDetails = buf;
9418 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
9419 && (forwardMostMove <= backwardMostMove ||
9420 (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
9421 (claimer=='b')==(forwardMostMove&1))
9423 /* [HGM] verify: draws that were not flagged are false claims */
9424 snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
9425 result = claimer == 'w' ? BlackWins : WhiteWins;
9426 resultDetails = buf;
9428 /* (Claiming a loss is accepted no questions asked!) */
9430 /* [HGM] bare: don't allow bare King to win */
9431 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
9432 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
9433 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
9434 && result != GameIsDrawn)
9435 { int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
9436 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
9437 int p = (signed char)boards[forwardMostMove][i][j] - color;
9438 if(p >= 0 && p <= (int)WhiteKing) k++;
9440 if (appData.debugMode) {
9441 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
9442 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
9445 result = GameIsDrawn;
9446 snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
9447 resultDetails = buf;
9453 if(serverMoves != NULL && !loadFlag) { char c = '=';
9454 if(result==WhiteWins) c = '+';
9455 if(result==BlackWins) c = '-';
9456 if(resultDetails != NULL)
9457 fprintf(serverMoves, ";%c;%s\n", c, resultDetails);
9459 if (resultDetails != NULL) {
9460 gameInfo.result = result;
9461 gameInfo.resultDetails = StrSave(resultDetails);
9463 /* display last move only if game was not loaded from file */
9464 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
9465 DisplayMove(currentMove - 1);
9467 if (forwardMostMove != 0) {
9468 if (gameMode != PlayFromGameFile && gameMode != EditGame
9469 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
9471 if (*appData.saveGameFile != NULLCHAR) {
9472 SaveGameToFile(appData.saveGameFile, TRUE);
9473 } else if (appData.autoSaveGames) {
9476 if (*appData.savePositionFile != NULLCHAR) {
9477 SavePositionToFile(appData.savePositionFile);
9482 /* Tell program how game ended in case it is learning */
9483 /* [HGM] Moved this to after saving the PGN, just in case */
9484 /* engine died and we got here through time loss. In that */
9485 /* case we will get a fatal error writing the pipe, which */
9486 /* would otherwise lose us the PGN. */
9487 /* [HGM] crash: not needed anymore, but doesn't hurt; */
9488 /* output during GameEnds should never be fatal anymore */
9489 if (gameMode == MachinePlaysWhite ||
9490 gameMode == MachinePlaysBlack ||
9491 gameMode == TwoMachinesPlay ||
9492 gameMode == IcsPlayingWhite ||
9493 gameMode == IcsPlayingBlack ||
9494 gameMode == BeginningOfGame) {
9496 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
9498 if (first.pr != NoProc) {
9499 SendToProgram(buf, &first);
9501 if (second.pr != NoProc &&
9502 gameMode == TwoMachinesPlay) {
9503 SendToProgram(buf, &second);
9508 if (appData.icsActive) {
9509 if (appData.quietPlay &&
9510 (gameMode == IcsPlayingWhite ||
9511 gameMode == IcsPlayingBlack)) {
9512 SendToICS(ics_prefix);
9513 SendToICS("set shout 1\n");
9515 nextGameMode = IcsIdle;
9516 ics_user_moved = FALSE;
9517 /* clean up premove. It's ugly when the game has ended and the
9518 * premove highlights are still on the board.
9522 ClearPremoveHighlights();
9523 DrawPosition(FALSE, boards[currentMove]);
9525 if (whosays == GE_ICS) {
9528 if (gameMode == IcsPlayingWhite)
9530 else if(gameMode == IcsPlayingBlack)
9534 if (gameMode == IcsPlayingBlack)
9536 else if(gameMode == IcsPlayingWhite)
9543 PlayIcsUnfinishedSound();
9546 } else if (gameMode == EditGame ||
9547 gameMode == PlayFromGameFile ||
9548 gameMode == AnalyzeMode ||
9549 gameMode == AnalyzeFile) {
9550 nextGameMode = gameMode;
9552 nextGameMode = EndOfGame;
9557 nextGameMode = gameMode;
9560 if (appData.noChessProgram) {
9561 gameMode = nextGameMode;
9563 endingGame = 0; /* [HGM] crash */
9568 /* Put first chess program into idle state */
9569 if (first.pr != NoProc &&
9570 (gameMode == MachinePlaysWhite ||
9571 gameMode == MachinePlaysBlack ||
9572 gameMode == TwoMachinesPlay ||
9573 gameMode == IcsPlayingWhite ||
9574 gameMode == IcsPlayingBlack ||
9575 gameMode == BeginningOfGame)) {
9576 SendToProgram("force\n", &first);
9577 if (first.usePing) {
9579 snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
9580 SendToProgram(buf, &first);
9583 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
9584 /* Kill off first chess program */
9585 if (first.isr != NULL)
9586 RemoveInputSource(first.isr);
9589 if (first.pr != NoProc) {
9591 DoSleep( appData.delayBeforeQuit );
9592 SendToProgram("quit\n", &first);
9593 DoSleep( appData.delayAfterQuit );
9594 DestroyChildProcess(first.pr, first.useSigterm);
9599 /* Put second chess program into idle state */
9600 if (second.pr != NoProc &&
9601 gameMode == TwoMachinesPlay) {
9602 SendToProgram("force\n", &second);
9603 if (second.usePing) {
9605 snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
9606 SendToProgram(buf, &second);
9609 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
9610 /* Kill off second chess program */
9611 if (second.isr != NULL)
9612 RemoveInputSource(second.isr);
9615 if (second.pr != NoProc) {
9616 DoSleep( appData.delayBeforeQuit );
9617 SendToProgram("quit\n", &second);
9618 DoSleep( appData.delayAfterQuit );
9619 DestroyChildProcess(second.pr, second.useSigterm);
9624 if (matchMode && gameMode == TwoMachinesPlay) {
9627 if (first.twoMachinesColor[0] == 'w') {
9634 if (first.twoMachinesColor[0] == 'b') {
9643 if (matchGame < appData.matchGames) {
9645 if(appData.sameColorGames <= 1) { /* [HGM] alternate: suppress color swap */
9646 tmp = first.twoMachinesColor;
9647 first.twoMachinesColor = second.twoMachinesColor;
9648 second.twoMachinesColor = tmp;
9650 gameMode = nextGameMode;
9652 if(appData.matchPause>10000 || appData.matchPause<10)
9653 appData.matchPause = 10000; /* [HGM] make pause adjustable */
9654 ScheduleDelayedEvent(NextMatchGame, appData.matchPause);
9655 endingGame = 0; /* [HGM] crash */
9658 gameMode = nextGameMode;
9659 snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
9660 first.tidy, second.tidy,
9661 first.matchWins, second.matchWins,
9662 appData.matchGames - (first.matchWins + second.matchWins));
9663 popupRequested++; // [HGM] crash: postpone to after resetting endingGame
9664 if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
9665 first.twoMachinesColor = "black\n";
9666 second.twoMachinesColor = "white\n";
9668 first.twoMachinesColor = "white\n";
9669 second.twoMachinesColor = "black\n";
9673 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
9674 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
9676 gameMode = nextGameMode;
9678 endingGame = 0; /* [HGM] crash */
9679 if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
9680 if(matchMode == TRUE) DisplayFatalError(buf, 0, 0); else {
9681 matchMode = FALSE; appData.matchGames = matchGame = 0;
9687 /* Assumes program was just initialized (initString sent).
9688 Leaves program in force mode. */
9690 FeedMovesToProgram(cps, upto)
9691 ChessProgramState *cps;
9696 if (appData.debugMode)
9697 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
9698 startedFromSetupPosition ? "position and " : "",
9699 backwardMostMove, upto, cps->which);
9700 if(currentlyInitializedVariant != gameInfo.variant) {
9702 // [HGM] variantswitch: make engine aware of new variant
9703 if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL)
9704 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
9705 snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
9706 SendToProgram(buf, cps);
9707 currentlyInitializedVariant = gameInfo.variant;
9709 SendToProgram("force\n", cps);
9710 if (startedFromSetupPosition) {
9711 SendBoard(cps, backwardMostMove);
9712 if (appData.debugMode) {
9713 fprintf(debugFP, "feedMoves\n");
9716 for (i = backwardMostMove; i < upto; i++) {
9717 SendMoveToProgram(i, cps);
9723 ResurrectChessProgram()
9725 /* The chess program may have exited.
9726 If so, restart it and feed it all the moves made so far. */
9728 if (appData.noChessProgram || first.pr != NoProc) return;
9730 StartChessProgram(&first);
9731 InitChessProgram(&first, FALSE);
9732 FeedMovesToProgram(&first, currentMove);
9734 if (!first.sendTime) {
9735 /* can't tell gnuchess what its clock should read,
9736 so we bow to its notion. */
9738 timeRemaining[0][currentMove] = whiteTimeRemaining;
9739 timeRemaining[1][currentMove] = blackTimeRemaining;
9742 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
9743 appData.icsEngineAnalyze) && first.analysisSupport) {
9744 SendToProgram("analyze\n", &first);
9745 first.analyzing = TRUE;
9758 if (appData.debugMode) {
9759 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
9760 redraw, init, gameMode);
9762 CleanupTail(); // [HGM] vari: delete any stored variations
9763 pausing = pauseExamInvalid = FALSE;
9764 startedFromSetupPosition = blackPlaysFirst = FALSE;
9766 whiteFlag = blackFlag = FALSE;
9767 userOfferedDraw = FALSE;
9768 hintRequested = bookRequested = FALSE;
9769 first.maybeThinking = FALSE;
9770 second.maybeThinking = FALSE;
9771 first.bookSuspend = FALSE; // [HGM] book
9772 second.bookSuspend = FALSE;
9773 thinkOutput[0] = NULLCHAR;
9774 lastHint[0] = NULLCHAR;
9775 ClearGameInfo(&gameInfo);
9776 gameInfo.variant = StringToVariant(appData.variant);
9777 ics_user_moved = ics_clock_paused = FALSE;
9778 ics_getting_history = H_FALSE;
9780 white_holding[0] = black_holding[0] = NULLCHAR;
9781 ClearProgramStats();
9782 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
9786 flipView = appData.flipView;
9787 ClearPremoveHighlights();
9789 alarmSounded = FALSE;
9791 GameEnds(EndOfFile, NULL, GE_PLAYER);
9792 if(appData.serverMovesName != NULL) {
9793 /* [HGM] prepare to make moves file for broadcasting */
9794 clock_t t = clock();
9795 if(serverMoves != NULL) fclose(serverMoves);
9796 serverMoves = fopen(appData.serverMovesName, "r");
9797 if(serverMoves != NULL) {
9798 fclose(serverMoves);
9799 /* delay 15 sec before overwriting, so all clients can see end */
9800 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
9802 serverMoves = fopen(appData.serverMovesName, "w");
9806 gameMode = BeginningOfGame;
9808 if(appData.icsActive) gameInfo.variant = VariantNormal;
9809 currentMove = forwardMostMove = backwardMostMove = 0;
9810 InitPosition(redraw);
9811 for (i = 0; i < MAX_MOVES; i++) {
9812 if (commentList[i] != NULL) {
9813 free(commentList[i]);
9814 commentList[i] = NULL;
9818 timeRemaining[0][0] = whiteTimeRemaining;
9819 timeRemaining[1][0] = blackTimeRemaining;
9820 if (first.pr == NULL) {
9821 StartChessProgram(&first);
9824 InitChessProgram(&first, startedFromSetupPosition);
9827 DisplayMessage("", "");
9828 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
9829 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
9836 if (!AutoPlayOneMove())
9838 if (matchMode || appData.timeDelay == 0)
9840 if (appData.timeDelay < 0)
9842 StartLoadGameTimer((long)(1000.0 * appData.timeDelay));
9851 int fromX, fromY, toX, toY;
9853 if (appData.debugMode) {
9854 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
9857 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
9860 if (gameMode == AnalyzeFile && currentMove > backwardMostMove) {
9861 pvInfoList[currentMove].depth = programStats.depth;
9862 pvInfoList[currentMove].score = programStats.score;
9863 pvInfoList[currentMove].time = 0;
9864 if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
9867 if (currentMove >= forwardMostMove) {
9868 if(gameMode == AnalyzeFile) { ExitAnalyzeMode(); SendToProgram("force\n", &first); }
9869 gameMode = EditGame;
9872 /* [AS] Clear current move marker at the end of a game */
9873 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
9878 toX = moveList[currentMove][2] - AAA;
9879 toY = moveList[currentMove][3] - ONE;
9881 if (moveList[currentMove][1] == '@') {
9882 if (appData.highlightLastMove) {
9883 SetHighlights(-1, -1, toX, toY);
9886 fromX = moveList[currentMove][0] - AAA;
9887 fromY = moveList[currentMove][1] - ONE;
9889 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
9891 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
9893 if (appData.highlightLastMove) {
9894 SetHighlights(fromX, fromY, toX, toY);
9897 DisplayMove(currentMove);
9898 SendMoveToProgram(currentMove++, &first);
9899 DisplayBothClocks();
9900 DrawPosition(FALSE, boards[currentMove]);
9901 // [HGM] PV info: always display, routine tests if empty
9902 DisplayComment(currentMove - 1, commentList[currentMove]);
9908 LoadGameOneMove(readAhead)
9909 ChessMove readAhead;
9911 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
9912 char promoChar = NULLCHAR;
9917 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
9918 gameMode != AnalyzeMode && gameMode != Training) {
9923 yyboardindex = forwardMostMove;
9924 if (readAhead != EndOfFile) {
9925 moveType = readAhead;
9927 if (gameFileFP == NULL)
9929 moveType = (ChessMove) Myylex();
9935 if (appData.debugMode)
9936 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
9939 /* append the comment but don't display it */
9940 AppendComment(currentMove, p, FALSE);
9943 case WhiteCapturesEnPassant:
9944 case BlackCapturesEnPassant:
9945 case WhitePromotion:
9946 case BlackPromotion:
9947 case WhiteNonPromotion:
9948 case BlackNonPromotion:
9950 case WhiteKingSideCastle:
9951 case WhiteQueenSideCastle:
9952 case BlackKingSideCastle:
9953 case BlackQueenSideCastle:
9954 case WhiteKingSideCastleWild:
9955 case WhiteQueenSideCastleWild:
9956 case BlackKingSideCastleWild:
9957 case BlackQueenSideCastleWild:
9959 case WhiteHSideCastleFR:
9960 case WhiteASideCastleFR:
9961 case BlackHSideCastleFR:
9962 case BlackASideCastleFR:
9964 if (appData.debugMode)
9965 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
9966 fromX = currentMoveString[0] - AAA;
9967 fromY = currentMoveString[1] - ONE;
9968 toX = currentMoveString[2] - AAA;
9969 toY = currentMoveString[3] - ONE;
9970 promoChar = currentMoveString[4];
9975 if (appData.debugMode)
9976 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
9977 fromX = moveType == WhiteDrop ?
9978 (int) CharToPiece(ToUpper(currentMoveString[0])) :
9979 (int) CharToPiece(ToLower(currentMoveString[0]));
9981 toX = currentMoveString[2] - AAA;
9982 toY = currentMoveString[3] - ONE;
9988 case GameUnfinished:
9989 if (appData.debugMode)
9990 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
9991 p = strchr(yy_text, '{');
9992 if (p == NULL) p = strchr(yy_text, '(');
9995 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
9997 q = strchr(p, *p == '{' ? '}' : ')');
9998 if (q != NULL) *q = NULLCHAR;
10001 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
10002 GameEnds(moveType, p, GE_FILE);
10004 if (cmailMsgLoaded) {
10006 flipView = WhiteOnMove(currentMove);
10007 if (moveType == GameUnfinished) flipView = !flipView;
10008 if (appData.debugMode)
10009 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
10014 if (appData.debugMode)
10015 fprintf(debugFP, "Parser hit end of file\n");
10016 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
10022 if (WhiteOnMove(currentMove)) {
10023 GameEnds(BlackWins, "Black mates", GE_FILE);
10025 GameEnds(WhiteWins, "White mates", GE_FILE);
10029 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
10035 case MoveNumberOne:
10036 if (lastLoadGameStart == GNUChessGame) {
10037 /* GNUChessGames have numbers, but they aren't move numbers */
10038 if (appData.debugMode)
10039 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
10040 yy_text, (int) moveType);
10041 return LoadGameOneMove(EndOfFile); /* tail recursion */
10043 /* else fall thru */
10048 /* Reached start of next game in file */
10049 if (appData.debugMode)
10050 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
10051 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
10057 if (WhiteOnMove(currentMove)) {
10058 GameEnds(BlackWins, "Black mates", GE_FILE);
10060 GameEnds(WhiteWins, "White mates", GE_FILE);
10064 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
10070 case PositionDiagram: /* should not happen; ignore */
10071 case ElapsedTime: /* ignore */
10072 case NAG: /* ignore */
10073 if (appData.debugMode)
10074 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
10075 yy_text, (int) moveType);
10076 return LoadGameOneMove(EndOfFile); /* tail recursion */
10079 if (appData.testLegality) {
10080 if (appData.debugMode)
10081 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
10082 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
10083 (forwardMostMove / 2) + 1,
10084 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10085 DisplayError(move, 0);
10088 if (appData.debugMode)
10089 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
10090 yy_text, currentMoveString);
10091 fromX = currentMoveString[0] - AAA;
10092 fromY = currentMoveString[1] - ONE;
10093 toX = currentMoveString[2] - AAA;
10094 toY = currentMoveString[3] - ONE;
10095 promoChar = currentMoveString[4];
10099 case AmbiguousMove:
10100 if (appData.debugMode)
10101 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
10102 snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
10103 (forwardMostMove / 2) + 1,
10104 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10105 DisplayError(move, 0);
10110 case ImpossibleMove:
10111 if (appData.debugMode)
10112 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
10113 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
10114 (forwardMostMove / 2) + 1,
10115 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10116 DisplayError(move, 0);
10122 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
10123 DrawPosition(FALSE, boards[currentMove]);
10124 DisplayBothClocks();
10125 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
10126 DisplayComment(currentMove - 1, commentList[currentMove]);
10128 (void) StopLoadGameTimer();
10130 cmailOldMove = forwardMostMove;
10133 /* currentMoveString is set as a side-effect of yylex */
10135 thinkOutput[0] = NULLCHAR;
10136 MakeMove(fromX, fromY, toX, toY, promoChar);
10137 currentMove = forwardMostMove;
10142 /* Load the nth game from the given file */
10144 LoadGameFromFile(filename, n, title, useList)
10148 /*Boolean*/ int useList;
10153 if (strcmp(filename, "-") == 0) {
10157 f = fopen(filename, "rb");
10159 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10160 DisplayError(buf, errno);
10164 if (fseek(f, 0, 0) == -1) {
10165 /* f is not seekable; probably a pipe */
10168 if (useList && n == 0) {
10169 int error = GameListBuild(f);
10171 DisplayError(_("Cannot build game list"), error);
10172 } else if (!ListEmpty(&gameList) &&
10173 ((ListGame *) gameList.tailPred)->number > 1) {
10174 GameListPopUp(f, title);
10181 return LoadGame(f, n, title, FALSE);
10186 MakeRegisteredMove()
10188 int fromX, fromY, toX, toY;
10190 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
10191 switch (cmailMoveType[lastLoadGameNumber - 1]) {
10194 if (appData.debugMode)
10195 fprintf(debugFP, "Restoring %s for game %d\n",
10196 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
10198 thinkOutput[0] = NULLCHAR;
10199 safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
10200 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
10201 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
10202 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
10203 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
10204 promoChar = cmailMove[lastLoadGameNumber - 1][4];
10205 MakeMove(fromX, fromY, toX, toY, promoChar);
10206 ShowMove(fromX, fromY, toX, toY);
10208 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
10215 if (WhiteOnMove(currentMove)) {
10216 GameEnds(BlackWins, "Black mates", GE_PLAYER);
10218 GameEnds(WhiteWins, "White mates", GE_PLAYER);
10223 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
10230 if (WhiteOnMove(currentMove)) {
10231 GameEnds(BlackWins, "White resigns", GE_PLAYER);
10233 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
10238 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
10249 /* Wrapper around LoadGame for use when a Cmail message is loaded */
10251 CmailLoadGame(f, gameNumber, title, useList)
10259 if (gameNumber > nCmailGames) {
10260 DisplayError(_("No more games in this message"), 0);
10263 if (f == lastLoadGameFP) {
10264 int offset = gameNumber - lastLoadGameNumber;
10266 cmailMsg[0] = NULLCHAR;
10267 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
10268 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
10269 nCmailMovesRegistered--;
10271 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
10272 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
10273 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
10276 if (! RegisterMove()) return FALSE;
10280 retVal = LoadGame(f, gameNumber, title, useList);
10282 /* Make move registered during previous look at this game, if any */
10283 MakeRegisteredMove();
10285 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
10286 commentList[currentMove]
10287 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
10288 DisplayComment(currentMove - 1, commentList[currentMove]);
10294 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
10299 int gameNumber = lastLoadGameNumber + offset;
10300 if (lastLoadGameFP == NULL) {
10301 DisplayError(_("No game has been loaded yet"), 0);
10304 if (gameNumber <= 0) {
10305 DisplayError(_("Can't back up any further"), 0);
10308 if (cmailMsgLoaded) {
10309 return CmailLoadGame(lastLoadGameFP, gameNumber,
10310 lastLoadGameTitle, lastLoadGameUseList);
10312 return LoadGame(lastLoadGameFP, gameNumber,
10313 lastLoadGameTitle, lastLoadGameUseList);
10319 /* Load the nth game from open file f */
10321 LoadGame(f, gameNumber, title, useList)
10329 int gn = gameNumber;
10330 ListGame *lg = NULL;
10331 int numPGNTags = 0;
10333 GameMode oldGameMode;
10334 VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
10336 if (appData.debugMode)
10337 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
10339 if (gameMode == Training )
10340 SetTrainingModeOff();
10342 oldGameMode = gameMode;
10343 if (gameMode != BeginningOfGame) {
10344 Reset(FALSE, TRUE);
10348 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
10349 fclose(lastLoadGameFP);
10353 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
10356 fseek(f, lg->offset, 0);
10357 GameListHighlight(gameNumber);
10361 DisplayError(_("Game number out of range"), 0);
10366 if (fseek(f, 0, 0) == -1) {
10367 if (f == lastLoadGameFP ?
10368 gameNumber == lastLoadGameNumber + 1 :
10372 DisplayError(_("Can't seek on game file"), 0);
10377 lastLoadGameFP = f;
10378 lastLoadGameNumber = gameNumber;
10379 safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
10380 lastLoadGameUseList = useList;
10384 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
10385 snprintf(buf, sizeof(buf), "%s vs. %s", lg->gameInfo.white,
10386 lg->gameInfo.black);
10388 } else if (*title != NULLCHAR) {
10389 if (gameNumber > 1) {
10390 snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
10393 DisplayTitle(title);
10397 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
10398 gameMode = PlayFromGameFile;
10402 currentMove = forwardMostMove = backwardMostMove = 0;
10403 CopyBoard(boards[0], initialPosition);
10407 * Skip the first gn-1 games in the file.
10408 * Also skip over anything that precedes an identifiable
10409 * start of game marker, to avoid being confused by
10410 * garbage at the start of the file. Currently
10411 * recognized start of game markers are the move number "1",
10412 * the pattern "gnuchess .* game", the pattern
10413 * "^[#;%] [^ ]* game file", and a PGN tag block.
10414 * A game that starts with one of the latter two patterns
10415 * will also have a move number 1, possibly
10416 * following a position diagram.
10417 * 5-4-02: Let's try being more lenient and allowing a game to
10418 * start with an unnumbered move. Does that break anything?
10420 cm = lastLoadGameStart = EndOfFile;
10422 yyboardindex = forwardMostMove;
10423 cm = (ChessMove) Myylex();
10426 if (cmailMsgLoaded) {
10427 nCmailGames = CMAIL_MAX_GAMES - gn;
10430 DisplayError(_("Game not found in file"), 0);
10437 lastLoadGameStart = cm;
10440 case MoveNumberOne:
10441 switch (lastLoadGameStart) {
10446 case MoveNumberOne:
10448 gn--; /* count this game */
10449 lastLoadGameStart = cm;
10458 switch (lastLoadGameStart) {
10461 case MoveNumberOne:
10463 gn--; /* count this game */
10464 lastLoadGameStart = cm;
10467 lastLoadGameStart = cm; /* game counted already */
10475 yyboardindex = forwardMostMove;
10476 cm = (ChessMove) Myylex();
10477 } while (cm == PGNTag || cm == Comment);
10484 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
10485 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
10486 != CMAIL_OLD_RESULT) {
10488 cmailResult[ CMAIL_MAX_GAMES
10489 - gn - 1] = CMAIL_OLD_RESULT;
10495 /* Only a NormalMove can be at the start of a game
10496 * without a position diagram. */
10497 if (lastLoadGameStart == EndOfFile ) {
10499 lastLoadGameStart = MoveNumberOne;
10508 if (appData.debugMode)
10509 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
10511 if (cm == XBoardGame) {
10512 /* Skip any header junk before position diagram and/or move 1 */
10514 yyboardindex = forwardMostMove;
10515 cm = (ChessMove) Myylex();
10517 if (cm == EndOfFile ||
10518 cm == GNUChessGame || cm == XBoardGame) {
10519 /* Empty game; pretend end-of-file and handle later */
10524 if (cm == MoveNumberOne || cm == PositionDiagram ||
10525 cm == PGNTag || cm == Comment)
10528 } else if (cm == GNUChessGame) {
10529 if (gameInfo.event != NULL) {
10530 free(gameInfo.event);
10532 gameInfo.event = StrSave(yy_text);
10535 startedFromSetupPosition = FALSE;
10536 while (cm == PGNTag) {
10537 if (appData.debugMode)
10538 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
10539 err = ParsePGNTag(yy_text, &gameInfo);
10540 if (!err) numPGNTags++;
10542 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
10543 if(gameInfo.variant != oldVariant) {
10544 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
10545 ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
10546 InitPosition(TRUE);
10547 oldVariant = gameInfo.variant;
10548 if (appData.debugMode)
10549 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
10553 if (gameInfo.fen != NULL) {
10554 Board initial_position;
10555 startedFromSetupPosition = TRUE;
10556 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
10558 DisplayError(_("Bad FEN position in file"), 0);
10561 CopyBoard(boards[0], initial_position);
10562 if (blackPlaysFirst) {
10563 currentMove = forwardMostMove = backwardMostMove = 1;
10564 CopyBoard(boards[1], initial_position);
10565 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10566 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10567 timeRemaining[0][1] = whiteTimeRemaining;
10568 timeRemaining[1][1] = blackTimeRemaining;
10569 if (commentList[0] != NULL) {
10570 commentList[1] = commentList[0];
10571 commentList[0] = NULL;
10574 currentMove = forwardMostMove = backwardMostMove = 0;
10576 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
10578 initialRulePlies = FENrulePlies;
10579 for( i=0; i< nrCastlingRights; i++ )
10580 initialRights[i] = initial_position[CASTLING][i];
10582 yyboardindex = forwardMostMove;
10583 free(gameInfo.fen);
10584 gameInfo.fen = NULL;
10587 yyboardindex = forwardMostMove;
10588 cm = (ChessMove) Myylex();
10590 /* Handle comments interspersed among the tags */
10591 while (cm == Comment) {
10593 if (appData.debugMode)
10594 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10596 AppendComment(currentMove, p, FALSE);
10597 yyboardindex = forwardMostMove;
10598 cm = (ChessMove) Myylex();
10602 /* don't rely on existence of Event tag since if game was
10603 * pasted from clipboard the Event tag may not exist
10605 if (numPGNTags > 0){
10607 if (gameInfo.variant == VariantNormal) {
10608 VariantClass v = StringToVariant(gameInfo.event);
10609 // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
10610 if(v < VariantShogi) gameInfo.variant = v;
10613 if( appData.autoDisplayTags ) {
10614 tags = PGNTags(&gameInfo);
10615 TagsPopUp(tags, CmailMsg());
10620 /* Make something up, but don't display it now */
10625 if (cm == PositionDiagram) {
10628 Board initial_position;
10630 if (appData.debugMode)
10631 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
10633 if (!startedFromSetupPosition) {
10635 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
10636 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
10647 initial_position[i][j++] = CharToPiece(*p);
10650 while (*p == ' ' || *p == '\t' ||
10651 *p == '\n' || *p == '\r') p++;
10653 if (strncmp(p, "black", strlen("black"))==0)
10654 blackPlaysFirst = TRUE;
10656 blackPlaysFirst = FALSE;
10657 startedFromSetupPosition = TRUE;
10659 CopyBoard(boards[0], initial_position);
10660 if (blackPlaysFirst) {
10661 currentMove = forwardMostMove = backwardMostMove = 1;
10662 CopyBoard(boards[1], initial_position);
10663 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10664 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10665 timeRemaining[0][1] = whiteTimeRemaining;
10666 timeRemaining[1][1] = blackTimeRemaining;
10667 if (commentList[0] != NULL) {
10668 commentList[1] = commentList[0];
10669 commentList[0] = NULL;
10672 currentMove = forwardMostMove = backwardMostMove = 0;
10675 yyboardindex = forwardMostMove;
10676 cm = (ChessMove) Myylex();
10679 if (first.pr == NoProc) {
10680 StartChessProgram(&first);
10682 InitChessProgram(&first, FALSE);
10683 SendToProgram("force\n", &first);
10684 if (startedFromSetupPosition) {
10685 SendBoard(&first, forwardMostMove);
10686 if (appData.debugMode) {
10687 fprintf(debugFP, "Load Game\n");
10689 DisplayBothClocks();
10692 /* [HGM] server: flag to write setup moves in broadcast file as one */
10693 loadFlag = appData.suppressLoadMoves;
10695 while (cm == Comment) {
10697 if (appData.debugMode)
10698 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10700 AppendComment(currentMove, p, FALSE);
10701 yyboardindex = forwardMostMove;
10702 cm = (ChessMove) Myylex();
10705 if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
10706 cm == WhiteWins || cm == BlackWins ||
10707 cm == GameIsDrawn || cm == GameUnfinished) {
10708 DisplayMessage("", _("No moves in game"));
10709 if (cmailMsgLoaded) {
10710 if (appData.debugMode)
10711 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
10715 DrawPosition(FALSE, boards[currentMove]);
10716 DisplayBothClocks();
10717 gameMode = EditGame;
10724 // [HGM] PV info: routine tests if comment empty
10725 if (!matchMode && (pausing || appData.timeDelay != 0)) {
10726 DisplayComment(currentMove - 1, commentList[currentMove]);
10728 if (!matchMode && appData.timeDelay != 0)
10729 DrawPosition(FALSE, boards[currentMove]);
10731 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
10732 programStats.ok_to_send = 1;
10735 /* if the first token after the PGN tags is a move
10736 * and not move number 1, retrieve it from the parser
10738 if (cm != MoveNumberOne)
10739 LoadGameOneMove(cm);
10741 /* load the remaining moves from the file */
10742 while (LoadGameOneMove(EndOfFile)) {
10743 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
10744 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
10747 /* rewind to the start of the game */
10748 currentMove = backwardMostMove;
10750 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
10752 if (oldGameMode == AnalyzeFile ||
10753 oldGameMode == AnalyzeMode) {
10754 AnalyzeFileEvent();
10757 if (matchMode || appData.timeDelay == 0) {
10759 gameMode = EditGame;
10761 } else if (appData.timeDelay > 0) {
10762 AutoPlayGameLoop();
10765 if (appData.debugMode)
10766 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
10768 loadFlag = 0; /* [HGM] true game starts */
10772 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
10774 ReloadPosition(offset)
10777 int positionNumber = lastLoadPositionNumber + offset;
10778 if (lastLoadPositionFP == NULL) {
10779 DisplayError(_("No position has been loaded yet"), 0);
10782 if (positionNumber <= 0) {
10783 DisplayError(_("Can't back up any further"), 0);
10786 return LoadPosition(lastLoadPositionFP, positionNumber,
10787 lastLoadPositionTitle);
10790 /* Load the nth position from the given file */
10792 LoadPositionFromFile(filename, n, title)
10800 if (strcmp(filename, "-") == 0) {
10801 return LoadPosition(stdin, n, "stdin");
10803 f = fopen(filename, "rb");
10805 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10806 DisplayError(buf, errno);
10809 return LoadPosition(f, n, title);
10814 /* Load the nth position from the given open file, and close it */
10816 LoadPosition(f, positionNumber, title)
10818 int positionNumber;
10821 char *p, line[MSG_SIZ];
10822 Board initial_position;
10823 int i, j, fenMode, pn;
10825 if (gameMode == Training )
10826 SetTrainingModeOff();
10828 if (gameMode != BeginningOfGame) {
10829 Reset(FALSE, TRUE);
10831 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
10832 fclose(lastLoadPositionFP);
10834 if (positionNumber == 0) positionNumber = 1;
10835 lastLoadPositionFP = f;
10836 lastLoadPositionNumber = positionNumber;
10837 safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
10838 if (first.pr == NoProc) {
10839 StartChessProgram(&first);
10840 InitChessProgram(&first, FALSE);
10842 pn = positionNumber;
10843 if (positionNumber < 0) {
10844 /* Negative position number means to seek to that byte offset */
10845 if (fseek(f, -positionNumber, 0) == -1) {
10846 DisplayError(_("Can't seek on position file"), 0);
10851 if (fseek(f, 0, 0) == -1) {
10852 if (f == lastLoadPositionFP ?
10853 positionNumber == lastLoadPositionNumber + 1 :
10854 positionNumber == 1) {
10857 DisplayError(_("Can't seek on position file"), 0);
10862 /* See if this file is FEN or old-style xboard */
10863 if (fgets(line, MSG_SIZ, f) == NULL) {
10864 DisplayError(_("Position not found in file"), 0);
10867 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
10868 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
10871 if (fenMode || line[0] == '#') pn--;
10873 /* skip positions before number pn */
10874 if (fgets(line, MSG_SIZ, f) == NULL) {
10876 DisplayError(_("Position not found in file"), 0);
10879 if (fenMode || line[0] == '#') pn--;
10884 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
10885 DisplayError(_("Bad FEN position in file"), 0);
10889 (void) fgets(line, MSG_SIZ, f);
10890 (void) fgets(line, MSG_SIZ, f);
10892 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
10893 (void) fgets(line, MSG_SIZ, f);
10894 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
10897 initial_position[i][j++] = CharToPiece(*p);
10901 blackPlaysFirst = FALSE;
10903 (void) fgets(line, MSG_SIZ, f);
10904 if (strncmp(line, "black", strlen("black"))==0)
10905 blackPlaysFirst = TRUE;
10908 startedFromSetupPosition = TRUE;
10910 SendToProgram("force\n", &first);
10911 CopyBoard(boards[0], initial_position);
10912 if (blackPlaysFirst) {
10913 currentMove = forwardMostMove = backwardMostMove = 1;
10914 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10915 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10916 CopyBoard(boards[1], initial_position);
10917 DisplayMessage("", _("Black to play"));
10919 currentMove = forwardMostMove = backwardMostMove = 0;
10920 DisplayMessage("", _("White to play"));
10922 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
10923 SendBoard(&first, forwardMostMove);
10924 if (appData.debugMode) {
10926 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
10927 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
10928 fprintf(debugFP, "Load Position\n");
10931 if (positionNumber > 1) {
10932 snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
10933 DisplayTitle(line);
10935 DisplayTitle(title);
10937 gameMode = EditGame;
10940 timeRemaining[0][1] = whiteTimeRemaining;
10941 timeRemaining[1][1] = blackTimeRemaining;
10942 DrawPosition(FALSE, boards[currentMove]);
10949 CopyPlayerNameIntoFileName(dest, src)
10952 while (*src != NULLCHAR && *src != ',') {
10957 *(*dest)++ = *src++;
10962 char *DefaultFileName(ext)
10965 static char def[MSG_SIZ];
10968 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
10970 CopyPlayerNameIntoFileName(&p, gameInfo.white);
10972 CopyPlayerNameIntoFileName(&p, gameInfo.black);
10974 safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
10981 /* Save the current game to the given file */
10983 SaveGameToFile(filename, append)
10991 if (strcmp(filename, "-") == 0) {
10992 return SaveGame(stdout, 0, NULL);
10994 f = fopen(filename, append ? "a" : "w");
10996 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10997 DisplayError(buf, errno);
11000 safeStrCpy(buf, lastMsg, MSG_SIZ);
11001 DisplayMessage(_("Waiting for access to save file"), "");
11002 flock(fileno(f), LOCK_EX); // [HGM] lock: lock file while we are writing
11003 DisplayMessage(_("Saving game"), "");
11004 if(lseek(fileno(f), 0, SEEK_END) == -1) DisplayError("Bad Seek", errno); // better safe than sorry...
11005 result = SaveGame(f, 0, NULL);
11006 DisplayMessage(buf, "");
11016 static char buf[MSG_SIZ];
11019 p = strchr(str, ' ');
11020 if (p == NULL) return str;
11021 strncpy(buf, str, p - str);
11022 buf[p - str] = NULLCHAR;
11026 #define PGN_MAX_LINE 75
11028 #define PGN_SIDE_WHITE 0
11029 #define PGN_SIDE_BLACK 1
11032 static int FindFirstMoveOutOfBook( int side )
11036 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
11037 int index = backwardMostMove;
11038 int has_book_hit = 0;
11040 if( (index % 2) != side ) {
11044 while( index < forwardMostMove ) {
11045 /* Check to see if engine is in book */
11046 int depth = pvInfoList[index].depth;
11047 int score = pvInfoList[index].score;
11053 else if( score == 0 && depth == 63 ) {
11054 in_book = 1; /* Zappa */
11056 else if( score == 2 && depth == 99 ) {
11057 in_book = 1; /* Abrok */
11060 has_book_hit += in_book;
11076 void GetOutOfBookInfo( char * buf )
11080 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
11082 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
11083 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
11087 if( oob[0] >= 0 || oob[1] >= 0 ) {
11088 for( i=0; i<2; i++ ) {
11092 if( i > 0 && oob[0] >= 0 ) {
11093 strcat( buf, " " );
11096 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
11097 sprintf( buf+strlen(buf), "%s%.2f",
11098 pvInfoList[idx].score >= 0 ? "+" : "",
11099 pvInfoList[idx].score / 100.0 );
11105 /* Save game in PGN style and close the file */
11110 int i, offset, linelen, newblock;
11114 int movelen, numlen, blank;
11115 char move_buffer[100]; /* [AS] Buffer for move+PV info */
11117 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
11119 tm = time((time_t *) NULL);
11121 PrintPGNTags(f, &gameInfo);
11123 if (backwardMostMove > 0 || startedFromSetupPosition) {
11124 char *fen = PositionToFEN(backwardMostMove, NULL);
11125 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
11126 fprintf(f, "\n{--------------\n");
11127 PrintPosition(f, backwardMostMove);
11128 fprintf(f, "--------------}\n");
11132 /* [AS] Out of book annotation */
11133 if( appData.saveOutOfBookInfo ) {
11136 GetOutOfBookInfo( buf );
11138 if( buf[0] != '\0' ) {
11139 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
11146 i = backwardMostMove;
11150 while (i < forwardMostMove) {
11151 /* Print comments preceding this move */
11152 if (commentList[i] != NULL) {
11153 if (linelen > 0) fprintf(f, "\n");
11154 fprintf(f, "%s", commentList[i]);
11159 /* Format move number */
11161 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
11164 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
11166 numtext[0] = NULLCHAR;
11168 numlen = strlen(numtext);
11171 /* Print move number */
11172 blank = linelen > 0 && numlen > 0;
11173 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
11182 fprintf(f, "%s", numtext);
11186 safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
11187 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
11190 blank = linelen > 0 && movelen > 0;
11191 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
11200 fprintf(f, "%s", move_buffer);
11201 linelen += movelen;
11203 /* [AS] Add PV info if present */
11204 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
11205 /* [HGM] add time */
11206 char buf[MSG_SIZ]; int seconds;
11208 seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
11214 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
11217 seconds = (seconds + 4)/10; // round to full seconds
11219 snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
11221 snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
11224 snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
11225 pvInfoList[i].score >= 0 ? "+" : "",
11226 pvInfoList[i].score / 100.0,
11227 pvInfoList[i].depth,
11230 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
11232 /* Print score/depth */
11233 blank = linelen > 0 && movelen > 0;
11234 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
11243 fprintf(f, "%s", move_buffer);
11244 linelen += movelen;
11250 /* Start a new line */
11251 if (linelen > 0) fprintf(f, "\n");
11253 /* Print comments after last move */
11254 if (commentList[i] != NULL) {
11255 fprintf(f, "%s\n", commentList[i]);
11259 if (gameInfo.resultDetails != NULL &&
11260 gameInfo.resultDetails[0] != NULLCHAR) {
11261 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
11262 PGNResult(gameInfo.result));
11264 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
11268 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
11272 /* Save game in old style and close the file */
11274 SaveGameOldStyle(f)
11280 tm = time((time_t *) NULL);
11282 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
11285 if (backwardMostMove > 0 || startedFromSetupPosition) {
11286 fprintf(f, "\n[--------------\n");
11287 PrintPosition(f, backwardMostMove);
11288 fprintf(f, "--------------]\n");
11293 i = backwardMostMove;
11294 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
11296 while (i < forwardMostMove) {
11297 if (commentList[i] != NULL) {
11298 fprintf(f, "[%s]\n", commentList[i]);
11301 if ((i % 2) == 1) {
11302 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
11305 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
11307 if (commentList[i] != NULL) {
11311 if (i >= forwardMostMove) {
11315 fprintf(f, "%s\n", parseList[i]);
11320 if (commentList[i] != NULL) {
11321 fprintf(f, "[%s]\n", commentList[i]);
11324 /* This isn't really the old style, but it's close enough */
11325 if (gameInfo.resultDetails != NULL &&
11326 gameInfo.resultDetails[0] != NULLCHAR) {
11327 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
11328 gameInfo.resultDetails);
11330 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
11337 /* Save the current game to open file f and close the file */
11339 SaveGame(f, dummy, dummy2)
11344 if (gameMode == EditPosition) EditPositionDone(TRUE);
11345 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
11346 if (appData.oldSaveStyle)
11347 return SaveGameOldStyle(f);
11349 return SaveGamePGN(f);
11352 /* Save the current position to the given file */
11354 SavePositionToFile(filename)
11360 if (strcmp(filename, "-") == 0) {
11361 return SavePosition(stdout, 0, NULL);
11363 f = fopen(filename, "a");
11365 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
11366 DisplayError(buf, errno);
11369 safeStrCpy(buf, lastMsg, MSG_SIZ);
11370 DisplayMessage(_("Waiting for access to save file"), "");
11371 flock(fileno(f), LOCK_EX); // [HGM] lock
11372 DisplayMessage(_("Saving position"), "");
11373 lseek(fileno(f), 0, SEEK_END); // better safe than sorry...
11374 SavePosition(f, 0, NULL);
11375 DisplayMessage(buf, "");
11381 /* Save the current position to the given open file and close the file */
11383 SavePosition(f, dummy, dummy2)
11391 if (gameMode == EditPosition) EditPositionDone(TRUE);
11392 if (appData.oldSaveStyle) {
11393 tm = time((time_t *) NULL);
11395 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
11397 fprintf(f, "[--------------\n");
11398 PrintPosition(f, currentMove);
11399 fprintf(f, "--------------]\n");
11401 fen = PositionToFEN(currentMove, NULL);
11402 fprintf(f, "%s\n", fen);
11410 ReloadCmailMsgEvent(unregister)
11414 static char *inFilename = NULL;
11415 static char *outFilename;
11417 struct stat inbuf, outbuf;
11420 /* Any registered moves are unregistered if unregister is set, */
11421 /* i.e. invoked by the signal handler */
11423 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
11424 cmailMoveRegistered[i] = FALSE;
11425 if (cmailCommentList[i] != NULL) {
11426 free(cmailCommentList[i]);
11427 cmailCommentList[i] = NULL;
11430 nCmailMovesRegistered = 0;
11433 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
11434 cmailResult[i] = CMAIL_NOT_RESULT;
11438 if (inFilename == NULL) {
11439 /* Because the filenames are static they only get malloced once */
11440 /* and they never get freed */
11441 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
11442 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
11444 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
11445 sprintf(outFilename, "%s.out", appData.cmailGameName);
11448 status = stat(outFilename, &outbuf);
11450 cmailMailedMove = FALSE;
11452 status = stat(inFilename, &inbuf);
11453 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
11456 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
11457 counts the games, notes how each one terminated, etc.
11459 It would be nice to remove this kludge and instead gather all
11460 the information while building the game list. (And to keep it
11461 in the game list nodes instead of having a bunch of fixed-size
11462 parallel arrays.) Note this will require getting each game's
11463 termination from the PGN tags, as the game list builder does
11464 not process the game moves. --mann
11466 cmailMsgLoaded = TRUE;
11467 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
11469 /* Load first game in the file or popup game menu */
11470 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
11472 #endif /* !WIN32 */
11480 char string[MSG_SIZ];
11482 if ( cmailMailedMove
11483 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
11484 return TRUE; /* Allow free viewing */
11487 /* Unregister move to ensure that we don't leave RegisterMove */
11488 /* with the move registered when the conditions for registering no */
11490 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11491 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
11492 nCmailMovesRegistered --;
11494 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
11496 free(cmailCommentList[lastLoadGameNumber - 1]);
11497 cmailCommentList[lastLoadGameNumber - 1] = NULL;
11501 if (cmailOldMove == -1) {
11502 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
11506 if (currentMove > cmailOldMove + 1) {
11507 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
11511 if (currentMove < cmailOldMove) {
11512 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
11516 if (forwardMostMove > currentMove) {
11517 /* Silently truncate extra moves */
11521 if ( (currentMove == cmailOldMove + 1)
11522 || ( (currentMove == cmailOldMove)
11523 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
11524 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
11525 if (gameInfo.result != GameUnfinished) {
11526 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
11529 if (commentList[currentMove] != NULL) {
11530 cmailCommentList[lastLoadGameNumber - 1]
11531 = StrSave(commentList[currentMove]);
11533 safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
11535 if (appData.debugMode)
11536 fprintf(debugFP, "Saving %s for game %d\n",
11537 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
11539 snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
11541 f = fopen(string, "w");
11542 if (appData.oldSaveStyle) {
11543 SaveGameOldStyle(f); /* also closes the file */
11545 snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
11546 f = fopen(string, "w");
11547 SavePosition(f, 0, NULL); /* also closes the file */
11549 fprintf(f, "{--------------\n");
11550 PrintPosition(f, currentMove);
11551 fprintf(f, "--------------}\n\n");
11553 SaveGame(f, 0, NULL); /* also closes the file*/
11556 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
11557 nCmailMovesRegistered ++;
11558 } else if (nCmailGames == 1) {
11559 DisplayError(_("You have not made a move yet"), 0);
11570 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
11571 FILE *commandOutput;
11572 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
11573 int nBytes = 0; /* Suppress warnings on uninitialized variables */
11579 if (! cmailMsgLoaded) {
11580 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
11584 if (nCmailGames == nCmailResults) {
11585 DisplayError(_("No unfinished games"), 0);
11589 #if CMAIL_PROHIBIT_REMAIL
11590 if (cmailMailedMove) {
11591 snprintf(msg, MSG_SIZ, _("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);
11592 DisplayError(msg, 0);
11597 if (! (cmailMailedMove || RegisterMove())) return;
11599 if ( cmailMailedMove
11600 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
11601 snprintf(string, MSG_SIZ, partCommandString,
11602 appData.debugMode ? " -v" : "", appData.cmailGameName);
11603 commandOutput = popen(string, "r");
11605 if (commandOutput == NULL) {
11606 DisplayError(_("Failed to invoke cmail"), 0);
11608 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
11609 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
11611 if (nBuffers > 1) {
11612 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
11613 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
11614 nBytes = MSG_SIZ - 1;
11616 (void) memcpy(msg, buffer, nBytes);
11618 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
11620 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
11621 cmailMailedMove = TRUE; /* Prevent >1 moves */
11624 for (i = 0; i < nCmailGames; i ++) {
11625 if (cmailResult[i] == CMAIL_NOT_RESULT) {
11630 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
11632 snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
11634 appData.cmailGameName,
11636 LoadGameFromFile(buffer, 1, buffer, FALSE);
11637 cmailMsgLoaded = FALSE;
11641 DisplayInformation(msg);
11642 pclose(commandOutput);
11645 if ((*cmailMsg) != '\0') {
11646 DisplayInformation(cmailMsg);
11651 #endif /* !WIN32 */
11660 int prependComma = 0;
11662 char string[MSG_SIZ]; /* Space for game-list */
11665 if (!cmailMsgLoaded) return "";
11667 if (cmailMailedMove) {
11668 snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
11670 /* Create a list of games left */
11671 snprintf(string, MSG_SIZ, "[");
11672 for (i = 0; i < nCmailGames; i ++) {
11673 if (! ( cmailMoveRegistered[i]
11674 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
11675 if (prependComma) {
11676 snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
11678 snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
11682 strcat(string, number);
11685 strcat(string, "]");
11687 if (nCmailMovesRegistered + nCmailResults == 0) {
11688 switch (nCmailGames) {
11690 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
11694 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
11698 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
11703 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
11705 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
11710 if (nCmailResults == nCmailGames) {
11711 snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
11713 snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
11718 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
11730 if (gameMode == Training)
11731 SetTrainingModeOff();
11734 cmailMsgLoaded = FALSE;
11735 if (appData.icsActive) {
11736 SendToICS(ics_prefix);
11737 SendToICS("refresh\n");
11747 /* Give up on clean exit */
11751 /* Keep trying for clean exit */
11755 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
11757 if (telnetISR != NULL) {
11758 RemoveInputSource(telnetISR);
11760 if (icsPR != NoProc) {
11761 DestroyChildProcess(icsPR, TRUE);
11764 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
11765 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
11767 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
11768 /* make sure this other one finishes before killing it! */
11769 if(endingGame) { int count = 0;
11770 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
11771 while(endingGame && count++ < 10) DoSleep(1);
11772 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
11775 /* Kill off chess programs */
11776 if (first.pr != NoProc) {
11779 DoSleep( appData.delayBeforeQuit );
11780 SendToProgram("quit\n", &first);
11781 DoSleep( appData.delayAfterQuit );
11782 DestroyChildProcess(first.pr, 10 /* [AS] first.useSigterm */ );
11784 if (second.pr != NoProc) {
11785 DoSleep( appData.delayBeforeQuit );
11786 SendToProgram("quit\n", &second);
11787 DoSleep( appData.delayAfterQuit );
11788 DestroyChildProcess(second.pr, 10 /* [AS] second.useSigterm */ );
11790 if (first.isr != NULL) {
11791 RemoveInputSource(first.isr);
11793 if (second.isr != NULL) {
11794 RemoveInputSource(second.isr);
11797 ShutDownFrontEnd();
11804 if (appData.debugMode)
11805 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
11809 if (gameMode == MachinePlaysWhite ||
11810 gameMode == MachinePlaysBlack) {
11813 DisplayBothClocks();
11815 if (gameMode == PlayFromGameFile) {
11816 if (appData.timeDelay >= 0)
11817 AutoPlayGameLoop();
11818 } else if (gameMode == IcsExamining && pauseExamInvalid) {
11819 Reset(FALSE, TRUE);
11820 SendToICS(ics_prefix);
11821 SendToICS("refresh\n");
11822 } else if (currentMove < forwardMostMove) {
11823 ForwardInner(forwardMostMove);
11825 pauseExamInvalid = FALSE;
11827 switch (gameMode) {
11831 pauseExamForwardMostMove = forwardMostMove;
11832 pauseExamInvalid = FALSE;
11835 case IcsPlayingWhite:
11836 case IcsPlayingBlack:
11840 case PlayFromGameFile:
11841 (void) StopLoadGameTimer();
11845 case BeginningOfGame:
11846 if (appData.icsActive) return;
11847 /* else fall through */
11848 case MachinePlaysWhite:
11849 case MachinePlaysBlack:
11850 case TwoMachinesPlay:
11851 if (forwardMostMove == 0)
11852 return; /* don't pause if no one has moved */
11853 if ((gameMode == MachinePlaysWhite &&
11854 !WhiteOnMove(forwardMostMove)) ||
11855 (gameMode == MachinePlaysBlack &&
11856 WhiteOnMove(forwardMostMove))) {
11869 char title[MSG_SIZ];
11871 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
11872 safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
11874 snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
11875 WhiteOnMove(currentMove - 1) ? " " : ".. ",
11876 parseList[currentMove - 1]);
11879 EditCommentPopUp(currentMove, title, commentList[currentMove]);
11886 char *tags = PGNTags(&gameInfo);
11887 EditTagsPopUp(tags, NULL);
11894 if (appData.noChessProgram || gameMode == AnalyzeMode)
11897 if (gameMode != AnalyzeFile) {
11898 if (!appData.icsEngineAnalyze) {
11900 if (gameMode != EditGame) return;
11902 ResurrectChessProgram();
11903 SendToProgram("analyze\n", &first);
11904 first.analyzing = TRUE;
11905 /*first.maybeThinking = TRUE;*/
11906 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11907 EngineOutputPopUp();
11909 if (!appData.icsEngineAnalyze) gameMode = AnalyzeMode;
11914 StartAnalysisClock();
11915 GetTimeMark(&lastNodeCountTime);
11922 if (appData.noChessProgram || gameMode == AnalyzeFile)
11925 if (gameMode != AnalyzeMode) {
11927 if (gameMode != EditGame) return;
11928 ResurrectChessProgram();
11929 SendToProgram("analyze\n", &first);
11930 first.analyzing = TRUE;
11931 /*first.maybeThinking = TRUE;*/
11932 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11933 EngineOutputPopUp();
11935 gameMode = AnalyzeFile;
11940 StartAnalysisClock();
11941 GetTimeMark(&lastNodeCountTime);
11946 MachineWhiteEvent()
11949 char *bookHit = NULL;
11951 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
11955 if (gameMode == PlayFromGameFile ||
11956 gameMode == TwoMachinesPlay ||
11957 gameMode == Training ||
11958 gameMode == AnalyzeMode ||
11959 gameMode == EndOfGame)
11962 if (gameMode == EditPosition)
11963 EditPositionDone(TRUE);
11965 if (!WhiteOnMove(currentMove)) {
11966 DisplayError(_("It is not White's turn"), 0);
11970 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
11973 if (gameMode == EditGame || gameMode == AnalyzeMode ||
11974 gameMode == AnalyzeFile)
11977 ResurrectChessProgram(); /* in case it isn't running */
11978 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
11979 gameMode = MachinePlaysWhite;
11982 gameMode = MachinePlaysWhite;
11986 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
11988 if (first.sendName) {
11989 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
11990 SendToProgram(buf, &first);
11992 if (first.sendTime) {
11993 if (first.useColors) {
11994 SendToProgram("black\n", &first); /*gnu kludge*/
11996 SendTimeRemaining(&first, TRUE);
11998 if (first.useColors) {
11999 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
12001 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
12002 SetMachineThinkingEnables();
12003 first.maybeThinking = TRUE;
12007 if (appData.autoFlipView && !flipView) {
12008 flipView = !flipView;
12009 DrawPosition(FALSE, NULL);
12010 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
12013 if(bookHit) { // [HGM] book: simulate book reply
12014 static char bookMove[MSG_SIZ]; // a bit generous?
12016 programStats.nodes = programStats.depth = programStats.time =
12017 programStats.score = programStats.got_only_move = 0;
12018 sprintf(programStats.movelist, "%s (xbook)", bookHit);
12020 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
12021 strcat(bookMove, bookHit);
12022 HandleMachineMove(bookMove, &first);
12027 MachineBlackEvent()
12030 char *bookHit = NULL;
12032 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
12036 if (gameMode == PlayFromGameFile ||
12037 gameMode == TwoMachinesPlay ||
12038 gameMode == Training ||
12039 gameMode == AnalyzeMode ||
12040 gameMode == EndOfGame)
12043 if (gameMode == EditPosition)
12044 EditPositionDone(TRUE);
12046 if (WhiteOnMove(currentMove)) {
12047 DisplayError(_("It is not Black's turn"), 0);
12051 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
12054 if (gameMode == EditGame || gameMode == AnalyzeMode ||
12055 gameMode == AnalyzeFile)
12058 ResurrectChessProgram(); /* in case it isn't running */
12059 gameMode = MachinePlaysBlack;
12063 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
12065 if (first.sendName) {
12066 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
12067 SendToProgram(buf, &first);
12069 if (first.sendTime) {
12070 if (first.useColors) {
12071 SendToProgram("white\n", &first); /*gnu kludge*/
12073 SendTimeRemaining(&first, FALSE);
12075 if (first.useColors) {
12076 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
12078 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
12079 SetMachineThinkingEnables();
12080 first.maybeThinking = TRUE;
12083 if (appData.autoFlipView && flipView) {
12084 flipView = !flipView;
12085 DrawPosition(FALSE, NULL);
12086 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
12088 if(bookHit) { // [HGM] book: simulate book reply
12089 static char bookMove[MSG_SIZ]; // a bit generous?
12091 programStats.nodes = programStats.depth = programStats.time =
12092 programStats.score = programStats.got_only_move = 0;
12093 sprintf(programStats.movelist, "%s (xbook)", bookHit);
12095 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
12096 strcat(bookMove, bookHit);
12097 HandleMachineMove(bookMove, &first);
12103 DisplayTwoMachinesTitle()
12106 if (appData.matchGames > 0) {
12107 if (first.twoMachinesColor[0] == 'w') {
12108 snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
12109 gameInfo.white, gameInfo.black,
12110 first.matchWins, second.matchWins,
12111 matchGame - 1 - (first.matchWins + second.matchWins));
12113 snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
12114 gameInfo.white, gameInfo.black,
12115 second.matchWins, first.matchWins,
12116 matchGame - 1 - (first.matchWins + second.matchWins));
12119 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
12125 SettingsMenuIfReady()
12127 if (second.lastPing != second.lastPong) {
12128 DisplayMessage("", _("Waiting for second chess program"));
12129 ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
12133 DisplayMessage("", "");
12134 SettingsPopUp(&second);
12138 WaitForEngine(ChessProgramState *cps, DelayedEventCallback retry)
12141 if (cps->pr == NULL) {
12142 StartChessProgram(cps);
12143 if (cps->protocolVersion == 1) {
12146 /* kludge: allow timeout for initial "feature" command */
12148 snprintf(buf, MSG_SIZ, _("Starting %s chess program"), cps->which);
12149 DisplayMessage("", buf);
12150 ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
12158 TwoMachinesEvent P((void))
12162 ChessProgramState *onmove;
12163 char *bookHit = NULL;
12164 static int stalling = 0;
12166 if (appData.noChessProgram) return;
12168 switch (gameMode) {
12169 case TwoMachinesPlay:
12171 case MachinePlaysWhite:
12172 case MachinePlaysBlack:
12173 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
12174 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
12178 case BeginningOfGame:
12179 case PlayFromGameFile:
12182 if (gameMode != EditGame) return;
12185 EditPositionDone(TRUE);
12196 // forwardMostMove = currentMove;
12197 TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
12198 ResurrectChessProgram(); /* in case first program isn't running */
12200 if(WaitForEngine(&second, TwoMachinesEventIfReady)) return;
12201 if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
12202 DisplayMessage("", _("Waiting for first chess program"));
12203 ScheduleDelayedEvent(TwoMachinesEvent, 10);
12207 InitChessProgram(&second, FALSE);
12208 SendToProgram("force\n", &second);
12210 if(second.lastPing != second.lastPong) { // [HGM] second engine might have to reallocate hash
12211 if(!stalling) DisplayMessage("", _("Waiting for second chess program"));
12213 ScheduleDelayedEvent(TwoMachinesEvent, 10);
12217 DisplayMessage("", "");
12218 if (startedFromSetupPosition) {
12219 SendBoard(&second, backwardMostMove);
12220 if (appData.debugMode) {
12221 fprintf(debugFP, "Two Machines\n");
12224 for (i = backwardMostMove; i < forwardMostMove; i++) {
12225 SendMoveToProgram(i, &second);
12228 gameMode = TwoMachinesPlay;
12232 DisplayTwoMachinesTitle();
12234 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
12240 SendToProgram(first.computerString, &first);
12241 if (first.sendName) {
12242 snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
12243 SendToProgram(buf, &first);
12245 SendToProgram(second.computerString, &second);
12246 if (second.sendName) {
12247 snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
12248 SendToProgram(buf, &second);
12252 if (!first.sendTime || !second.sendTime) {
12253 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
12254 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
12256 if (onmove->sendTime) {
12257 if (onmove->useColors) {
12258 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
12260 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
12262 if (onmove->useColors) {
12263 SendToProgram(onmove->twoMachinesColor, onmove);
12265 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
12266 // SendToProgram("go\n", onmove);
12267 onmove->maybeThinking = TRUE;
12268 SetMachineThinkingEnables();
12272 if(bookHit) { // [HGM] book: simulate book reply
12273 static char bookMove[MSG_SIZ]; // a bit generous?
12275 programStats.nodes = programStats.depth = programStats.time =
12276 programStats.score = programStats.got_only_move = 0;
12277 sprintf(programStats.movelist, "%s (xbook)", bookHit);
12279 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
12280 strcat(bookMove, bookHit);
12281 savedMessage = bookMove; // args for deferred call
12282 savedState = onmove;
12283 ScheduleDelayedEvent(DeferredBookMove, 1);
12290 if (gameMode == Training) {
12291 SetTrainingModeOff();
12292 gameMode = PlayFromGameFile;
12293 DisplayMessage("", _("Training mode off"));
12295 gameMode = Training;
12296 animateTraining = appData.animate;
12298 /* make sure we are not already at the end of the game */
12299 if (currentMove < forwardMostMove) {
12300 SetTrainingModeOn();
12301 DisplayMessage("", _("Training mode on"));
12303 gameMode = PlayFromGameFile;
12304 DisplayError(_("Already at end of game"), 0);
12313 if (!appData.icsActive) return;
12314 switch (gameMode) {
12315 case IcsPlayingWhite:
12316 case IcsPlayingBlack:
12319 case BeginningOfGame:
12327 EditPositionDone(TRUE);
12340 gameMode = IcsIdle;
12351 switch (gameMode) {
12353 SetTrainingModeOff();
12355 case MachinePlaysWhite:
12356 case MachinePlaysBlack:
12357 case BeginningOfGame:
12358 SendToProgram("force\n", &first);
12359 SetUserThinkingEnables();
12361 case PlayFromGameFile:
12362 (void) StopLoadGameTimer();
12363 if (gameFileFP != NULL) {
12368 EditPositionDone(TRUE);
12373 SendToProgram("force\n", &first);
12375 case TwoMachinesPlay:
12376 GameEnds(EndOfFile, NULL, GE_PLAYER);
12377 ResurrectChessProgram();
12378 SetUserThinkingEnables();
12381 ResurrectChessProgram();
12383 case IcsPlayingBlack:
12384 case IcsPlayingWhite:
12385 DisplayError(_("Warning: You are still playing a game"), 0);
12388 DisplayError(_("Warning: You are still observing a game"), 0);
12391 DisplayError(_("Warning: You are still examining a game"), 0);
12402 first.offeredDraw = second.offeredDraw = 0;
12404 if (gameMode == PlayFromGameFile) {
12405 whiteTimeRemaining = timeRemaining[0][currentMove];
12406 blackTimeRemaining = timeRemaining[1][currentMove];
12410 if (gameMode == MachinePlaysWhite ||
12411 gameMode == MachinePlaysBlack ||
12412 gameMode == TwoMachinesPlay ||
12413 gameMode == EndOfGame) {
12414 i = forwardMostMove;
12415 while (i > currentMove) {
12416 SendToProgram("undo\n", &first);
12419 whiteTimeRemaining = timeRemaining[0][currentMove];
12420 blackTimeRemaining = timeRemaining[1][currentMove];
12421 DisplayBothClocks();
12422 if (whiteFlag || blackFlag) {
12423 whiteFlag = blackFlag = 0;
12428 gameMode = EditGame;
12435 EditPositionEvent()
12437 if (gameMode == EditPosition) {
12443 if (gameMode != EditGame) return;
12445 gameMode = EditPosition;
12448 if (currentMove > 0)
12449 CopyBoard(boards[0], boards[currentMove]);
12451 blackPlaysFirst = !WhiteOnMove(currentMove);
12453 currentMove = forwardMostMove = backwardMostMove = 0;
12454 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12461 /* [DM] icsEngineAnalyze - possible call from other functions */
12462 if (appData.icsEngineAnalyze) {
12463 appData.icsEngineAnalyze = FALSE;
12465 DisplayMessage("",_("Close ICS engine analyze..."));
12467 if (first.analysisSupport && first.analyzing) {
12468 SendToProgram("exit\n", &first);
12469 first.analyzing = FALSE;
12471 thinkOutput[0] = NULLCHAR;
12475 EditPositionDone(Boolean fakeRights)
12477 int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
12479 startedFromSetupPosition = TRUE;
12480 InitChessProgram(&first, FALSE);
12481 if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
12482 boards[0][EP_STATUS] = EP_NONE;
12483 boards[0][CASTLING][2] = boards[0][CASTLING][5] = BOARD_WIDTH>>1;
12484 if(boards[0][0][BOARD_WIDTH>>1] == king) {
12485 boards[0][CASTLING][1] = boards[0][0][BOARD_LEFT] == WhiteRook ? 0 : NoRights;
12486 boards[0][CASTLING][0] = boards[0][0][BOARD_RGHT-1] == WhiteRook ? BOARD_RGHT-1 : NoRights;
12487 } else boards[0][CASTLING][2] = NoRights;
12488 if(boards[0][BOARD_HEIGHT-1][BOARD_WIDTH>>1] == WHITE_TO_BLACK king) {
12489 boards[0][CASTLING][4] = boards[0][BOARD_HEIGHT-1][BOARD_LEFT] == BlackRook ? 0 : NoRights;
12490 boards[0][CASTLING][3] = boards[0][BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook ? BOARD_RGHT-1 : NoRights;
12491 } else boards[0][CASTLING][5] = NoRights;
12493 SendToProgram("force\n", &first);
12494 if (blackPlaysFirst) {
12495 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12496 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12497 currentMove = forwardMostMove = backwardMostMove = 1;
12498 CopyBoard(boards[1], boards[0]);
12500 currentMove = forwardMostMove = backwardMostMove = 0;
12502 SendBoard(&first, forwardMostMove);
12503 if (appData.debugMode) {
12504 fprintf(debugFP, "EditPosDone\n");
12507 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
12508 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
12509 gameMode = EditGame;
12511 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12512 ClearHighlights(); /* [AS] */
12515 /* Pause for `ms' milliseconds */
12516 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
12526 } while (SubtractTimeMarks(&m2, &m1) < ms);
12529 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
12531 SendMultiLineToICS(buf)
12534 char temp[MSG_SIZ+1], *p;
12541 strncpy(temp, buf, len);
12546 if (*p == '\n' || *p == '\r')
12551 strcat(temp, "\n");
12553 SendToPlayer(temp, strlen(temp));
12557 SetWhiteToPlayEvent()
12559 if (gameMode == EditPosition) {
12560 blackPlaysFirst = FALSE;
12561 DisplayBothClocks(); /* works because currentMove is 0 */
12562 } else if (gameMode == IcsExamining) {
12563 SendToICS(ics_prefix);
12564 SendToICS("tomove white\n");
12569 SetBlackToPlayEvent()
12571 if (gameMode == EditPosition) {
12572 blackPlaysFirst = TRUE;
12573 currentMove = 1; /* kludge */
12574 DisplayBothClocks();
12576 } else if (gameMode == IcsExamining) {
12577 SendToICS(ics_prefix);
12578 SendToICS("tomove black\n");
12583 EditPositionMenuEvent(selection, x, y)
12584 ChessSquare selection;
12588 ChessSquare piece = boards[0][y][x];
12590 if (gameMode != EditPosition && gameMode != IcsExamining) return;
12592 switch (selection) {
12594 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
12595 SendToICS(ics_prefix);
12596 SendToICS("bsetup clear\n");
12597 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
12598 SendToICS(ics_prefix);
12599 SendToICS("clearboard\n");
12601 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
12602 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
12603 for (y = 0; y < BOARD_HEIGHT; y++) {
12604 if (gameMode == IcsExamining) {
12605 if (boards[currentMove][y][x] != EmptySquare) {
12606 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
12611 boards[0][y][x] = p;
12616 if (gameMode == EditPosition) {
12617 DrawPosition(FALSE, boards[0]);
12622 SetWhiteToPlayEvent();
12626 SetBlackToPlayEvent();
12630 if (gameMode == IcsExamining) {
12631 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
12632 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
12635 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
12636 if(x == BOARD_LEFT-2) {
12637 if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
12638 boards[0][y][1] = 0;
12640 if(x == BOARD_RGHT+1) {
12641 if(y >= gameInfo.holdingsSize) break;
12642 boards[0][y][BOARD_WIDTH-2] = 0;
12645 boards[0][y][x] = EmptySquare;
12646 DrawPosition(FALSE, boards[0]);
12651 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
12652 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
12653 selection = (ChessSquare) (PROMOTED piece);
12654 } else if(piece == EmptySquare) selection = WhiteSilver;
12655 else selection = (ChessSquare)((int)piece - 1);
12659 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
12660 piece > (int)BlackMan && piece <= (int)BlackKing ) {
12661 selection = (ChessSquare) (DEMOTED piece);
12662 } else if(piece == EmptySquare) selection = BlackSilver;
12663 else selection = (ChessSquare)((int)piece + 1);
12668 if(gameInfo.variant == VariantShatranj ||
12669 gameInfo.variant == VariantXiangqi ||
12670 gameInfo.variant == VariantCourier ||
12671 gameInfo.variant == VariantMakruk )
12672 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
12677 if(gameInfo.variant == VariantXiangqi)
12678 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
12679 if(gameInfo.variant == VariantKnightmate)
12680 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
12683 if (gameMode == IcsExamining) {
12684 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
12685 snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
12686 PieceToChar(selection), AAA + x, ONE + y);
12689 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
12691 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
12692 n = PieceToNumber(selection - BlackPawn);
12693 if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
12694 boards[0][BOARD_HEIGHT-1-n][0] = selection;
12695 boards[0][BOARD_HEIGHT-1-n][1]++;
12697 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
12698 n = PieceToNumber(selection);
12699 if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
12700 boards[0][n][BOARD_WIDTH-1] = selection;
12701 boards[0][n][BOARD_WIDTH-2]++;
12704 boards[0][y][x] = selection;
12705 DrawPosition(TRUE, boards[0]);
12713 DropMenuEvent(selection, x, y)
12714 ChessSquare selection;
12717 ChessMove moveType;
12719 switch (gameMode) {
12720 case IcsPlayingWhite:
12721 case MachinePlaysBlack:
12722 if (!WhiteOnMove(currentMove)) {
12723 DisplayMoveError(_("It is Black's turn"));
12726 moveType = WhiteDrop;
12728 case IcsPlayingBlack:
12729 case MachinePlaysWhite:
12730 if (WhiteOnMove(currentMove)) {
12731 DisplayMoveError(_("It is White's turn"));
12734 moveType = BlackDrop;
12737 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
12743 if (moveType == BlackDrop && selection < BlackPawn) {
12744 selection = (ChessSquare) ((int) selection
12745 + (int) BlackPawn - (int) WhitePawn);
12747 if (boards[currentMove][y][x] != EmptySquare) {
12748 DisplayMoveError(_("That square is occupied"));
12752 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
12758 /* Accept a pending offer of any kind from opponent */
12760 if (appData.icsActive) {
12761 SendToICS(ics_prefix);
12762 SendToICS("accept\n");
12763 } else if (cmailMsgLoaded) {
12764 if (currentMove == cmailOldMove &&
12765 commentList[cmailOldMove] != NULL &&
12766 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12767 "Black offers a draw" : "White offers a draw")) {
12769 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12770 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
12772 DisplayError(_("There is no pending offer on this move"), 0);
12773 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12776 /* Not used for offers from chess program */
12783 /* Decline a pending offer of any kind from opponent */
12785 if (appData.icsActive) {
12786 SendToICS(ics_prefix);
12787 SendToICS("decline\n");
12788 } else if (cmailMsgLoaded) {
12789 if (currentMove == cmailOldMove &&
12790 commentList[cmailOldMove] != NULL &&
12791 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12792 "Black offers a draw" : "White offers a draw")) {
12794 AppendComment(cmailOldMove, "Draw declined", TRUE);
12795 DisplayComment(cmailOldMove - 1, "Draw declined");
12798 DisplayError(_("There is no pending offer on this move"), 0);
12801 /* Not used for offers from chess program */
12808 /* Issue ICS rematch command */
12809 if (appData.icsActive) {
12810 SendToICS(ics_prefix);
12811 SendToICS("rematch\n");
12818 /* Call your opponent's flag (claim a win on time) */
12819 if (appData.icsActive) {
12820 SendToICS(ics_prefix);
12821 SendToICS("flag\n");
12823 switch (gameMode) {
12826 case MachinePlaysWhite:
12829 GameEnds(GameIsDrawn, "Both players ran out of time",
12832 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
12834 DisplayError(_("Your opponent is not out of time"), 0);
12837 case MachinePlaysBlack:
12840 GameEnds(GameIsDrawn, "Both players ran out of time",
12843 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
12845 DisplayError(_("Your opponent is not out of time"), 0);
12853 ClockClick(int which)
12854 { // [HGM] code moved to back-end from winboard.c
12855 if(which) { // black clock
12856 if (gameMode == EditPosition || gameMode == IcsExamining) {
12857 if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
12858 SetBlackToPlayEvent();
12859 } else if (gameMode == EditGame || shiftKey) {
12860 AdjustClock(which, -1);
12861 } else if (gameMode == IcsPlayingWhite ||
12862 gameMode == MachinePlaysBlack) {
12865 } else { // white clock
12866 if (gameMode == EditPosition || gameMode == IcsExamining) {
12867 if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
12868 SetWhiteToPlayEvent();
12869 } else if (gameMode == EditGame || shiftKey) {
12870 AdjustClock(which, -1);
12871 } else if (gameMode == IcsPlayingBlack ||
12872 gameMode == MachinePlaysWhite) {
12881 /* Offer draw or accept pending draw offer from opponent */
12883 if (appData.icsActive) {
12884 /* Note: tournament rules require draw offers to be
12885 made after you make your move but before you punch
12886 your clock. Currently ICS doesn't let you do that;
12887 instead, you immediately punch your clock after making
12888 a move, but you can offer a draw at any time. */
12890 SendToICS(ics_prefix);
12891 SendToICS("draw\n");
12892 userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
12893 } else if (cmailMsgLoaded) {
12894 if (currentMove == cmailOldMove &&
12895 commentList[cmailOldMove] != NULL &&
12896 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12897 "Black offers a draw" : "White offers a draw")) {
12898 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12899 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
12900 } else if (currentMove == cmailOldMove + 1) {
12901 char *offer = WhiteOnMove(cmailOldMove) ?
12902 "White offers a draw" : "Black offers a draw";
12903 AppendComment(currentMove, offer, TRUE);
12904 DisplayComment(currentMove - 1, offer);
12905 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
12907 DisplayError(_("You must make your move before offering a draw"), 0);
12908 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12910 } else if (first.offeredDraw) {
12911 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
12913 if (first.sendDrawOffers) {
12914 SendToProgram("draw\n", &first);
12915 userOfferedDraw = TRUE;
12923 /* Offer Adjourn or accept pending Adjourn offer from opponent */
12925 if (appData.icsActive) {
12926 SendToICS(ics_prefix);
12927 SendToICS("adjourn\n");
12929 /* Currently GNU Chess doesn't offer or accept Adjourns */
12937 /* Offer Abort or accept pending Abort offer from opponent */
12939 if (appData.icsActive) {
12940 SendToICS(ics_prefix);
12941 SendToICS("abort\n");
12943 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
12950 /* Resign. You can do this even if it's not your turn. */
12952 if (appData.icsActive) {
12953 SendToICS(ics_prefix);
12954 SendToICS("resign\n");
12956 switch (gameMode) {
12957 case MachinePlaysWhite:
12958 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12960 case MachinePlaysBlack:
12961 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12964 if (cmailMsgLoaded) {
12966 if (WhiteOnMove(cmailOldMove)) {
12967 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12969 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12971 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
12982 StopObservingEvent()
12984 /* Stop observing current games */
12985 SendToICS(ics_prefix);
12986 SendToICS("unobserve\n");
12990 StopExaminingEvent()
12992 /* Stop observing current game */
12993 SendToICS(ics_prefix);
12994 SendToICS("unexamine\n");
12998 ForwardInner(target)
13003 if (appData.debugMode)
13004 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
13005 target, currentMove, forwardMostMove);
13007 if (gameMode == EditPosition)
13010 if (gameMode == PlayFromGameFile && !pausing)
13013 if (gameMode == IcsExamining && pausing)
13014 limit = pauseExamForwardMostMove;
13016 limit = forwardMostMove;
13018 if (target > limit) target = limit;
13020 if (target > 0 && moveList[target - 1][0]) {
13021 int fromX, fromY, toX, toY;
13022 toX = moveList[target - 1][2] - AAA;
13023 toY = moveList[target - 1][3] - ONE;
13024 if (moveList[target - 1][1] == '@') {
13025 if (appData.highlightLastMove) {
13026 SetHighlights(-1, -1, toX, toY);
13029 fromX = moveList[target - 1][0] - AAA;
13030 fromY = moveList[target - 1][1] - ONE;
13031 if (target == currentMove + 1) {
13032 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
13034 if (appData.highlightLastMove) {
13035 SetHighlights(fromX, fromY, toX, toY);
13039 if (gameMode == EditGame || gameMode == AnalyzeMode ||
13040 gameMode == Training || gameMode == PlayFromGameFile ||
13041 gameMode == AnalyzeFile) {
13042 while (currentMove < target) {
13043 SendMoveToProgram(currentMove++, &first);
13046 currentMove = target;
13049 if (gameMode == EditGame || gameMode == EndOfGame) {
13050 whiteTimeRemaining = timeRemaining[0][currentMove];
13051 blackTimeRemaining = timeRemaining[1][currentMove];
13053 DisplayBothClocks();
13054 DisplayMove(currentMove - 1);
13055 DrawPosition(FALSE, boards[currentMove]);
13056 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
13057 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
13058 DisplayComment(currentMove - 1, commentList[currentMove]);
13066 if (gameMode == IcsExamining && !pausing) {
13067 SendToICS(ics_prefix);
13068 SendToICS("forward\n");
13070 ForwardInner(currentMove + 1);
13077 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13078 /* to optimze, we temporarily turn off analysis mode while we feed
13079 * the remaining moves to the engine. Otherwise we get analysis output
13082 if (first.analysisSupport) {
13083 SendToProgram("exit\nforce\n", &first);
13084 first.analyzing = FALSE;
13088 if (gameMode == IcsExamining && !pausing) {
13089 SendToICS(ics_prefix);
13090 SendToICS("forward 999999\n");
13092 ForwardInner(forwardMostMove);
13095 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13096 /* we have fed all the moves, so reactivate analysis mode */
13097 SendToProgram("analyze\n", &first);
13098 first.analyzing = TRUE;
13099 /*first.maybeThinking = TRUE;*/
13100 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13105 BackwardInner(target)
13108 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
13110 if (appData.debugMode)
13111 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
13112 target, currentMove, forwardMostMove);
13114 if (gameMode == EditPosition) return;
13115 if (currentMove <= backwardMostMove) {
13117 DrawPosition(full_redraw, boards[currentMove]);
13120 if (gameMode == PlayFromGameFile && !pausing)
13123 if (moveList[target][0]) {
13124 int fromX, fromY, toX, toY;
13125 toX = moveList[target][2] - AAA;
13126 toY = moveList[target][3] - ONE;
13127 if (moveList[target][1] == '@') {
13128 if (appData.highlightLastMove) {
13129 SetHighlights(-1, -1, toX, toY);
13132 fromX = moveList[target][0] - AAA;
13133 fromY = moveList[target][1] - ONE;
13134 if (target == currentMove - 1) {
13135 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
13137 if (appData.highlightLastMove) {
13138 SetHighlights(fromX, fromY, toX, toY);
13142 if (gameMode == EditGame || gameMode==AnalyzeMode ||
13143 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
13144 while (currentMove > target) {
13145 SendToProgram("undo\n", &first);
13149 currentMove = target;
13152 if (gameMode == EditGame || gameMode == EndOfGame) {
13153 whiteTimeRemaining = timeRemaining[0][currentMove];
13154 blackTimeRemaining = timeRemaining[1][currentMove];
13156 DisplayBothClocks();
13157 DisplayMove(currentMove - 1);
13158 DrawPosition(full_redraw, boards[currentMove]);
13159 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
13160 // [HGM] PV info: routine tests if comment empty
13161 DisplayComment(currentMove - 1, commentList[currentMove]);
13167 if (gameMode == IcsExamining && !pausing) {
13168 SendToICS(ics_prefix);
13169 SendToICS("backward\n");
13171 BackwardInner(currentMove - 1);
13178 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13179 /* to optimize, we temporarily turn off analysis mode while we undo
13180 * all the moves. Otherwise we get analysis output after each undo.
13182 if (first.analysisSupport) {
13183 SendToProgram("exit\nforce\n", &first);
13184 first.analyzing = FALSE;
13188 if (gameMode == IcsExamining && !pausing) {
13189 SendToICS(ics_prefix);
13190 SendToICS("backward 999999\n");
13192 BackwardInner(backwardMostMove);
13195 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13196 /* we have fed all the moves, so reactivate analysis mode */
13197 SendToProgram("analyze\n", &first);
13198 first.analyzing = TRUE;
13199 /*first.maybeThinking = TRUE;*/
13200 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13207 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
13208 if (to >= forwardMostMove) to = forwardMostMove;
13209 if (to <= backwardMostMove) to = backwardMostMove;
13210 if (to < currentMove) {
13218 RevertEvent(Boolean annotate)
13220 if(PopTail(annotate)) { // [HGM] vari: restore old game tail
13223 if (gameMode != IcsExamining) {
13224 DisplayError(_("You are not examining a game"), 0);
13228 DisplayError(_("You can't revert while pausing"), 0);
13231 SendToICS(ics_prefix);
13232 SendToICS("revert\n");
13238 switch (gameMode) {
13239 case MachinePlaysWhite:
13240 case MachinePlaysBlack:
13241 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
13242 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
13245 if (forwardMostMove < 2) return;
13246 currentMove = forwardMostMove = forwardMostMove - 2;
13247 whiteTimeRemaining = timeRemaining[0][currentMove];
13248 blackTimeRemaining = timeRemaining[1][currentMove];
13249 DisplayBothClocks();
13250 DisplayMove(currentMove - 1);
13251 ClearHighlights();/*!! could figure this out*/
13252 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
13253 SendToProgram("remove\n", &first);
13254 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
13257 case BeginningOfGame:
13261 case IcsPlayingWhite:
13262 case IcsPlayingBlack:
13263 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
13264 SendToICS(ics_prefix);
13265 SendToICS("takeback 2\n");
13267 SendToICS(ics_prefix);
13268 SendToICS("takeback 1\n");
13277 ChessProgramState *cps;
13279 switch (gameMode) {
13280 case MachinePlaysWhite:
13281 if (!WhiteOnMove(forwardMostMove)) {
13282 DisplayError(_("It is your turn"), 0);
13287 case MachinePlaysBlack:
13288 if (WhiteOnMove(forwardMostMove)) {
13289 DisplayError(_("It is your turn"), 0);
13294 case TwoMachinesPlay:
13295 if (WhiteOnMove(forwardMostMove) ==
13296 (first.twoMachinesColor[0] == 'w')) {
13302 case BeginningOfGame:
13306 SendToProgram("?\n", cps);
13310 TruncateGameEvent()
13313 if (gameMode != EditGame) return;
13320 CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
13321 if (forwardMostMove > currentMove) {
13322 if (gameInfo.resultDetails != NULL) {
13323 free(gameInfo.resultDetails);
13324 gameInfo.resultDetails = NULL;
13325 gameInfo.result = GameUnfinished;
13327 forwardMostMove = currentMove;
13328 HistorySet(parseList, backwardMostMove, forwardMostMove,
13336 if (appData.noChessProgram) return;
13337 switch (gameMode) {
13338 case MachinePlaysWhite:
13339 if (WhiteOnMove(forwardMostMove)) {
13340 DisplayError(_("Wait until your turn"), 0);
13344 case BeginningOfGame:
13345 case MachinePlaysBlack:
13346 if (!WhiteOnMove(forwardMostMove)) {
13347 DisplayError(_("Wait until your turn"), 0);
13352 DisplayError(_("No hint available"), 0);
13355 SendToProgram("hint\n", &first);
13356 hintRequested = TRUE;
13362 if (appData.noChessProgram) return;
13363 switch (gameMode) {
13364 case MachinePlaysWhite:
13365 if (WhiteOnMove(forwardMostMove)) {
13366 DisplayError(_("Wait until your turn"), 0);
13370 case BeginningOfGame:
13371 case MachinePlaysBlack:
13372 if (!WhiteOnMove(forwardMostMove)) {
13373 DisplayError(_("Wait until your turn"), 0);
13378 EditPositionDone(TRUE);
13380 case TwoMachinesPlay:
13385 SendToProgram("bk\n", &first);
13386 bookOutput[0] = NULLCHAR;
13387 bookRequested = TRUE;
13393 char *tags = PGNTags(&gameInfo);
13394 TagsPopUp(tags, CmailMsg());
13398 /* end button procedures */
13401 PrintPosition(fp, move)
13407 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
13408 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
13409 char c = PieceToChar(boards[move][i][j]);
13410 fputc(c == 'x' ? '.' : c, fp);
13411 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
13414 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
13415 fprintf(fp, "white to play\n");
13417 fprintf(fp, "black to play\n");
13424 if (gameInfo.white != NULL) {
13425 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
13431 /* Find last component of program's own name, using some heuristics */
13433 TidyProgramName(prog, host, buf)
13434 char *prog, *host, buf[MSG_SIZ];
13437 int local = (strcmp(host, "localhost") == 0);
13438 while (!local && (p = strchr(prog, ';')) != NULL) {
13440 while (*p == ' ') p++;
13443 if (*prog == '"' || *prog == '\'') {
13444 q = strchr(prog + 1, *prog);
13446 q = strchr(prog, ' ');
13448 if (q == NULL) q = prog + strlen(prog);
13450 while (p >= prog && *p != '/' && *p != '\\') p--;
13452 if(p == prog && *p == '"') p++;
13453 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) q -= 4;
13454 memcpy(buf, p, q - p);
13455 buf[q - p] = NULLCHAR;
13463 TimeControlTagValue()
13466 if (!appData.clockMode) {
13467 safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
13468 } else if (movesPerSession > 0) {
13469 snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
13470 } else if (timeIncrement == 0) {
13471 snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
13473 snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
13475 return StrSave(buf);
13481 /* This routine is used only for certain modes */
13482 VariantClass v = gameInfo.variant;
13483 ChessMove r = GameUnfinished;
13486 if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
13487 r = gameInfo.result;
13488 p = gameInfo.resultDetails;
13489 gameInfo.resultDetails = NULL;
13491 ClearGameInfo(&gameInfo);
13492 gameInfo.variant = v;
13494 switch (gameMode) {
13495 case MachinePlaysWhite:
13496 gameInfo.event = StrSave( appData.pgnEventHeader );
13497 gameInfo.site = StrSave(HostName());
13498 gameInfo.date = PGNDate();
13499 gameInfo.round = StrSave("-");
13500 gameInfo.white = StrSave(first.tidy);
13501 gameInfo.black = StrSave(UserName());
13502 gameInfo.timeControl = TimeControlTagValue();
13505 case MachinePlaysBlack:
13506 gameInfo.event = StrSave( appData.pgnEventHeader );
13507 gameInfo.site = StrSave(HostName());
13508 gameInfo.date = PGNDate();
13509 gameInfo.round = StrSave("-");
13510 gameInfo.white = StrSave(UserName());
13511 gameInfo.black = StrSave(first.tidy);
13512 gameInfo.timeControl = TimeControlTagValue();
13515 case TwoMachinesPlay:
13516 gameInfo.event = StrSave( appData.pgnEventHeader );
13517 gameInfo.site = StrSave(HostName());
13518 gameInfo.date = PGNDate();
13519 if (matchGame > 0) {
13521 snprintf(buf, MSG_SIZ, "%d", matchGame);
13522 gameInfo.round = StrSave(buf);
13524 gameInfo.round = StrSave("-");
13526 if (first.twoMachinesColor[0] == 'w') {
13527 gameInfo.white = StrSave(first.tidy);
13528 gameInfo.black = StrSave(second.tidy);
13530 gameInfo.white = StrSave(second.tidy);
13531 gameInfo.black = StrSave(first.tidy);
13533 gameInfo.timeControl = TimeControlTagValue();
13537 gameInfo.event = StrSave("Edited game");
13538 gameInfo.site = StrSave(HostName());
13539 gameInfo.date = PGNDate();
13540 gameInfo.round = StrSave("-");
13541 gameInfo.white = StrSave("-");
13542 gameInfo.black = StrSave("-");
13543 gameInfo.result = r;
13544 gameInfo.resultDetails = p;
13548 gameInfo.event = StrSave("Edited position");
13549 gameInfo.site = StrSave(HostName());
13550 gameInfo.date = PGNDate();
13551 gameInfo.round = StrSave("-");
13552 gameInfo.white = StrSave("-");
13553 gameInfo.black = StrSave("-");
13556 case IcsPlayingWhite:
13557 case IcsPlayingBlack:
13562 case PlayFromGameFile:
13563 gameInfo.event = StrSave("Game from non-PGN file");
13564 gameInfo.site = StrSave(HostName());
13565 gameInfo.date = PGNDate();
13566 gameInfo.round = StrSave("-");
13567 gameInfo.white = StrSave("?");
13568 gameInfo.black = StrSave("?");
13577 ReplaceComment(index, text)
13585 if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
13586 pvInfoList[index-1].depth == len &&
13587 fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
13588 (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
13589 while (*text == '\n') text++;
13590 len = strlen(text);
13591 while (len > 0 && text[len - 1] == '\n') len--;
13593 if (commentList[index] != NULL)
13594 free(commentList[index]);
13597 commentList[index] = NULL;
13600 if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
13601 *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
13602 *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
13603 commentList[index] = (char *) malloc(len + 2);
13604 strncpy(commentList[index], text, len);
13605 commentList[index][len] = '\n';
13606 commentList[index][len + 1] = NULLCHAR;
13608 // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
13610 commentList[index] = (char *) malloc(len + 7);
13611 safeStrCpy(commentList[index], "{\n", 3);
13612 safeStrCpy(commentList[index]+2, text, len+1);
13613 commentList[index][len+2] = NULLCHAR;
13614 while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
13615 strcat(commentList[index], "\n}\n");
13629 if (ch == '\r') continue;
13631 } while (ch != '\0');
13635 AppendComment(index, text, addBraces)
13638 Boolean addBraces; // [HGM] braces: tells if we should add {}
13643 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces); fflush(debugFP);
13644 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
13647 while (*text == '\n') text++;
13648 len = strlen(text);
13649 while (len > 0 && text[len - 1] == '\n') len--;
13651 if (len == 0) return;
13653 if (commentList[index] != NULL) {
13654 old = commentList[index];
13655 oldlen = strlen(old);
13656 while(commentList[index][oldlen-1] == '\n')
13657 commentList[index][--oldlen] = NULLCHAR;
13658 commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
13659 safeStrCpy(commentList[index], old, oldlen + len + 6);
13661 // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
13662 if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
13663 if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
13664 while (*text == '\n') { text++; len--; }
13665 commentList[index][--oldlen] = NULLCHAR;
13667 if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
13668 else strcat(commentList[index], "\n");
13669 strcat(commentList[index], text);
13670 if(addBraces) strcat(commentList[index], addBraces == 2 ? ")\n" : "\n}\n");
13671 else strcat(commentList[index], "\n");
13673 commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
13675 safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
13676 else commentList[index][0] = NULLCHAR;
13677 strcat(commentList[index], text);
13678 strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
13679 if(addBraces == TRUE) strcat(commentList[index], "}\n");
13683 static char * FindStr( char * text, char * sub_text )
13685 char * result = strstr( text, sub_text );
13687 if( result != NULL ) {
13688 result += strlen( sub_text );
13694 /* [AS] Try to extract PV info from PGN comment */
13695 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
13696 char *GetInfoFromComment( int index, char * text )
13698 char * sep = text, *p;
13700 if( text != NULL && index > 0 ) {
13703 int time = -1, sec = 0, deci;
13704 char * s_eval = FindStr( text, "[%eval " );
13705 char * s_emt = FindStr( text, "[%emt " );
13707 if( s_eval != NULL || s_emt != NULL ) {
13711 if( s_eval != NULL ) {
13712 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
13716 if( delim != ']' ) {
13721 if( s_emt != NULL ) {
13726 /* We expect something like: [+|-]nnn.nn/dd */
13729 if(*text != '{') return text; // [HGM] braces: must be normal comment
13731 sep = strchr( text, '/' );
13732 if( sep == NULL || sep < (text+4) ) {
13737 if(p[1] == '(') { // comment starts with PV
13738 p = strchr(p, ')'); // locate end of PV
13739 if(p == NULL || sep < p+5) return text;
13740 // at this point we have something like "{(.*) +0.23/6 ..."
13741 p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
13742 *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
13743 // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
13745 time = -1; sec = -1; deci = -1;
13746 if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
13747 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
13748 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
13749 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
13753 if( score_lo < 0 || score_lo >= 100 ) {
13757 if(sec >= 0) time = 600*time + 10*sec; else
13758 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
13760 score = score >= 0 ? score*100 + score_lo : score*100 - score_lo;
13762 /* [HGM] PV time: now locate end of PV info */
13763 while( *++sep >= '0' && *sep <= '9'); // strip depth
13765 while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
13767 while( *++sep >= '0' && *sep <= '9'); // strip seconds
13769 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
13770 while(*sep == ' ') sep++;
13781 pvInfoList[index-1].depth = depth;
13782 pvInfoList[index-1].score = score;
13783 pvInfoList[index-1].time = 10*time; // centi-sec
13784 if(*sep == '}') *sep = 0; else *--sep = '{';
13785 if(p != text) { while(*p++ = *sep++); sep = text; } // squeeze out space between PV and comment, and return both
13791 SendToProgram(message, cps)
13793 ChessProgramState *cps;
13795 int count, outCount, error;
13798 if (cps->pr == NULL) return;
13801 if (appData.debugMode) {
13804 fprintf(debugFP, "%ld >%-6s: %s",
13805 SubtractTimeMarks(&now, &programStartTime),
13806 cps->which, message);
13809 count = strlen(message);
13810 outCount = OutputToProcess(cps->pr, message, count, &error);
13811 if (outCount < count && !exiting
13812 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
13813 if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
13814 snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
13815 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
13816 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
13817 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
13818 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
13820 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
13822 gameInfo.resultDetails = StrSave(buf);
13824 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
13829 ReceiveFromProgram(isr, closure, message, count, error)
13830 InputSourceRef isr;
13838 ChessProgramState *cps = (ChessProgramState *)closure;
13840 if (isr != cps->isr) return; /* Killed intentionally */
13843 snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
13844 _(cps->which), cps->program);
13845 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
13846 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
13847 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
13848 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
13850 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
13852 gameInfo.resultDetails = StrSave(buf);
13854 RemoveInputSource(cps->isr);
13855 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
13857 snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
13858 _(cps->which), cps->program);
13859 RemoveInputSource(cps->isr);
13861 /* [AS] Program is misbehaving badly... kill it */
13862 if( count == -2 ) {
13863 DestroyChildProcess( cps->pr, 9 );
13867 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
13872 if ((end_str = strchr(message, '\r')) != NULL)
13873 *end_str = NULLCHAR;
13874 if ((end_str = strchr(message, '\n')) != NULL)
13875 *end_str = NULLCHAR;
13877 if (appData.debugMode) {
13878 TimeMark now; int print = 1;
13879 char *quote = ""; char c; int i;
13881 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
13882 char start = message[0];
13883 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
13884 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
13885 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
13886 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
13887 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
13888 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
13889 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
13890 sscanf(message, "setboard %c", &c)!=1 && sscanf(message, "setup %c", &c)!=1 &&
13891 sscanf(message, "hint: %c", &c)!=1 &&
13892 sscanf(message, "pong %c", &c)!=1 && start != '#') {
13893 quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
13894 print = (appData.engineComments >= 2);
13896 message[0] = start; // restore original message
13900 fprintf(debugFP, "%ld <%-6s: %s%s\n",
13901 SubtractTimeMarks(&now, &programStartTime), cps->which,
13907 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
13908 if (appData.icsEngineAnalyze) {
13909 if (strstr(message, "whisper") != NULL ||
13910 strstr(message, "kibitz") != NULL ||
13911 strstr(message, "tellics") != NULL) return;
13914 HandleMachineMove(message, cps);
13919 SendTimeControl(cps, mps, tc, inc, sd, st)
13920 ChessProgramState *cps;
13921 int mps, inc, sd, st;
13927 if( timeControl_2 > 0 ) {
13928 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
13929 tc = timeControl_2;
13932 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
13933 inc /= cps->timeOdds;
13934 st /= cps->timeOdds;
13936 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
13939 /* Set exact time per move, normally using st command */
13940 if (cps->stKludge) {
13941 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
13943 if (seconds == 0) {
13944 snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
13946 snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
13949 snprintf(buf, MSG_SIZ, "st %d\n", st);
13952 /* Set conventional or incremental time control, using level command */
13953 if (seconds == 0) {
13954 /* Note old gnuchess bug -- minutes:seconds used to not work.
13955 Fixed in later versions, but still avoid :seconds
13956 when seconds is 0. */
13957 snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
13959 snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
13960 seconds, inc/1000.);
13963 SendToProgram(buf, cps);
13965 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
13966 /* Orthogonally, limit search to given depth */
13968 if (cps->sdKludge) {
13969 snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
13971 snprintf(buf, MSG_SIZ, "sd %d\n", sd);
13973 SendToProgram(buf, cps);
13976 if(cps->nps >= 0) { /* [HGM] nps */
13977 if(cps->supportsNPS == FALSE)
13978 cps->nps = -1; // don't use if engine explicitly says not supported!
13980 snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
13981 SendToProgram(buf, cps);
13986 ChessProgramState *WhitePlayer()
13987 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
13989 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
13990 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
13996 SendTimeRemaining(cps, machineWhite)
13997 ChessProgramState *cps;
13998 int /*boolean*/ machineWhite;
14000 char message[MSG_SIZ];
14003 /* Note: this routine must be called when the clocks are stopped
14004 or when they have *just* been set or switched; otherwise
14005 it will be off by the time since the current tick started.
14007 if (machineWhite) {
14008 time = whiteTimeRemaining / 10;
14009 otime = blackTimeRemaining / 10;
14011 time = blackTimeRemaining / 10;
14012 otime = whiteTimeRemaining / 10;
14014 /* [HGM] translate opponent's time by time-odds factor */
14015 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
14016 if (appData.debugMode) {
14017 fprintf(debugFP, "time odds: %f %f \n", cps->timeOdds, cps->other->timeOdds);
14020 if (time <= 0) time = 1;
14021 if (otime <= 0) otime = 1;
14023 snprintf(message, MSG_SIZ, "time %ld\n", time);
14024 SendToProgram(message, cps);
14026 snprintf(message, MSG_SIZ, "otim %ld\n", otime);
14027 SendToProgram(message, cps);
14031 BoolFeature(p, name, loc, cps)
14035 ChessProgramState *cps;
14038 int len = strlen(name);
14041 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
14043 sscanf(*p, "%d", &val);
14045 while (**p && **p != ' ')
14047 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
14048 SendToProgram(buf, cps);
14055 IntFeature(p, name, loc, cps)
14059 ChessProgramState *cps;
14062 int len = strlen(name);
14063 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
14065 sscanf(*p, "%d", loc);
14066 while (**p && **p != ' ') (*p)++;
14067 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
14068 SendToProgram(buf, cps);
14075 StringFeature(p, name, loc, cps)
14079 ChessProgramState *cps;
14082 int len = strlen(name);
14083 if (strncmp((*p), name, len) == 0
14084 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
14086 sscanf(*p, "%[^\"]", loc);
14087 while (**p && **p != '\"') (*p)++;
14088 if (**p == '\"') (*p)++;
14089 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
14090 SendToProgram(buf, cps);
14097 ParseOption(Option *opt, ChessProgramState *cps)
14098 // [HGM] options: process the string that defines an engine option, and determine
14099 // name, type, default value, and allowed value range
14101 char *p, *q, buf[MSG_SIZ];
14102 int n, min = (-1)<<31, max = 1<<31, def;
14104 if(p = strstr(opt->name, " -spin ")) {
14105 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
14106 if(max < min) max = min; // enforce consistency
14107 if(def < min) def = min;
14108 if(def > max) def = max;
14113 } else if((p = strstr(opt->name, " -slider "))) {
14114 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
14115 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
14116 if(max < min) max = min; // enforce consistency
14117 if(def < min) def = min;
14118 if(def > max) def = max;
14122 opt->type = Spin; // Slider;
14123 } else if((p = strstr(opt->name, " -string "))) {
14124 opt->textValue = p+9;
14125 opt->type = TextBox;
14126 } else if((p = strstr(opt->name, " -file "))) {
14127 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
14128 opt->textValue = p+7;
14129 opt->type = FileName; // FileName;
14130 } else if((p = strstr(opt->name, " -path "))) {
14131 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
14132 opt->textValue = p+7;
14133 opt->type = PathName; // PathName;
14134 } else if(p = strstr(opt->name, " -check ")) {
14135 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
14136 opt->value = (def != 0);
14137 opt->type = CheckBox;
14138 } else if(p = strstr(opt->name, " -combo ")) {
14139 opt->textValue = (char*) (&cps->comboList[cps->comboCnt]); // cheat with pointer type
14140 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
14141 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
14142 opt->value = n = 0;
14143 while(q = StrStr(q, " /// ")) {
14144 n++; *q = 0; // count choices, and null-terminate each of them
14146 if(*q == '*') { // remember default, which is marked with * prefix
14150 cps->comboList[cps->comboCnt++] = q;
14152 cps->comboList[cps->comboCnt++] = NULL;
14154 opt->type = ComboBox;
14155 } else if(p = strstr(opt->name, " -button")) {
14156 opt->type = Button;
14157 } else if(p = strstr(opt->name, " -save")) {
14158 opt->type = SaveButton;
14159 } else return FALSE;
14160 *p = 0; // terminate option name
14161 // now look if the command-line options define a setting for this engine option.
14162 if(cps->optionSettings && cps->optionSettings[0])
14163 p = strstr(cps->optionSettings, opt->name); else p = NULL;
14164 if(p && (p == cps->optionSettings || p[-1] == ',')) {
14165 snprintf(buf, MSG_SIZ, "option %s", p);
14166 if(p = strstr(buf, ",")) *p = 0;
14167 if(q = strchr(buf, '=')) switch(opt->type) {
14169 for(n=0; n<opt->max; n++)
14170 if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
14173 safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
14177 opt->value = atoi(q+1);
14182 SendToProgram(buf, cps);
14188 FeatureDone(cps, val)
14189 ChessProgramState* cps;
14192 DelayedEventCallback cb = GetDelayedEvent();
14193 if ((cb == InitBackEnd3 && cps == &first) ||
14194 (cb == SettingsMenuIfReady && cps == &second) ||
14195 (cb == LoadEngine) ||
14196 (cb == TwoMachinesEventIfReady && cps == &second)) {
14197 CancelDelayedEvent();
14198 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
14200 cps->initDone = val;
14203 /* Parse feature command from engine */
14205 ParseFeatures(args, cps)
14207 ChessProgramState *cps;
14215 while (*p == ' ') p++;
14216 if (*p == NULLCHAR) return;
14218 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
14219 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
14220 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
14221 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
14222 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
14223 if (BoolFeature(&p, "reuse", &val, cps)) {
14224 /* Engine can disable reuse, but can't enable it if user said no */
14225 if (!val) cps->reuse = FALSE;
14228 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
14229 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
14230 if (gameMode == TwoMachinesPlay) {
14231 DisplayTwoMachinesTitle();
14237 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
14238 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
14239 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
14240 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
14241 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
14242 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
14243 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
14244 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
14245 if (BoolFeature(&p, "pause", &val, cps)) continue; /* unused at present */
14246 if (IntFeature(&p, "done", &val, cps)) {
14247 FeatureDone(cps, val);
14250 /* Added by Tord: */
14251 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
14252 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
14253 /* End of additions by Tord */
14255 /* [HGM] added features: */
14256 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
14257 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
14258 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
14259 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
14260 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
14261 if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
14262 if (StringFeature(&p, "option", &(cps->option[cps->nrOptions].name), cps)) {
14263 if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
14264 snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
14265 SendToProgram(buf, cps);
14268 if(cps->nrOptions >= MAX_OPTIONS) {
14270 snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
14271 DisplayError(buf, 0);
14275 /* End of additions by HGM */
14277 /* unknown feature: complain and skip */
14279 while (*q && *q != '=') q++;
14280 snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
14281 SendToProgram(buf, cps);
14287 while (*p && *p != '\"') p++;
14288 if (*p == '\"') p++;
14290 while (*p && *p != ' ') p++;
14298 PeriodicUpdatesEvent(newState)
14301 if (newState == appData.periodicUpdates)
14304 appData.periodicUpdates=newState;
14306 /* Display type changes, so update it now */
14307 // DisplayAnalysis();
14309 /* Get the ball rolling again... */
14311 AnalysisPeriodicEvent(1);
14312 StartAnalysisClock();
14317 PonderNextMoveEvent(newState)
14320 if (newState == appData.ponderNextMove) return;
14321 if (gameMode == EditPosition) EditPositionDone(TRUE);
14323 SendToProgram("hard\n", &first);
14324 if (gameMode == TwoMachinesPlay) {
14325 SendToProgram("hard\n", &second);
14328 SendToProgram("easy\n", &first);
14329 thinkOutput[0] = NULLCHAR;
14330 if (gameMode == TwoMachinesPlay) {
14331 SendToProgram("easy\n", &second);
14334 appData.ponderNextMove = newState;
14338 NewSettingEvent(option, feature, command, value)
14340 int option, value, *feature;
14344 if (gameMode == EditPosition) EditPositionDone(TRUE);
14345 snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
14346 if(feature == NULL || *feature) SendToProgram(buf, &first);
14347 if (gameMode == TwoMachinesPlay) {
14348 if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
14353 ShowThinkingEvent()
14354 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
14356 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
14357 int newState = appData.showThinking
14358 // [HGM] thinking: other features now need thinking output as well
14359 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
14361 if (oldState == newState) return;
14362 oldState = newState;
14363 if (gameMode == EditPosition) EditPositionDone(TRUE);
14365 SendToProgram("post\n", &first);
14366 if (gameMode == TwoMachinesPlay) {
14367 SendToProgram("post\n", &second);
14370 SendToProgram("nopost\n", &first);
14371 thinkOutput[0] = NULLCHAR;
14372 if (gameMode == TwoMachinesPlay) {
14373 SendToProgram("nopost\n", &second);
14376 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
14380 AskQuestionEvent(title, question, replyPrefix, which)
14381 char *title; char *question; char *replyPrefix; char *which;
14383 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
14384 if (pr == NoProc) return;
14385 AskQuestion(title, question, replyPrefix, pr);
14389 TypeInEvent(char firstChar)
14391 if ((gameMode == BeginningOfGame && !appData.icsActive) ||
\r
14392 gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
\r
14393 gameMode == AnalyzeMode || gameMode == EditGame ||
\r
14394 gameMode == EditPosition || gameMode == IcsExamining ||
\r
14395 gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
\r
14396 isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
\r
14397 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
\r
14398 gameMode == IcsObserving || gameMode == TwoMachinesPlay ) ||
\r
14399 gameMode == Training) PopUpMoveDialog(firstChar);
14403 TypeInDoneEvent(char *move)
14406 int n, fromX, fromY, toX, toY;
14408 ChessMove moveType;
\r
14411 if(gameMode == EditPosition && ParseFEN(board, &n, move) ) {
\r
14412 EditPositionPasteFEN(move);
\r
14415 // [HGM] movenum: allow move number to be typed in any mode
\r
14416 if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
\r
14417 ToNrEvent(2*n-1);
\r
14421 if (gameMode != EditGame && currentMove != forwardMostMove &&
\r
14422 gameMode != Training) {
\r
14423 DisplayMoveError(_("Displayed move is not current"));
\r
14425 int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
\r
14426 &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
\r
14427 if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
\r
14428 if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
\r
14429 &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
\r
14430 UserMoveEvent(fromX, fromY, toX, toY, promoChar);
\r
14432 DisplayMoveError(_("Could not parse move"));
\r
14438 DisplayMove(moveNumber)
14441 char message[MSG_SIZ];
14443 char cpThinkOutput[MSG_SIZ];
14445 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
14447 if (moveNumber == forwardMostMove - 1 ||
14448 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14450 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
14452 if (strchr(cpThinkOutput, '\n')) {
14453 *strchr(cpThinkOutput, '\n') = NULLCHAR;
14456 *cpThinkOutput = NULLCHAR;
14459 /* [AS] Hide thinking from human user */
14460 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
14461 *cpThinkOutput = NULLCHAR;
14462 if( thinkOutput[0] != NULLCHAR ) {
14465 for( i=0; i<=hiddenThinkOutputState; i++ ) {
14466 cpThinkOutput[i] = '.';
14468 cpThinkOutput[i] = NULLCHAR;
14469 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
14473 if (moveNumber == forwardMostMove - 1 &&
14474 gameInfo.resultDetails != NULL) {
14475 if (gameInfo.resultDetails[0] == NULLCHAR) {
14476 snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
14478 snprintf(res, MSG_SIZ, " {%s} %s",
14479 T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
14485 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
14486 DisplayMessage(res, cpThinkOutput);
14488 snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
14489 WhiteOnMove(moveNumber) ? " " : ".. ",
14490 parseList[moveNumber], res);
14491 DisplayMessage(message, cpThinkOutput);
14496 DisplayComment(moveNumber, text)
14500 char title[MSG_SIZ];
14501 char buf[8000]; // comment can be long!
14504 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
14505 safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
14507 snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
14508 WhiteOnMove(moveNumber) ? " " : ".. ",
14509 parseList[moveNumber]);
14511 // [HGM] PV info: display PV info together with (or as) comment
14512 if(moveNumber >= 0 && (depth = pvInfoList[moveNumber].depth) > 0) {
14513 if(text == NULL) text = "";
14514 score = pvInfoList[moveNumber].score;
14515 snprintf(buf,sizeof(buf)/sizeof(buf[0]), "%s%.2f/%d %d\n%s", score>0 ? "+" : "", score/100.,
14516 depth, (pvInfoList[moveNumber].time+50)/100, text);
14519 if (text != NULL && (appData.autoDisplayComment || commentUp))
14520 CommentPopUp(title, text);
14523 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
14524 * might be busy thinking or pondering. It can be omitted if your
14525 * gnuchess is configured to stop thinking immediately on any user
14526 * input. However, that gnuchess feature depends on the FIONREAD
14527 * ioctl, which does not work properly on some flavors of Unix.
14531 ChessProgramState *cps;
14534 if (!cps->useSigint) return;
14535 if (appData.noChessProgram || (cps->pr == NoProc)) return;
14536 switch (gameMode) {
14537 case MachinePlaysWhite:
14538 case MachinePlaysBlack:
14539 case TwoMachinesPlay:
14540 case IcsPlayingWhite:
14541 case IcsPlayingBlack:
14544 /* Skip if we know it isn't thinking */
14545 if (!cps->maybeThinking) return;
14546 if (appData.debugMode)
14547 fprintf(debugFP, "Interrupting %s\n", cps->which);
14548 InterruptChildProcess(cps->pr);
14549 cps->maybeThinking = FALSE;
14554 #endif /*ATTENTION*/
14560 if (whiteTimeRemaining <= 0) {
14563 if (appData.icsActive) {
14564 if (appData.autoCallFlag &&
14565 gameMode == IcsPlayingBlack && !blackFlag) {
14566 SendToICS(ics_prefix);
14567 SendToICS("flag\n");
14571 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
14573 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
14574 if (appData.autoCallFlag) {
14575 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
14582 if (blackTimeRemaining <= 0) {
14585 if (appData.icsActive) {
14586 if (appData.autoCallFlag &&
14587 gameMode == IcsPlayingWhite && !whiteFlag) {
14588 SendToICS(ics_prefix);
14589 SendToICS("flag\n");
14593 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
14595 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
14596 if (appData.autoCallFlag) {
14597 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
14610 if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
14611 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
14614 * add time to clocks when time control is achieved ([HGM] now also used for increment)
14616 if ( !WhiteOnMove(forwardMostMove) ) {
14617 /* White made time control */
14618 lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
14619 whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
14620 /* [HGM] time odds: correct new time quota for time odds! */
14621 / WhitePlayer()->timeOdds;
14622 lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
14624 lastBlack -= blackTimeRemaining;
14625 /* Black made time control */
14626 blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
14627 / WhitePlayer()->other->timeOdds;
14628 lastWhite = whiteTimeRemaining;
14633 DisplayBothClocks()
14635 int wom = gameMode == EditPosition ?
14636 !blackPlaysFirst : WhiteOnMove(currentMove);
14637 DisplayWhiteClock(whiteTimeRemaining, wom);
14638 DisplayBlackClock(blackTimeRemaining, !wom);
14642 /* Timekeeping seems to be a portability nightmare. I think everyone
14643 has ftime(), but I'm really not sure, so I'm including some ifdefs
14644 to use other calls if you don't. Clocks will be less accurate if
14645 you have neither ftime nor gettimeofday.
14648 /* VS 2008 requires the #include outside of the function */
14649 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
14650 #include <sys/timeb.h>
14653 /* Get the current time as a TimeMark */
14658 #if HAVE_GETTIMEOFDAY
14660 struct timeval timeVal;
14661 struct timezone timeZone;
14663 gettimeofday(&timeVal, &timeZone);
14664 tm->sec = (long) timeVal.tv_sec;
14665 tm->ms = (int) (timeVal.tv_usec / 1000L);
14667 #else /*!HAVE_GETTIMEOFDAY*/
14670 // include <sys/timeb.h> / moved to just above start of function
14671 struct timeb timeB;
14674 tm->sec = (long) timeB.time;
14675 tm->ms = (int) timeB.millitm;
14677 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
14678 tm->sec = (long) time(NULL);
14684 /* Return the difference in milliseconds between two
14685 time marks. We assume the difference will fit in a long!
14688 SubtractTimeMarks(tm2, tm1)
14689 TimeMark *tm2, *tm1;
14691 return 1000L*(tm2->sec - tm1->sec) +
14692 (long) (tm2->ms - tm1->ms);
14697 * Code to manage the game clocks.
14699 * In tournament play, black starts the clock and then white makes a move.
14700 * We give the human user a slight advantage if he is playing white---the
14701 * clocks don't run until he makes his first move, so it takes zero time.
14702 * Also, we don't account for network lag, so we could get out of sync
14703 * with GNU Chess's clock -- but then, referees are always right.
14706 static TimeMark tickStartTM;
14707 static long intendedTickLength;
14710 NextTickLength(timeRemaining)
14711 long timeRemaining;
14713 long nominalTickLength, nextTickLength;
14715 if (timeRemaining > 0L && timeRemaining <= 10000L)
14716 nominalTickLength = 100L;
14718 nominalTickLength = 1000L;
14719 nextTickLength = timeRemaining % nominalTickLength;
14720 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
14722 return nextTickLength;
14725 /* Adjust clock one minute up or down */
14727 AdjustClock(Boolean which, int dir)
14729 if(which) blackTimeRemaining += 60000*dir;
14730 else whiteTimeRemaining += 60000*dir;
14731 DisplayBothClocks();
14734 /* Stop clocks and reset to a fresh time control */
14738 (void) StopClockTimer();
14739 if (appData.icsActive) {
14740 whiteTimeRemaining = blackTimeRemaining = 0;
14741 } else if (searchTime) {
14742 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
14743 blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
14744 } else { /* [HGM] correct new time quote for time odds */
14745 whiteTC = blackTC = fullTimeControlString;
14746 whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
14747 blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
14749 if (whiteFlag || blackFlag) {
14751 whiteFlag = blackFlag = FALSE;
14753 lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
14754 DisplayBothClocks();
14757 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
14759 /* Decrement running clock by amount of time that has passed */
14763 long timeRemaining;
14764 long lastTickLength, fudge;
14767 if (!appData.clockMode) return;
14768 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
14772 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14774 /* Fudge if we woke up a little too soon */
14775 fudge = intendedTickLength - lastTickLength;
14776 if (fudge < 0 || fudge > FUDGE) fudge = 0;
14778 if (WhiteOnMove(forwardMostMove)) {
14779 if(whiteNPS >= 0) lastTickLength = 0;
14780 timeRemaining = whiteTimeRemaining -= lastTickLength;
14781 if(timeRemaining < 0 && !appData.icsActive) {
14782 GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
14783 if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
14784 whiteStartMove = forwardMostMove; whiteTC = nextSession;
14785 lastWhite= timeRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
14788 DisplayWhiteClock(whiteTimeRemaining - fudge,
14789 WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
14791 if(blackNPS >= 0) lastTickLength = 0;
14792 timeRemaining = blackTimeRemaining -= lastTickLength;
14793 if(timeRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
14794 GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
14796 blackStartMove = forwardMostMove;
14797 lastBlack = timeRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
14800 DisplayBlackClock(blackTimeRemaining - fudge,
14801 !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
14803 if (CheckFlags()) return;
14806 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
14807 StartClockTimer(intendedTickLength);
14809 /* if the time remaining has fallen below the alarm threshold, sound the
14810 * alarm. if the alarm has sounded and (due to a takeback or time control
14811 * with increment) the time remaining has increased to a level above the
14812 * threshold, reset the alarm so it can sound again.
14815 if (appData.icsActive && appData.icsAlarm) {
14817 /* make sure we are dealing with the user's clock */
14818 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
14819 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
14822 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
14823 alarmSounded = FALSE;
14824 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
14826 alarmSounded = TRUE;
14832 /* A player has just moved, so stop the previously running
14833 clock and (if in clock mode) start the other one.
14834 We redisplay both clocks in case we're in ICS mode, because
14835 ICS gives us an update to both clocks after every move.
14836 Note that this routine is called *after* forwardMostMove
14837 is updated, so the last fractional tick must be subtracted
14838 from the color that is *not* on move now.
14841 SwitchClocks(int newMoveNr)
14843 long lastTickLength;
14845 int flagged = FALSE;
14849 if (StopClockTimer() && appData.clockMode) {
14850 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14851 if (!WhiteOnMove(forwardMostMove)) {
14852 if(blackNPS >= 0) lastTickLength = 0;
14853 blackTimeRemaining -= lastTickLength;
14854 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
14855 // if(pvInfoList[forwardMostMove].time == -1)
14856 pvInfoList[forwardMostMove].time = // use GUI time
14857 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
14859 if(whiteNPS >= 0) lastTickLength = 0;
14860 whiteTimeRemaining -= lastTickLength;
14861 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
14862 // if(pvInfoList[forwardMostMove].time == -1)
14863 pvInfoList[forwardMostMove].time =
14864 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
14866 flagged = CheckFlags();
14868 forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
14869 CheckTimeControl();
14871 if (flagged || !appData.clockMode) return;
14873 switch (gameMode) {
14874 case MachinePlaysBlack:
14875 case MachinePlaysWhite:
14876 case BeginningOfGame:
14877 if (pausing) return;
14881 case PlayFromGameFile:
14889 if (searchTime) { // [HGM] st: set clock of player that has to move to max time
14890 if(WhiteOnMove(forwardMostMove))
14891 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
14892 else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
14896 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
14897 whiteTimeRemaining : blackTimeRemaining);
14898 StartClockTimer(intendedTickLength);
14902 /* Stop both clocks */
14906 long lastTickLength;
14909 if (!StopClockTimer()) return;
14910 if (!appData.clockMode) return;
14914 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14915 if (WhiteOnMove(forwardMostMove)) {
14916 if(whiteNPS >= 0) lastTickLength = 0;
14917 whiteTimeRemaining -= lastTickLength;
14918 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
14920 if(blackNPS >= 0) lastTickLength = 0;
14921 blackTimeRemaining -= lastTickLength;
14922 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
14927 /* Start clock of player on move. Time may have been reset, so
14928 if clock is already running, stop and restart it. */
14932 (void) StopClockTimer(); /* in case it was running already */
14933 DisplayBothClocks();
14934 if (CheckFlags()) return;
14936 if (!appData.clockMode) return;
14937 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
14939 GetTimeMark(&tickStartTM);
14940 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
14941 whiteTimeRemaining : blackTimeRemaining);
14943 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
14944 whiteNPS = blackNPS = -1;
14945 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
14946 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
14947 whiteNPS = first.nps;
14948 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
14949 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
14950 blackNPS = first.nps;
14951 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
14952 whiteNPS = second.nps;
14953 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
14954 blackNPS = second.nps;
14955 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
14957 StartClockTimer(intendedTickLength);
14964 long second, minute, hour, day;
14966 static char buf[32];
14968 if (ms > 0 && ms <= 9900) {
14969 /* convert milliseconds to tenths, rounding up */
14970 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
14972 snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
14976 /* convert milliseconds to seconds, rounding up */
14977 /* use floating point to avoid strangeness of integer division
14978 with negative dividends on many machines */
14979 second = (long) floor(((double) (ms + 999L)) / 1000.0);
14986 day = second / (60 * 60 * 24);
14987 second = second % (60 * 60 * 24);
14988 hour = second / (60 * 60);
14989 second = second % (60 * 60);
14990 minute = second / 60;
14991 second = second % 60;
14994 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ",
14995 sign, day, hour, minute, second);
14997 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
14999 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second);
15006 * This is necessary because some C libraries aren't ANSI C compliant yet.
15009 StrStr(string, match)
15010 char *string, *match;
15014 length = strlen(match);
15016 for (i = strlen(string) - length; i >= 0; i--, string++)
15017 if (!strncmp(match, string, length))
15024 StrCaseStr(string, match)
15025 char *string, *match;
15029 length = strlen(match);
15031 for (i = strlen(string) - length; i >= 0; i--, string++) {
15032 for (j = 0; j < length; j++) {
15033 if (ToLower(match[j]) != ToLower(string[j]))
15036 if (j == length) return string;
15050 c1 = ToLower(*s1++);
15051 c2 = ToLower(*s2++);
15052 if (c1 > c2) return 1;
15053 if (c1 < c2) return -1;
15054 if (c1 == NULLCHAR) return 0;
15063 return isupper(c) ? tolower(c) : c;
15071 return islower(c) ? toupper(c) : c;
15073 #endif /* !_amigados */
15081 if ((ret = (char *) malloc(strlen(s) + 1)))
15083 safeStrCpy(ret, s, strlen(s)+1);
15089 StrSavePtr(s, savePtr)
15090 char *s, **savePtr;
15095 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
15096 safeStrCpy(*savePtr, s, strlen(s)+1);
15108 clock = time((time_t *)NULL);
15109 tm = localtime(&clock);
15110 snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
15111 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
15112 return StrSave(buf);
15117 PositionToFEN(move, overrideCastling)
15119 char *overrideCastling;
15121 int i, j, fromX, fromY, toX, toY;
15128 whiteToPlay = (gameMode == EditPosition) ?
15129 !blackPlaysFirst : (move % 2 == 0);
15132 /* Piece placement data */
15133 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
15135 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
15136 if (boards[move][i][j] == EmptySquare) {
15138 } else { ChessSquare piece = boards[move][i][j];
15139 if (emptycount > 0) {
15140 if(emptycount<10) /* [HGM] can be >= 10 */
15141 *p++ = '0' + emptycount;
15142 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
15145 if(PieceToChar(piece) == '+') {
15146 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
15148 piece = (ChessSquare)(DEMOTED piece);
15150 *p++ = PieceToChar(piece);
15152 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
15153 p[-1] = PieceToChar((ChessSquare)(DEMOTED piece));
15158 if (emptycount > 0) {
15159 if(emptycount<10) /* [HGM] can be >= 10 */
15160 *p++ = '0' + emptycount;
15161 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
15168 /* [HGM] print Crazyhouse or Shogi holdings */
15169 if( gameInfo.holdingsWidth ) {
15170 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
15172 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
15173 piece = boards[move][i][BOARD_WIDTH-1];
15174 if( piece != EmptySquare )
15175 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
15176 *p++ = PieceToChar(piece);
15178 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
15179 piece = boards[move][BOARD_HEIGHT-i-1][0];
15180 if( piece != EmptySquare )
15181 for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
15182 *p++ = PieceToChar(piece);
15185 if( q == p ) *p++ = '-';
15191 *p++ = whiteToPlay ? 'w' : 'b';
15194 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
15195 while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' '; else --p;
15197 if(nrCastlingRights) {
15199 if(gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) {
15200 /* [HGM] write directly from rights */
15201 if(boards[move][CASTLING][2] != NoRights &&
15202 boards[move][CASTLING][0] != NoRights )
15203 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
15204 if(boards[move][CASTLING][2] != NoRights &&
15205 boards[move][CASTLING][1] != NoRights )
15206 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
15207 if(boards[move][CASTLING][5] != NoRights &&
15208 boards[move][CASTLING][3] != NoRights )
15209 *p++ = boards[move][CASTLING][3] + AAA;
15210 if(boards[move][CASTLING][5] != NoRights &&
15211 boards[move][CASTLING][4] != NoRights )
15212 *p++ = boards[move][CASTLING][4] + AAA;
15215 /* [HGM] write true castling rights */
15216 if( nrCastlingRights == 6 ) {
15217 if(boards[move][CASTLING][0] == BOARD_RGHT-1 &&
15218 boards[move][CASTLING][2] != NoRights ) *p++ = 'K';
15219 if(boards[move][CASTLING][1] == BOARD_LEFT &&
15220 boards[move][CASTLING][2] != NoRights ) *p++ = 'Q';
15221 if(boards[move][CASTLING][3] == BOARD_RGHT-1 &&
15222 boards[move][CASTLING][5] != NoRights ) *p++ = 'k';
15223 if(boards[move][CASTLING][4] == BOARD_LEFT &&
15224 boards[move][CASTLING][5] != NoRights ) *p++ = 'q';
15227 if (q == p) *p++ = '-'; /* No castling rights */
15231 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
15232 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
15233 /* En passant target square */
15234 if (move > backwardMostMove) {
15235 fromX = moveList[move - 1][0] - AAA;
15236 fromY = moveList[move - 1][1] - ONE;
15237 toX = moveList[move - 1][2] - AAA;
15238 toY = moveList[move - 1][3] - ONE;
15239 if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
15240 toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
15241 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
15243 /* 2-square pawn move just happened */
15245 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
15249 } else if(move == backwardMostMove) {
15250 // [HGM] perhaps we should always do it like this, and forget the above?
15251 if((signed char)boards[move][EP_STATUS] >= 0) {
15252 *p++ = boards[move][EP_STATUS] + AAA;
15253 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
15264 /* [HGM] find reversible plies */
15265 { int i = 0, j=move;
15267 if (appData.debugMode) { int k;
15268 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
15269 for(k=backwardMostMove; k<=forwardMostMove; k++)
15270 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
15274 while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
15275 if( j == backwardMostMove ) i += initialRulePlies;
15276 sprintf(p, "%d ", i);
15277 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
15279 /* Fullmove number */
15280 sprintf(p, "%d", (move / 2) + 1);
15282 return StrSave(buf);
15286 ParseFEN(board, blackPlaysFirst, fen)
15288 int *blackPlaysFirst;
15298 /* [HGM] by default clear Crazyhouse holdings, if present */
15299 if(gameInfo.holdingsWidth) {
15300 for(i=0; i<BOARD_HEIGHT; i++) {
15301 board[i][0] = EmptySquare; /* black holdings */
15302 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
15303 board[i][1] = (ChessSquare) 0; /* black counts */
15304 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
15308 /* Piece placement data */
15309 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
15312 if (*p == '/' || *p == ' ' || (*p == '[' && i == 0) ) {
15313 if (*p == '/') p++;
15314 emptycount = gameInfo.boardWidth - j;
15315 while (emptycount--)
15316 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
15318 #if(BOARD_FILES >= 10)
15319 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
15320 p++; emptycount=10;
15321 if (j + emptycount > gameInfo.boardWidth) return FALSE;
15322 while (emptycount--)
15323 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
15325 } else if (isdigit(*p)) {
15326 emptycount = *p++ - '0';
15327 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
15328 if (j + emptycount > gameInfo.boardWidth) return FALSE;
15329 while (emptycount--)
15330 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
15331 } else if (*p == '+' || isalpha(*p)) {
15332 if (j >= gameInfo.boardWidth) return FALSE;
15334 piece = CharToPiece(*++p);
15335 if(piece == EmptySquare) return FALSE; /* unknown piece */
15336 piece = (ChessSquare) (PROMOTED piece ); p++;
15337 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
15338 } else piece = CharToPiece(*p++);
15340 if(piece==EmptySquare) return FALSE; /* unknown piece */
15341 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
15342 piece = (ChessSquare) (PROMOTED piece);
15343 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
15346 board[i][(j++)+gameInfo.holdingsWidth] = piece;
15352 while (*p == '/' || *p == ' ') p++;
15354 /* [HGM] look for Crazyhouse holdings here */
15355 while(*p==' ') p++;
15356 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
15358 if(*p == '-' ) p++; /* empty holdings */ else {
15359 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
15360 /* if we would allow FEN reading to set board size, we would */
15361 /* have to add holdings and shift the board read so far here */
15362 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
15364 if((int) piece >= (int) BlackPawn ) {
15365 i = (int)piece - (int)BlackPawn;
15366 i = PieceToNumber((ChessSquare)i);
15367 if( i >= gameInfo.holdingsSize ) return FALSE;
15368 board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
15369 board[BOARD_HEIGHT-1-i][1]++; /* black counts */
15371 i = (int)piece - (int)WhitePawn;
15372 i = PieceToNumber((ChessSquare)i);
15373 if( i >= gameInfo.holdingsSize ) return FALSE;
15374 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
15375 board[i][BOARD_WIDTH-2]++; /* black holdings */
15382 while(*p == ' ') p++;
15386 if(appData.colorNickNames) {
15387 if( c == appData.colorNickNames[0] ) c = 'w'; else
15388 if( c == appData.colorNickNames[1] ) c = 'b';
15392 *blackPlaysFirst = FALSE;
15395 *blackPlaysFirst = TRUE;
15401 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
15402 /* return the extra info in global variiables */
15404 /* set defaults in case FEN is incomplete */
15405 board[EP_STATUS] = EP_UNKNOWN;
15406 for(i=0; i<nrCastlingRights; i++ ) {
15407 board[CASTLING][i] =
15408 gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom ? NoRights : initialRights[i];
15409 } /* assume possible unless obviously impossible */
15410 if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
15411 if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
15412 if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
15413 && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
15414 if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
15415 if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
15416 if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
15417 && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
15420 while(*p==' ') p++;
15421 if(nrCastlingRights) {
15422 if(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-') {
15423 /* castling indicator present, so default becomes no castlings */
15424 for(i=0; i<nrCastlingRights; i++ ) {
15425 board[CASTLING][i] = NoRights;
15428 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
15429 (gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) &&
15430 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
15431 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
15432 char c = *p++; int whiteKingFile=NoRights, blackKingFile=NoRights;
15434 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
15435 if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
15436 if(board[0 ][i] == WhiteKing) whiteKingFile = i;
15438 if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
15439 whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
15440 if(whiteKingFile == NoRights || board[0][whiteKingFile] != WhiteUnicorn
15441 && board[0][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
15442 if(blackKingFile == NoRights || board[BOARD_HEIGHT-1][blackKingFile] != BlackUnicorn
15443 && board[BOARD_HEIGHT-1][blackKingFile] != BlackKing) blackKingFile = NoRights;
15446 for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
15447 board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
15448 board[CASTLING][2] = whiteKingFile;
15451 for(i=BOARD_LEFT; i<BOARD_RGHT && board[0][i]!=WhiteRook && i<whiteKingFile; i++);
15452 board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
15453 board[CASTLING][2] = whiteKingFile;
15456 for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
15457 board[CASTLING][3] = i != blackKingFile ? i : NoRights;
15458 board[CASTLING][5] = blackKingFile;
15461 for(i=BOARD_LEFT; i<BOARD_RGHT && board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
15462 board[CASTLING][4] = i != blackKingFile ? i : NoRights;
15463 board[CASTLING][5] = blackKingFile;
15466 default: /* FRC castlings */
15467 if(c >= 'a') { /* black rights */
15468 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
15469 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
15470 if(i == BOARD_RGHT) break;
15471 board[CASTLING][5] = i;
15473 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
15474 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
15476 board[CASTLING][3] = c;
15478 board[CASTLING][4] = c;
15479 } else { /* white rights */
15480 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
15481 if(board[0][i] == WhiteKing) break;
15482 if(i == BOARD_RGHT) break;
15483 board[CASTLING][2] = i;
15484 c -= AAA - 'a' + 'A';
15485 if(board[0][c] >= WhiteKing) break;
15487 board[CASTLING][0] = c;
15489 board[CASTLING][1] = c;
15493 for(i=0; i<nrCastlingRights; i++)
15494 if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
15495 if (appData.debugMode) {
15496 fprintf(debugFP, "FEN castling rights:");
15497 for(i=0; i<nrCastlingRights; i++)
15498 fprintf(debugFP, " %d", board[CASTLING][i]);
15499 fprintf(debugFP, "\n");
15502 while(*p==' ') p++;
15505 /* read e.p. field in games that know e.p. capture */
15506 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
15507 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
15509 p++; board[EP_STATUS] = EP_NONE;
15511 char c = *p++ - AAA;
15513 if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
15514 if(*p >= '0' && *p <='9') p++;
15515 board[EP_STATUS] = c;
15520 if(sscanf(p, "%d", &i) == 1) {
15521 FENrulePlies = i; /* 50-move ply counter */
15522 /* (The move number is still ignored) */
15529 EditPositionPasteFEN(char *fen)
15532 Board initial_position;
15534 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
15535 DisplayError(_("Bad FEN position in clipboard"), 0);
15538 int savedBlackPlaysFirst = blackPlaysFirst;
15539 EditPositionEvent();
15540 blackPlaysFirst = savedBlackPlaysFirst;
15541 CopyBoard(boards[0], initial_position);
15542 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
15543 EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
15544 DisplayBothClocks();
15545 DrawPosition(FALSE, boards[currentMove]);
15550 static char cseq[12] = "\\ ";
15552 Boolean set_cont_sequence(char *new_seq)
15557 // handle bad attempts to set the sequence
15559 return 0; // acceptable error - no debug
15561 len = strlen(new_seq);
15562 ret = (len > 0) && (len < sizeof(cseq));
15564 safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
15565 else if (appData.debugMode)
15566 fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
15571 reformat a source message so words don't cross the width boundary. internal
15572 newlines are not removed. returns the wrapped size (no null character unless
15573 included in source message). If dest is NULL, only calculate the size required
15574 for the dest buffer. lp argument indicats line position upon entry, and it's
15575 passed back upon exit.
15577 int wrap(char *dest, char *src, int count, int width, int *lp)
15579 int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
15581 cseq_len = strlen(cseq);
15582 old_line = line = *lp;
15583 ansi = len = clen = 0;
15585 for (i=0; i < count; i++)
15587 if (src[i] == '\033')
15590 // if we hit the width, back up
15591 if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
15593 // store i & len in case the word is too long
15594 old_i = i, old_len = len;
15596 // find the end of the last word
15597 while (i && src[i] != ' ' && src[i] != '\n')
15603 // word too long? restore i & len before splitting it
15604 if ((old_i-i+clen) >= width)
15611 if (i && src[i-1] == ' ')
15614 if (src[i] != ' ' && src[i] != '\n')
15621 // now append the newline and continuation sequence
15626 strncpy(dest+len, cseq, cseq_len);
15634 dest[len] = src[i];
15638 if (src[i] == '\n')
15643 if (dest && appData.debugMode)
15645 fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
15646 count, width, line, len, *lp);
15647 show_bytes(debugFP, src, count);
15648 fprintf(debugFP, "\ndest: ");
15649 show_bytes(debugFP, dest, len);
15650 fprintf(debugFP, "\n");
15652 *lp = dest ? line : old_line;
15657 // [HGM] vari: routines for shelving variations
15660 PushTail(int firstMove, int lastMove)
15662 int i, j, nrMoves = lastMove - firstMove;
15664 if(appData.icsActive) { // only in local mode
15665 forwardMostMove = currentMove; // mimic old ICS behavior
15668 if(storedGames >= MAX_VARIATIONS-1) return;
15670 // push current tail of game on stack
15671 savedResult[storedGames] = gameInfo.result;
15672 savedDetails[storedGames] = gameInfo.resultDetails;
15673 gameInfo.resultDetails = NULL;
15674 savedFirst[storedGames] = firstMove;
15675 savedLast [storedGames] = lastMove;
15676 savedFramePtr[storedGames] = framePtr;
15677 framePtr -= nrMoves; // reserve space for the boards
15678 for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
15679 CopyBoard(boards[framePtr+i], boards[firstMove+i]);
15680 for(j=0; j<MOVE_LEN; j++)
15681 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
15682 for(j=0; j<2*MOVE_LEN; j++)
15683 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
15684 timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
15685 timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
15686 pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
15687 pvInfoList[firstMove+i-1].depth = 0;
15688 commentList[framePtr+i] = commentList[firstMove+i];
15689 commentList[firstMove+i] = NULL;
15693 forwardMostMove = firstMove; // truncate game so we can start variation
15694 if(storedGames == 1) GreyRevert(FALSE);
15698 PopTail(Boolean annotate)
15701 char buf[8000], moveBuf[20];
15703 if(appData.icsActive) return FALSE; // only in local mode
15704 if(!storedGames) return FALSE; // sanity
15705 CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
15708 ToNrEvent(savedFirst[storedGames]); // sets currentMove
15709 nrMoves = savedLast[storedGames] - currentMove;
15712 if(!WhiteOnMove(currentMove))
15713 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
15714 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
15715 for(i=currentMove; i<forwardMostMove; i++) {
15717 snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
15718 else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
15719 strcat(buf, moveBuf);
15720 if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
15721 if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
15725 for(i=1; i<=nrMoves; i++) { // copy last variation back
15726 CopyBoard(boards[currentMove+i], boards[framePtr+i]);
15727 for(j=0; j<MOVE_LEN; j++)
15728 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
15729 for(j=0; j<2*MOVE_LEN; j++)
15730 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
15731 timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
15732 timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
15733 pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
15734 if(commentList[currentMove+i]) free(commentList[currentMove+i]);
15735 commentList[currentMove+i] = commentList[framePtr+i];
15736 commentList[framePtr+i] = NULL;
15738 if(annotate) AppendComment(currentMove+1, buf, FALSE);
15739 framePtr = savedFramePtr[storedGames];
15740 gameInfo.result = savedResult[storedGames];
15741 if(gameInfo.resultDetails != NULL) {
15742 free(gameInfo.resultDetails);
15744 gameInfo.resultDetails = savedDetails[storedGames];
15745 forwardMostMove = currentMove + nrMoves;
15746 if(storedGames == 0) GreyRevert(TRUE);
15752 { // remove all shelved variations
15754 for(i=0; i<storedGames; i++) {
15755 if(savedDetails[i])
15756 free(savedDetails[i]);
15757 savedDetails[i] = NULL;
15759 for(i=framePtr; i<MAX_MOVES; i++) {
15760 if(commentList[i]) free(commentList[i]);
15761 commentList[i] = NULL;
15763 framePtr = MAX_MOVES-1;
15768 LoadVariation(int index, char *text)
15769 { // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
15770 char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
15771 int level = 0, move;
15773 if(gameMode != EditGame && gameMode != AnalyzeMode) return;
15774 // first find outermost bracketing variation
15775 while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
15776 if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
15777 if(*p == '{') wait = '}'; else
15778 if(*p == '[') wait = ']'; else
15779 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
15780 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
15782 if(*p == wait) wait = NULLCHAR; // closing ]} found
15785 if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
15786 if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
15787 end[1] = NULLCHAR; // clip off comment beyond variation
15788 ToNrEvent(currentMove-1);
15789 PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
15790 // kludge: use ParsePV() to append variation to game
15791 move = currentMove;
15792 ParsePV(start, TRUE);
15793 forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
15794 ClearPremoveHighlights();
15796 ToNrEvent(currentMove+1);