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 MatchEvent(int mode)
1236 { // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
1237 /* Set up machine vs. machine match */
1238 if (appData.noChessProgram) {
1239 DisplayFatalError(_("Can't have a match with no chess programs"),
1245 if (*appData.loadGameFile != NULLCHAR) {
1246 int index = appData.loadGameIndex; // [HGM] autoinc
1247 if(index<0) lastIndex = index = 1;
1248 if (!LoadGameFromFile(appData.loadGameFile,
1250 appData.loadGameFile, FALSE)) {
1251 DisplayFatalError(_("Bad game file"), 0, 1);
1254 } else if (*appData.loadPositionFile != NULLCHAR) {
1255 int index = appData.loadPositionIndex; // [HGM] autoinc
1256 if(index<0) lastIndex = index = 1;
1257 if (!LoadPositionFromFile(appData.loadPositionFile,
1259 appData.loadPositionFile)) {
1260 DisplayFatalError(_("Bad position file"), 0, 1);
1264 first.matchWins = second.matchWins = 0; // [HGM] match: needed in later matches
\r
1269 InitBackEnd3 P((void))
1271 GameMode initialMode;
1275 InitChessProgram(&first, startedFromSetupPosition);
1277 if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
1278 free(programVersion);
1279 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1280 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1283 if (appData.icsActive) {
1285 /* [DM] Make a console window if needed [HGM] merged ifs */
1291 if (*appData.icsCommPort != NULLCHAR)
1292 len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1293 appData.icsCommPort);
1295 len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1296 appData.icsHost, appData.icsPort);
1298 if( (len > MSG_SIZ) && appData.debugMode )
1299 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1301 DisplayFatalError(buf, err, 1);
1306 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1308 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1309 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1310 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1311 } else if (appData.noChessProgram) {
1317 if (*appData.cmailGameName != NULLCHAR) {
1319 OpenLoopback(&cmailPR);
1321 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1325 DisplayMessage("", "");
1326 if (StrCaseCmp(appData.initialMode, "") == 0) {
1327 initialMode = BeginningOfGame;
1328 if(!appData.icsActive && appData.noChessProgram) { // [HGM] could be fall-back
1329 gameMode = MachinePlaysBlack; // "Machine Black" might have been implicitly highlighted
1330 ModeHighlight(); // make sure XBoard knows it is highlighted, so it will un-highlight it
1331 gameMode = BeginningOfGame; // in case BeginningOfGame now means "Edit Position"
1334 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1335 initialMode = TwoMachinesPlay;
1336 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1337 initialMode = AnalyzeFile;
1338 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1339 initialMode = AnalyzeMode;
1340 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1341 initialMode = MachinePlaysWhite;
1342 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1343 initialMode = MachinePlaysBlack;
1344 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1345 initialMode = EditGame;
1346 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1347 initialMode = EditPosition;
1348 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1349 initialMode = Training;
1351 len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1352 if( (len > MSG_SIZ) && appData.debugMode )
1353 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1355 DisplayFatalError(buf, 0, 2);
1359 if (appData.matchMode) {
1361 } else if (*appData.cmailGameName != NULLCHAR) {
1362 /* Set up cmail mode */
1363 ReloadCmailMsgEvent(TRUE);
1365 /* Set up other modes */
1366 if (initialMode == AnalyzeFile) {
1367 if (*appData.loadGameFile == NULLCHAR) {
1368 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1372 if (*appData.loadGameFile != NULLCHAR) {
1373 (void) LoadGameFromFile(appData.loadGameFile,
1374 appData.loadGameIndex,
1375 appData.loadGameFile, TRUE);
1376 } else if (*appData.loadPositionFile != NULLCHAR) {
1377 (void) LoadPositionFromFile(appData.loadPositionFile,
1378 appData.loadPositionIndex,
1379 appData.loadPositionFile);
1380 /* [HGM] try to make self-starting even after FEN load */
1381 /* to allow automatic setup of fairy variants with wtm */
1382 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1383 gameMode = BeginningOfGame;
1384 setboardSpoiledMachineBlack = 1;
1386 /* [HGM] loadPos: make that every new game uses the setup */
1387 /* from file as long as we do not switch variant */
1388 if(!blackPlaysFirst) {
1389 startedFromPositionFile = TRUE;
1390 CopyBoard(filePosition, boards[0]);
1393 if (initialMode == AnalyzeMode) {
1394 if (appData.noChessProgram) {
1395 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1398 if (appData.icsActive) {
1399 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1403 } else if (initialMode == AnalyzeFile) {
1404 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1405 ShowThinkingEvent();
1407 AnalysisPeriodicEvent(1);
1408 } else if (initialMode == MachinePlaysWhite) {
1409 if (appData.noChessProgram) {
1410 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1414 if (appData.icsActive) {
1415 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1419 MachineWhiteEvent();
1420 } else if (initialMode == MachinePlaysBlack) {
1421 if (appData.noChessProgram) {
1422 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1426 if (appData.icsActive) {
1427 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1431 MachineBlackEvent();
1432 } else if (initialMode == TwoMachinesPlay) {
1433 if (appData.noChessProgram) {
1434 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1438 if (appData.icsActive) {
1439 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1444 } else if (initialMode == EditGame) {
1446 } else if (initialMode == EditPosition) {
1447 EditPositionEvent();
1448 } else if (initialMode == Training) {
1449 if (*appData.loadGameFile == NULLCHAR) {
1450 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1459 * Establish will establish a contact to a remote host.port.
1460 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1461 * used to talk to the host.
1462 * Returns 0 if okay, error code if not.
1469 if (*appData.icsCommPort != NULLCHAR) {
1470 /* Talk to the host through a serial comm port */
1471 return OpenCommPort(appData.icsCommPort, &icsPR);
1473 } else if (*appData.gateway != NULLCHAR) {
1474 if (*appData.remoteShell == NULLCHAR) {
1475 /* Use the rcmd protocol to run telnet program on a gateway host */
1476 snprintf(buf, sizeof(buf), "%s %s %s",
1477 appData.telnetProgram, appData.icsHost, appData.icsPort);
1478 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1481 /* Use the rsh program to run telnet program on a gateway host */
1482 if (*appData.remoteUser == NULLCHAR) {
1483 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1484 appData.gateway, appData.telnetProgram,
1485 appData.icsHost, appData.icsPort);
1487 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1488 appData.remoteShell, appData.gateway,
1489 appData.remoteUser, appData.telnetProgram,
1490 appData.icsHost, appData.icsPort);
1492 return StartChildProcess(buf, "", &icsPR);
1495 } else if (appData.useTelnet) {
1496 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1499 /* TCP socket interface differs somewhat between
1500 Unix and NT; handle details in the front end.
1502 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1506 void EscapeExpand(char *p, char *q)
1507 { // [HGM] initstring: routine to shape up string arguments
1508 while(*p++ = *q++) if(p[-1] == '\\')
1510 case 'n': p[-1] = '\n'; break;
1511 case 'r': p[-1] = '\r'; break;
1512 case 't': p[-1] = '\t'; break;
1513 case '\\': p[-1] = '\\'; break;
1514 case 0: *p = 0; return;
1515 default: p[-1] = q[-1]; break;
1520 show_bytes(fp, buf, count)
1526 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1527 fprintf(fp, "\\%03o", *buf & 0xff);
1536 /* Returns an errno value */
1538 OutputMaybeTelnet(pr, message, count, outError)
1544 char buf[8192], *p, *q, *buflim;
1545 int left, newcount, outcount;
1547 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1548 *appData.gateway != NULLCHAR) {
1549 if (appData.debugMode) {
1550 fprintf(debugFP, ">ICS: ");
1551 show_bytes(debugFP, message, count);
1552 fprintf(debugFP, "\n");
1554 return OutputToProcess(pr, message, count, outError);
1557 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1564 if (appData.debugMode) {
1565 fprintf(debugFP, ">ICS: ");
1566 show_bytes(debugFP, buf, newcount);
1567 fprintf(debugFP, "\n");
1569 outcount = OutputToProcess(pr, buf, newcount, outError);
1570 if (outcount < newcount) return -1; /* to be sure */
1577 } else if (((unsigned char) *p) == TN_IAC) {
1578 *q++ = (char) TN_IAC;
1585 if (appData.debugMode) {
1586 fprintf(debugFP, ">ICS: ");
1587 show_bytes(debugFP, buf, newcount);
1588 fprintf(debugFP, "\n");
1590 outcount = OutputToProcess(pr, buf, newcount, outError);
1591 if (outcount < newcount) return -1; /* to be sure */
1596 read_from_player(isr, closure, message, count, error)
1603 int outError, outCount;
1604 static int gotEof = 0;
1606 /* Pass data read from player on to ICS */
1609 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1610 if (outCount < count) {
1611 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1613 } else if (count < 0) {
1614 RemoveInputSource(isr);
1615 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1616 } else if (gotEof++ > 0) {
1617 RemoveInputSource(isr);
1618 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1624 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1625 if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
1626 connectionAlive = FALSE; // only sticks if no response to 'date' command.
1627 SendToICS("date\n");
1628 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1631 /* added routine for printf style output to ics */
1632 void ics_printf(char *format, ...)
1634 char buffer[MSG_SIZ];
1637 va_start(args, format);
1638 vsnprintf(buffer, sizeof(buffer), format, args);
1639 buffer[sizeof(buffer)-1] = '\0';
1648 int count, outCount, outError;
1650 if (icsPR == NULL) return;
1653 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1654 if (outCount < count) {
1655 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1659 /* This is used for sending logon scripts to the ICS. Sending
1660 without a delay causes problems when using timestamp on ICC
1661 (at least on my machine). */
1663 SendToICSDelayed(s,msdelay)
1667 int count, outCount, outError;
1669 if (icsPR == NULL) return;
1672 if (appData.debugMode) {
1673 fprintf(debugFP, ">ICS: ");
1674 show_bytes(debugFP, s, count);
1675 fprintf(debugFP, "\n");
1677 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1679 if (outCount < count) {
1680 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1685 /* Remove all highlighting escape sequences in s
1686 Also deletes any suffix starting with '('
1689 StripHighlightAndTitle(s)
1692 static char retbuf[MSG_SIZ];
1695 while (*s != NULLCHAR) {
1696 while (*s == '\033') {
1697 while (*s != NULLCHAR && !isalpha(*s)) s++;
1698 if (*s != NULLCHAR) s++;
1700 while (*s != NULLCHAR && *s != '\033') {
1701 if (*s == '(' || *s == '[') {
1712 /* Remove all highlighting escape sequences in s */
1717 static char retbuf[MSG_SIZ];
1720 while (*s != NULLCHAR) {
1721 while (*s == '\033') {
1722 while (*s != NULLCHAR && !isalpha(*s)) s++;
1723 if (*s != NULLCHAR) s++;
1725 while (*s != NULLCHAR && *s != '\033') {
1733 char *variantNames[] = VARIANT_NAMES;
1738 return variantNames[v];
1742 /* Identify a variant from the strings the chess servers use or the
1743 PGN Variant tag names we use. */
1750 VariantClass v = VariantNormal;
1751 int i, found = FALSE;
1757 /* [HGM] skip over optional board-size prefixes */
1758 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
1759 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
1760 while( *e++ != '_');
1763 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
1767 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1768 if (StrCaseStr(e, variantNames[i])) {
1769 v = (VariantClass) i;
1776 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
1777 || StrCaseStr(e, "wild/fr")
1778 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
1779 v = VariantFischeRandom;
1780 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
1781 (i = 1, p = StrCaseStr(e, "w"))) {
1783 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
1790 case 0: /* FICS only, actually */
1792 /* Castling legal even if K starts on d-file */
1793 v = VariantWildCastle;
1798 /* Castling illegal even if K & R happen to start in
1799 normal positions. */
1800 v = VariantNoCastle;
1813 /* Castling legal iff K & R start in normal positions */
1819 /* Special wilds for position setup; unclear what to do here */
1820 v = VariantLoadable;
1823 /* Bizarre ICC game */
1824 v = VariantTwoKings;
1827 v = VariantKriegspiel;
1833 v = VariantFischeRandom;
1836 v = VariantCrazyhouse;
1839 v = VariantBughouse;
1845 /* Not quite the same as FICS suicide! */
1846 v = VariantGiveaway;
1852 v = VariantShatranj;
1855 /* Temporary names for future ICC types. The name *will* change in
1856 the next xboard/WinBoard release after ICC defines it. */
1894 v = VariantCapablanca;
1897 v = VariantKnightmate;
1903 v = VariantCylinder;
1909 v = VariantCapaRandom;
1912 v = VariantBerolina;
1924 /* Found "wild" or "w" in the string but no number;
1925 must assume it's normal chess. */
1929 len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
1930 if( (len > MSG_SIZ) && appData.debugMode )
1931 fprintf(debugFP, "StringToVariant: buffer truncated.\n");
1933 DisplayError(buf, 0);
1939 if (appData.debugMode) {
1940 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
1941 e, wnum, VariantName(v));
1946 static int leftover_start = 0, leftover_len = 0;
1947 char star_match[STAR_MATCH_N][MSG_SIZ];
1949 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
1950 advance *index beyond it, and set leftover_start to the new value of
1951 *index; else return FALSE. If pattern contains the character '*', it
1952 matches any sequence of characters not containing '\r', '\n', or the
1953 character following the '*' (if any), and the matched sequence(s) are
1954 copied into star_match.
1957 looking_at(buf, index, pattern)
1962 char *bufp = &buf[*index], *patternp = pattern;
1964 char *matchp = star_match[0];
1967 if (*patternp == NULLCHAR) {
1968 *index = leftover_start = bufp - buf;
1972 if (*bufp == NULLCHAR) return FALSE;
1973 if (*patternp == '*') {
1974 if (*bufp == *(patternp + 1)) {
1976 matchp = star_match[++star_count];
1980 } else if (*bufp == '\n' || *bufp == '\r') {
1982 if (*patternp == NULLCHAR)
1987 *matchp++ = *bufp++;
1991 if (*patternp != *bufp) return FALSE;
1998 SendToPlayer(data, length)
2002 int error, outCount;
2003 outCount = OutputToProcess(NoProc, data, length, &error);
2004 if (outCount < length) {
2005 DisplayFatalError(_("Error writing to display"), error, 1);
2010 PackHolding(packed, holding)
2022 switch (runlength) {
2033 sprintf(q, "%d", runlength);
2045 /* Telnet protocol requests from the front end */
2047 TelnetRequest(ddww, option)
2048 unsigned char ddww, option;
2050 unsigned char msg[3];
2051 int outCount, outError;
2053 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
2055 if (appData.debugMode) {
2056 char buf1[8], buf2[8], *ddwwStr, *optionStr;
2072 snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2081 snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2084 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2089 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2091 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2098 if (!appData.icsActive) return;
2099 TelnetRequest(TN_DO, TN_ECHO);
2105 if (!appData.icsActive) return;
2106 TelnetRequest(TN_DONT, TN_ECHO);
2110 CopyHoldings(Board board, char *holdings, ChessSquare lowestPiece)
2112 /* put the holdings sent to us by the server on the board holdings area */
2113 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2117 if(gameInfo.holdingsWidth < 2) return;
2118 if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2119 return; // prevent overwriting by pre-board holdings
2121 if( (int)lowestPiece >= BlackPawn ) {
2124 holdingsStartRow = BOARD_HEIGHT-1;
2127 holdingsColumn = BOARD_WIDTH-1;
2128 countsColumn = BOARD_WIDTH-2;
2129 holdingsStartRow = 0;
2133 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
2134 board[i][holdingsColumn] = EmptySquare;
2135 board[i][countsColumn] = (ChessSquare) 0;
2137 while( (p=*holdings++) != NULLCHAR ) {
2138 piece = CharToPiece( ToUpper(p) );
2139 if(piece == EmptySquare) continue;
2140 /*j = (int) piece - (int) WhitePawn;*/
2141 j = PieceToNumber(piece);
2142 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2143 if(j < 0) continue; /* should not happen */
2144 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2145 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2146 board[holdingsStartRow+j*direction][countsColumn]++;
2152 VariantSwitch(Board board, VariantClass newVariant)
2154 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2155 static Board oldBoard;
2157 startedFromPositionFile = FALSE;
2158 if(gameInfo.variant == newVariant) return;
2160 /* [HGM] This routine is called each time an assignment is made to
2161 * gameInfo.variant during a game, to make sure the board sizes
2162 * are set to match the new variant. If that means adding or deleting
2163 * holdings, we shift the playing board accordingly
2164 * This kludge is needed because in ICS observe mode, we get boards
2165 * of an ongoing game without knowing the variant, and learn about the
2166 * latter only later. This can be because of the move list we requested,
2167 * in which case the game history is refilled from the beginning anyway,
2168 * but also when receiving holdings of a crazyhouse game. In the latter
2169 * case we want to add those holdings to the already received position.
2173 if (appData.debugMode) {
2174 fprintf(debugFP, "Switch board from %s to %s\n",
2175 VariantName(gameInfo.variant), VariantName(newVariant));
2176 setbuf(debugFP, NULL);
2178 shuffleOpenings = 0; /* [HGM] shuffle */
2179 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2183 newWidth = 9; newHeight = 9;
2184 gameInfo.holdingsSize = 7;
2185 case VariantBughouse:
2186 case VariantCrazyhouse:
2187 newHoldingsWidth = 2; break;
2191 newHoldingsWidth = 2;
2192 gameInfo.holdingsSize = 8;
2195 case VariantCapablanca:
2196 case VariantCapaRandom:
2199 newHoldingsWidth = gameInfo.holdingsSize = 0;
2202 if(newWidth != gameInfo.boardWidth ||
2203 newHeight != gameInfo.boardHeight ||
2204 newHoldingsWidth != gameInfo.holdingsWidth ) {
2206 /* shift position to new playing area, if needed */
2207 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2208 for(i=0; i<BOARD_HEIGHT; i++)
2209 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2210 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2212 for(i=0; i<newHeight; i++) {
2213 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2214 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2216 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2217 for(i=0; i<BOARD_HEIGHT; i++)
2218 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2219 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2222 gameInfo.boardWidth = newWidth;
2223 gameInfo.boardHeight = newHeight;
2224 gameInfo.holdingsWidth = newHoldingsWidth;
2225 gameInfo.variant = newVariant;
2226 InitDrawingSizes(-2, 0);
2227 } else gameInfo.variant = newVariant;
2228 CopyBoard(oldBoard, board); // remember correctly formatted board
2229 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2230 DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2233 static int loggedOn = FALSE;
2235 /*-- Game start info cache: --*/
2237 char gs_kind[MSG_SIZ];
2238 static char player1Name[128] = "";
2239 static char player2Name[128] = "";
2240 static char cont_seq[] = "\n\\ ";
2241 static int player1Rating = -1;
2242 static int player2Rating = -1;
2243 /*----------------------------*/
2245 ColorClass curColor = ColorNormal;
2246 int suppressKibitz = 0;
2249 Boolean soughtPending = FALSE;
2250 Boolean seekGraphUp;
2251 #define MAX_SEEK_ADS 200
2253 char *seekAdList[MAX_SEEK_ADS];
2254 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2255 float tcList[MAX_SEEK_ADS];
2256 char colorList[MAX_SEEK_ADS];
2257 int nrOfSeekAds = 0;
2258 int minRating = 1010, maxRating = 2800;
2259 int hMargin = 10, vMargin = 20, h, w;
2260 extern int squareSize, lineGap;
2265 int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2266 xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2267 if(r < minRating+100 && r >=0 ) r = minRating+100;
2268 if(r > maxRating) r = maxRating;
2269 if(tc < 1.) tc = 1.;
2270 if(tc > 95.) tc = 95.;
2271 x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2272 y = ((double)r - minRating)/(maxRating - minRating)
2273 * (h-vMargin-squareSize/8-1) + vMargin;
2274 if(ratingList[i] < 0) y = vMargin + squareSize/4;
2275 if(strstr(seekAdList[i], " u ")) color = 1;
2276 if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2277 !strstr(seekAdList[i], "bullet") &&
2278 !strstr(seekAdList[i], "blitz") &&
2279 !strstr(seekAdList[i], "standard") ) color = 2;
2280 if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2281 DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2285 AddAd(char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
2287 char buf[MSG_SIZ], *ext = "";
2288 VariantClass v = StringToVariant(type);
2289 if(strstr(type, "wild")) {
2290 ext = type + 4; // append wild number
2291 if(v == VariantFischeRandom) type = "chess960"; else
2292 if(v == VariantLoadable) type = "setup"; else
2293 type = VariantName(v);
2295 snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2296 if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2297 if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2298 ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2299 sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2300 tcList[nrOfSeekAds] = base + (2./3.)*inc;
2301 seekNrList[nrOfSeekAds] = nr;
2302 zList[nrOfSeekAds] = 0;
2303 seekAdList[nrOfSeekAds++] = StrSave(buf);
2304 if(plot) PlotSeekAd(nrOfSeekAds-1);
2311 int x = xList[i], y = yList[i], d=squareSize/4, k;
2312 DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2313 if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2314 // now replot every dot that overlapped
2315 for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2316 int xx = xList[k], yy = yList[k];
2317 if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2318 DrawSeekDot(xx, yy, colorList[k]);
2323 RemoveSeekAd(int nr)
2326 for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2328 if(seekAdList[i]) free(seekAdList[i]);
2329 seekAdList[i] = seekAdList[--nrOfSeekAds];
2330 seekNrList[i] = seekNrList[nrOfSeekAds];
2331 ratingList[i] = ratingList[nrOfSeekAds];
2332 colorList[i] = colorList[nrOfSeekAds];
2333 tcList[i] = tcList[nrOfSeekAds];
2334 xList[i] = xList[nrOfSeekAds];
2335 yList[i] = yList[nrOfSeekAds];
2336 zList[i] = zList[nrOfSeekAds];
2337 seekAdList[nrOfSeekAds] = NULL;
2343 MatchSoughtLine(char *line)
2345 char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2346 int nr, base, inc, u=0; char dummy;
2348 if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2349 sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2351 (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2352 sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
2353 // match: compact and save the line
2354 AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2364 if(!seekGraphUp) return FALSE;
2365 h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap;
2366 w = BOARD_WIDTH * (squareSize + lineGap) + lineGap;
2368 DrawSeekBackground(0, 0, w, h);
2369 DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2370 DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2371 for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2372 int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2374 DrawSeekAxis(hMargin+5*(i%500==0), yy, hMargin-5, yy); // rating ticks
2377 snprintf(buf, MSG_SIZ, "%d", i);
2378 DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2381 DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2382 for(i=1; i<100; i+=(i<10?1:5)) {
2383 int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2384 DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2385 if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2387 snprintf(buf, MSG_SIZ, "%d", i);
2388 DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2391 for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2395 int SeekGraphClick(ClickType click, int x, int y, int moving)
2397 static int lastDown = 0, displayed = 0, lastSecond;
2398 if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2399 if(click == Release || moving) return FALSE;
2401 soughtPending = TRUE;
2402 SendToICS(ics_prefix);
2403 SendToICS("sought\n"); // should this be "sought all"?
2404 } else { // issue challenge based on clicked ad
2405 int dist = 10000; int i, closest = 0, second = 0;
2406 for(i=0; i<nrOfSeekAds; i++) {
2407 int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
2408 if(d < dist) { dist = d; closest = i; }
2409 second += (d - zList[i] < 120); // count in-range ads
2410 if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2414 second = (second > 1);
2415 if(displayed != closest || second != lastSecond) {
2416 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2417 lastSecond = second; displayed = closest;
2419 if(click == Press) {
2420 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2423 } // on press 'hit', only show info
2424 if(moving == 2) return TRUE; // ignore right up-clicks on dot
2425 snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2426 SendToICS(ics_prefix);
2428 return TRUE; // let incoming board of started game pop down the graph
2429 } else if(click == Release) { // release 'miss' is ignored
2430 zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2431 if(moving == 2) { // right up-click
2432 nrOfSeekAds = 0; // refresh graph
2433 soughtPending = TRUE;
2434 SendToICS(ics_prefix);
2435 SendToICS("sought\n"); // should this be "sought all"?
2438 } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2439 // press miss or release hit 'pop down' seek graph
2440 seekGraphUp = FALSE;
2441 DrawPosition(TRUE, NULL);
2447 read_from_ics(isr, closure, data, count, error)
2454 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2455 #define STARTED_NONE 0
2456 #define STARTED_MOVES 1
2457 #define STARTED_BOARD 2
2458 #define STARTED_OBSERVE 3
2459 #define STARTED_HOLDINGS 4
2460 #define STARTED_CHATTER 5
2461 #define STARTED_COMMENT 6
2462 #define STARTED_MOVES_NOHIDE 7
2464 static int started = STARTED_NONE;
2465 static char parse[20000];
2466 static int parse_pos = 0;
2467 static char buf[BUF_SIZE + 1];
2468 static int firstTime = TRUE, intfSet = FALSE;
2469 static ColorClass prevColor = ColorNormal;
2470 static int savingComment = FALSE;
2471 static int cmatch = 0; // continuation sequence match
2478 int backup; /* [DM] For zippy color lines */
2480 char talker[MSG_SIZ]; // [HGM] chat
2483 connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2485 if (appData.debugMode) {
2487 fprintf(debugFP, "<ICS: ");
2488 show_bytes(debugFP, data, count);
2489 fprintf(debugFP, "\n");
2493 if (appData.debugMode) { int f = forwardMostMove;
2494 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2495 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2496 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2499 /* If last read ended with a partial line that we couldn't parse,
2500 prepend it to the new read and try again. */
2501 if (leftover_len > 0) {
2502 for (i=0; i<leftover_len; i++)
2503 buf[i] = buf[leftover_start + i];
2506 /* copy new characters into the buffer */
2507 bp = buf + leftover_len;
2508 buf_len=leftover_len;
2509 for (i=0; i<count; i++)
2512 if (data[i] == '\r')
2515 // join lines split by ICS?
2516 if (!appData.noJoin)
2519 Joining just consists of finding matches against the
2520 continuation sequence, and discarding that sequence
2521 if found instead of copying it. So, until a match
2522 fails, there's nothing to do since it might be the
2523 complete sequence, and thus, something we don't want
2526 if (data[i] == cont_seq[cmatch])
2529 if (cmatch == strlen(cont_seq))
2531 cmatch = 0; // complete match. just reset the counter
2534 it's possible for the ICS to not include the space
2535 at the end of the last word, making our [correct]
2536 join operation fuse two separate words. the server
2537 does this when the space occurs at the width setting.
2539 if (!buf_len || buf[buf_len-1] != ' ')
2550 match failed, so we have to copy what matched before
2551 falling through and copying this character. In reality,
2552 this will only ever be just the newline character, but
2553 it doesn't hurt to be precise.
2555 strncpy(bp, cont_seq, cmatch);
2567 buf[buf_len] = NULLCHAR;
2568 // next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2573 while (i < buf_len) {
2574 /* Deal with part of the TELNET option negotiation
2575 protocol. We refuse to do anything beyond the
2576 defaults, except that we allow the WILL ECHO option,
2577 which ICS uses to turn off password echoing when we are
2578 directly connected to it. We reject this option
2579 if localLineEditing mode is on (always on in xboard)
2580 and we are talking to port 23, which might be a real
2581 telnet server that will try to keep WILL ECHO on permanently.
2583 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2584 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2585 unsigned char option;
2587 switch ((unsigned char) buf[++i]) {
2589 if (appData.debugMode)
2590 fprintf(debugFP, "\n<WILL ");
2591 switch (option = (unsigned char) buf[++i]) {
2593 if (appData.debugMode)
2594 fprintf(debugFP, "ECHO ");
2595 /* Reply only if this is a change, according
2596 to the protocol rules. */
2597 if (remoteEchoOption) break;
2598 if (appData.localLineEditing &&
2599 atoi(appData.icsPort) == TN_PORT) {
2600 TelnetRequest(TN_DONT, TN_ECHO);
2603 TelnetRequest(TN_DO, TN_ECHO);
2604 remoteEchoOption = TRUE;
2608 if (appData.debugMode)
2609 fprintf(debugFP, "%d ", option);
2610 /* Whatever this is, we don't want it. */
2611 TelnetRequest(TN_DONT, option);
2616 if (appData.debugMode)
2617 fprintf(debugFP, "\n<WONT ");
2618 switch (option = (unsigned char) buf[++i]) {
2620 if (appData.debugMode)
2621 fprintf(debugFP, "ECHO ");
2622 /* Reply only if this is a change, according
2623 to the protocol rules. */
2624 if (!remoteEchoOption) break;
2626 TelnetRequest(TN_DONT, TN_ECHO);
2627 remoteEchoOption = FALSE;
2630 if (appData.debugMode)
2631 fprintf(debugFP, "%d ", (unsigned char) option);
2632 /* Whatever this is, it must already be turned
2633 off, because we never agree to turn on
2634 anything non-default, so according to the
2635 protocol rules, we don't reply. */
2640 if (appData.debugMode)
2641 fprintf(debugFP, "\n<DO ");
2642 switch (option = (unsigned char) buf[++i]) {
2644 /* Whatever this is, we refuse to do it. */
2645 if (appData.debugMode)
2646 fprintf(debugFP, "%d ", option);
2647 TelnetRequest(TN_WONT, option);
2652 if (appData.debugMode)
2653 fprintf(debugFP, "\n<DONT ");
2654 switch (option = (unsigned char) buf[++i]) {
2656 if (appData.debugMode)
2657 fprintf(debugFP, "%d ", option);
2658 /* Whatever this is, we are already not doing
2659 it, because we never agree to do anything
2660 non-default, so according to the protocol
2661 rules, we don't reply. */
2666 if (appData.debugMode)
2667 fprintf(debugFP, "\n<IAC ");
2668 /* Doubled IAC; pass it through */
2672 if (appData.debugMode)
2673 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2674 /* Drop all other telnet commands on the floor */
2677 if (oldi > next_out)
2678 SendToPlayer(&buf[next_out], oldi - next_out);
2684 /* OK, this at least will *usually* work */
2685 if (!loggedOn && looking_at(buf, &i, "ics%")) {
2689 if (loggedOn && !intfSet) {
2690 if (ics_type == ICS_ICC) {
2691 snprintf(str, MSG_SIZ,
2692 "/set-quietly interface %s\n/set-quietly style 12\n",
2694 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2695 strcat(str, "/set-2 51 1\n/set seek 1\n");
2696 } else if (ics_type == ICS_CHESSNET) {
2697 snprintf(str, MSG_SIZ, "/style 12\n");
2699 safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
2700 strcat(str, programVersion);
2701 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2702 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2703 strcat(str, "$iset seekremove 1\n$set seek 1\n");
2705 strcat(str, "$iset nohighlight 1\n");
2707 strcat(str, "$iset lock 1\n$style 12\n");
2710 NotifyFrontendLogin();
2714 if (started == STARTED_COMMENT) {
2715 /* Accumulate characters in comment */
2716 parse[parse_pos++] = buf[i];
2717 if (buf[i] == '\n') {
2718 parse[parse_pos] = NULLCHAR;
2719 if(chattingPartner>=0) {
2721 snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
2722 OutputChatMessage(chattingPartner, mess);
2723 chattingPartner = -1;
2724 next_out = i+1; // [HGM] suppress printing in ICS window
2726 if(!suppressKibitz) // [HGM] kibitz
2727 AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
2728 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2729 int nrDigit = 0, nrAlph = 0, j;
2730 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2731 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2732 parse[parse_pos] = NULLCHAR;
2733 // try to be smart: if it does not look like search info, it should go to
2734 // ICS interaction window after all, not to engine-output window.
2735 for(j=0; j<parse_pos; j++) { // count letters and digits
2736 nrDigit += (parse[j] >= '0' && parse[j] <= '9');
2737 nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
2738 nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
2740 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
2741 int depth=0; float score;
2742 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
2743 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
2744 pvInfoList[forwardMostMove-1].depth = depth;
2745 pvInfoList[forwardMostMove-1].score = 100*score;
2747 OutputKibitz(suppressKibitz, parse);
2750 snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
2751 SendToPlayer(tmp, strlen(tmp));
2753 next_out = i+1; // [HGM] suppress printing in ICS window
2755 started = STARTED_NONE;
2757 /* Don't match patterns against characters in comment */
2762 if (started == STARTED_CHATTER) {
2763 if (buf[i] != '\n') {
2764 /* Don't match patterns against characters in chatter */
2768 started = STARTED_NONE;
2769 if(suppressKibitz) next_out = i+1;
2772 /* Kludge to deal with rcmd protocol */
2773 if (firstTime && looking_at(buf, &i, "\001*")) {
2774 DisplayFatalError(&buf[1], 0, 1);
2780 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
2783 if (appData.debugMode)
2784 fprintf(debugFP, "ics_type %d\n", ics_type);
2787 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
2788 ics_type = ICS_FICS;
2790 if (appData.debugMode)
2791 fprintf(debugFP, "ics_type %d\n", ics_type);
2794 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
2795 ics_type = ICS_CHESSNET;
2797 if (appData.debugMode)
2798 fprintf(debugFP, "ics_type %d\n", ics_type);
2803 (looking_at(buf, &i, "\"*\" is *a registered name") ||
2804 looking_at(buf, &i, "Logging you in as \"*\"") ||
2805 looking_at(buf, &i, "will be \"*\""))) {
2806 safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
2810 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
2812 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
2813 DisplayIcsInteractionTitle(buf);
2814 have_set_title = TRUE;
2817 /* skip finger notes */
2818 if (started == STARTED_NONE &&
2819 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
2820 (buf[i] == '1' && buf[i+1] == '0')) &&
2821 buf[i+2] == ':' && buf[i+3] == ' ') {
2822 started = STARTED_CHATTER;
2828 // [HGM] seekgraph: recognize sought lines and end-of-sought message
2829 if(appData.seekGraph) {
2830 if(soughtPending && MatchSoughtLine(buf+i)) {
2831 i = strstr(buf+i, "rated") - buf;
2832 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2833 next_out = leftover_start = i;
2834 started = STARTED_CHATTER;
2835 suppressKibitz = TRUE;
2838 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
2839 && looking_at(buf, &i, "* ads displayed")) {
2840 soughtPending = FALSE;
2845 if(appData.autoRefresh) {
2846 if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
2847 int s = (ics_type == ICS_ICC); // ICC format differs
2849 AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
2850 star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
2851 looking_at(buf, &i, "*% "); // eat prompt
2852 if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
2853 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2854 next_out = i; // suppress
2857 if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
2858 char *p = star_match[0];
2860 if(seekGraphUp) RemoveSeekAd(atoi(p));
2861 while(*p && *p++ != ' '); // next
2863 looking_at(buf, &i, "*% "); // eat prompt
2864 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2871 /* skip formula vars */
2872 if (started == STARTED_NONE &&
2873 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
2874 started = STARTED_CHATTER;
2879 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
2880 if (appData.autoKibitz && started == STARTED_NONE &&
2881 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
2882 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
2883 if((looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
2884 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
2885 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
2886 suppressKibitz = TRUE;
2887 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2889 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
2890 && (gameMode == IcsPlayingWhite)) ||
2891 (StrStr(star_match[0], gameInfo.black) == star_match[0]
2892 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
2893 started = STARTED_CHATTER; // own kibitz we simply discard
2895 started = STARTED_COMMENT; // make sure it will be collected in parse[]
2896 parse_pos = 0; parse[0] = NULLCHAR;
2897 savingComment = TRUE;
2898 suppressKibitz = gameMode != IcsObserving ? 2 :
2899 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
2903 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
2904 looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
2905 && atoi(star_match[0])) {
2906 // suppress the acknowledgements of our own autoKibitz
2908 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2909 if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
2910 SendToPlayer(star_match[0], strlen(star_match[0]));
2911 if(looking_at(buf, &i, "*% ")) // eat prompt
2912 suppressKibitz = FALSE;
2916 } // [HGM] kibitz: end of patch
2918 // [HGM] chat: intercept tells by users for which we have an open chat window
2920 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
2921 looking_at(buf, &i, "* whispers:") ||
2922 looking_at(buf, &i, "* kibitzes:") ||
2923 looking_at(buf, &i, "* shouts:") ||
2924 looking_at(buf, &i, "* c-shouts:") ||
2925 looking_at(buf, &i, "--> * ") ||
2926 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
2927 looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
2928 looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
2929 looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
2931 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
2932 chattingPartner = -1;
2934 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
2935 for(p=0; p<MAX_CHAT; p++) {
2936 if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
2937 talker[0] = '['; strcat(talker, "] ");
2938 Colorize(channel == 1 ? ColorChannel1 : ColorChannel, FALSE);
2939 chattingPartner = p; break;
2942 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
2943 for(p=0; p<MAX_CHAT; p++) {
2944 if(!strcmp("kibitzes", chatPartner[p])) {
2945 talker[0] = '['; strcat(talker, "] ");
2946 chattingPartner = p; break;
2949 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
2950 for(p=0; p<MAX_CHAT; p++) {
2951 if(!strcmp("whispers", chatPartner[p])) {
2952 talker[0] = '['; strcat(talker, "] ");
2953 chattingPartner = p; break;
2956 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
2957 if(buf[i-8] == '-' && buf[i-3] == 't')
2958 for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
2959 if(!strcmp("c-shouts", chatPartner[p])) {
2960 talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
2961 chattingPartner = p; break;
2964 if(chattingPartner < 0)
2965 for(p=0; p<MAX_CHAT; p++) {
2966 if(!strcmp("shouts", chatPartner[p])) {
2967 if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
2968 else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
2969 else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
2970 chattingPartner = p; break;
2974 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
2975 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
2976 talker[0] = 0; Colorize(ColorTell, FALSE);
2977 chattingPartner = p; break;
2979 if(chattingPartner<0) i = oldi; else {
2980 Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
2981 if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
2982 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2983 started = STARTED_COMMENT;
2984 parse_pos = 0; parse[0] = NULLCHAR;
2985 savingComment = 3 + chattingPartner; // counts as TRUE
2986 suppressKibitz = TRUE;
2989 } // [HGM] chat: end of patch
2992 if (appData.zippyTalk || appData.zippyPlay) {
2993 /* [DM] Backup address for color zippy lines */
2995 if (loggedOn == TRUE)
2996 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
2997 (appData.zippyPlay && ZippyMatch(buf, &backup)));
2999 } // [DM] 'else { ' deleted
3001 /* Regular tells and says */
3002 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
3003 looking_at(buf, &i, "* (your partner) tells you: ") ||
3004 looking_at(buf, &i, "* says: ") ||
3005 /* Don't color "message" or "messages" output */
3006 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
3007 looking_at(buf, &i, "*. * at *:*: ") ||
3008 looking_at(buf, &i, "--* (*:*): ") ||
3009 /* Message notifications (same color as tells) */
3010 looking_at(buf, &i, "* has left a message ") ||
3011 looking_at(buf, &i, "* just sent you a message:\n") ||
3012 /* Whispers and kibitzes */
3013 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
3014 looking_at(buf, &i, "* kibitzes: ") ||
3016 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
3018 if (tkind == 1 && strchr(star_match[0], ':')) {
3019 /* Avoid "tells you:" spoofs in channels */
3022 if (star_match[0][0] == NULLCHAR ||
3023 strchr(star_match[0], ' ') ||
3024 (tkind == 3 && strchr(star_match[1], ' '))) {
3025 /* Reject bogus matches */
3028 if (appData.colorize) {
3029 if (oldi > next_out) {
3030 SendToPlayer(&buf[next_out], oldi - next_out);
3035 Colorize(ColorTell, FALSE);
3036 curColor = ColorTell;
3039 Colorize(ColorKibitz, FALSE);
3040 curColor = ColorKibitz;
3043 p = strrchr(star_match[1], '(');
3050 Colorize(ColorChannel1, FALSE);
3051 curColor = ColorChannel1;
3053 Colorize(ColorChannel, FALSE);
3054 curColor = ColorChannel;
3058 curColor = ColorNormal;
3062 if (started == STARTED_NONE && appData.autoComment &&
3063 (gameMode == IcsObserving ||
3064 gameMode == IcsPlayingWhite ||
3065 gameMode == IcsPlayingBlack)) {
3066 parse_pos = i - oldi;
3067 memcpy(parse, &buf[oldi], parse_pos);
3068 parse[parse_pos] = NULLCHAR;
3069 started = STARTED_COMMENT;
3070 savingComment = TRUE;
3072 started = STARTED_CHATTER;
3073 savingComment = FALSE;
3080 if (looking_at(buf, &i, "* s-shouts: ") ||
3081 looking_at(buf, &i, "* c-shouts: ")) {
3082 if (appData.colorize) {
3083 if (oldi > next_out) {
3084 SendToPlayer(&buf[next_out], oldi - next_out);
3087 Colorize(ColorSShout, FALSE);
3088 curColor = ColorSShout;
3091 started = STARTED_CHATTER;
3095 if (looking_at(buf, &i, "--->")) {
3100 if (looking_at(buf, &i, "* shouts: ") ||
3101 looking_at(buf, &i, "--> ")) {
3102 if (appData.colorize) {
3103 if (oldi > next_out) {
3104 SendToPlayer(&buf[next_out], oldi - next_out);
3107 Colorize(ColorShout, FALSE);
3108 curColor = ColorShout;
3111 started = STARTED_CHATTER;
3115 if (looking_at( buf, &i, "Challenge:")) {
3116 if (appData.colorize) {
3117 if (oldi > next_out) {
3118 SendToPlayer(&buf[next_out], oldi - next_out);
3121 Colorize(ColorChallenge, FALSE);
3122 curColor = ColorChallenge;
3128 if (looking_at(buf, &i, "* offers you") ||
3129 looking_at(buf, &i, "* offers to be") ||
3130 looking_at(buf, &i, "* would like to") ||
3131 looking_at(buf, &i, "* requests to") ||
3132 looking_at(buf, &i, "Your opponent offers") ||
3133 looking_at(buf, &i, "Your opponent requests")) {
3135 if (appData.colorize) {
3136 if (oldi > next_out) {
3137 SendToPlayer(&buf[next_out], oldi - next_out);
3140 Colorize(ColorRequest, FALSE);
3141 curColor = ColorRequest;
3146 if (looking_at(buf, &i, "* (*) seeking")) {
3147 if (appData.colorize) {
3148 if (oldi > next_out) {
3149 SendToPlayer(&buf[next_out], oldi - next_out);
3152 Colorize(ColorSeek, FALSE);
3153 curColor = ColorSeek;
3158 if(i < backup) { i = backup; continue; } // [HGM] for if ZippyControl matches, but the colorie code doesn't
3160 if (looking_at(buf, &i, "\\ ")) {
3161 if (prevColor != ColorNormal) {
3162 if (oldi > next_out) {
3163 SendToPlayer(&buf[next_out], oldi - next_out);
3166 Colorize(prevColor, TRUE);
3167 curColor = prevColor;
3169 if (savingComment) {
3170 parse_pos = i - oldi;
3171 memcpy(parse, &buf[oldi], parse_pos);
3172 parse[parse_pos] = NULLCHAR;
3173 started = STARTED_COMMENT;
3174 if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3175 chattingPartner = savingComment - 3; // kludge to remember the box
3177 started = STARTED_CHATTER;
3182 if (looking_at(buf, &i, "Black Strength :") ||
3183 looking_at(buf, &i, "<<< style 10 board >>>") ||
3184 looking_at(buf, &i, "<10>") ||
3185 looking_at(buf, &i, "#@#")) {
3186 /* Wrong board style */
3188 SendToICS(ics_prefix);
3189 SendToICS("set style 12\n");
3190 SendToICS(ics_prefix);
3191 SendToICS("refresh\n");
3195 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
3197 have_sent_ICS_logon = 1;
3201 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3202 (looking_at(buf, &i, "\n<12> ") ||
3203 looking_at(buf, &i, "<12> "))) {
3205 if (oldi > next_out) {
3206 SendToPlayer(&buf[next_out], oldi - next_out);
3209 started = STARTED_BOARD;
3214 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3215 looking_at(buf, &i, "<b1> ")) {
3216 if (oldi > next_out) {
3217 SendToPlayer(&buf[next_out], oldi - next_out);
3220 started = STARTED_HOLDINGS;
3225 if (looking_at(buf, &i, "* *vs. * *--- *")) {
3227 /* Header for a move list -- first line */
3229 switch (ics_getting_history) {
3233 case BeginningOfGame:
3234 /* User typed "moves" or "oldmoves" while we
3235 were idle. Pretend we asked for these
3236 moves and soak them up so user can step
3237 through them and/or save them.
3240 gameMode = IcsObserving;
3243 ics_getting_history = H_GOT_UNREQ_HEADER;
3245 case EditGame: /*?*/
3246 case EditPosition: /*?*/
3247 /* Should above feature work in these modes too? */
3248 /* For now it doesn't */
3249 ics_getting_history = H_GOT_UNWANTED_HEADER;
3252 ics_getting_history = H_GOT_UNWANTED_HEADER;
3257 /* Is this the right one? */
3258 if (gameInfo.white && gameInfo.black &&
3259 strcmp(gameInfo.white, star_match[0]) == 0 &&
3260 strcmp(gameInfo.black, star_match[2]) == 0) {
3262 ics_getting_history = H_GOT_REQ_HEADER;
3265 case H_GOT_REQ_HEADER:
3266 case H_GOT_UNREQ_HEADER:
3267 case H_GOT_UNWANTED_HEADER:
3268 case H_GETTING_MOVES:
3269 /* Should not happen */
3270 DisplayError(_("Error gathering move list: two headers"), 0);
3271 ics_getting_history = H_FALSE;
3275 /* Save player ratings into gameInfo if needed */
3276 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3277 ics_getting_history == H_GOT_UNREQ_HEADER) &&
3278 (gameInfo.whiteRating == -1 ||
3279 gameInfo.blackRating == -1)) {
3281 gameInfo.whiteRating = string_to_rating(star_match[1]);
3282 gameInfo.blackRating = string_to_rating(star_match[3]);
3283 if (appData.debugMode)
3284 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
3285 gameInfo.whiteRating, gameInfo.blackRating);
3290 if (looking_at(buf, &i,
3291 "* * match, initial time: * minute*, increment: * second")) {
3292 /* Header for a move list -- second line */
3293 /* Initial board will follow if this is a wild game */
3294 if (gameInfo.event != NULL) free(gameInfo.event);
3295 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3296 gameInfo.event = StrSave(str);
3297 /* [HGM] we switched variant. Translate boards if needed. */
3298 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3302 if (looking_at(buf, &i, "Move ")) {
3303 /* Beginning of a move list */
3304 switch (ics_getting_history) {
3306 /* Normally should not happen */
3307 /* Maybe user hit reset while we were parsing */
3310 /* Happens if we are ignoring a move list that is not
3311 * the one we just requested. Common if the user
3312 * tries to observe two games without turning off
3315 case H_GETTING_MOVES:
3316 /* Should not happen */
3317 DisplayError(_("Error gathering move list: nested"), 0);
3318 ics_getting_history = H_FALSE;
3320 case H_GOT_REQ_HEADER:
3321 ics_getting_history = H_GETTING_MOVES;
3322 started = STARTED_MOVES;
3324 if (oldi > next_out) {
3325 SendToPlayer(&buf[next_out], oldi - next_out);
3328 case H_GOT_UNREQ_HEADER:
3329 ics_getting_history = H_GETTING_MOVES;
3330 started = STARTED_MOVES_NOHIDE;
3333 case H_GOT_UNWANTED_HEADER:
3334 ics_getting_history = H_FALSE;
3340 if (looking_at(buf, &i, "% ") ||
3341 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3342 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3343 if(ics_type == ICS_ICC && soughtPending) { // [HGM] seekgraph: on ICC sought-list has no termination line
3344 soughtPending = FALSE;
3348 if(suppressKibitz) next_out = i;
3349 savingComment = FALSE;
3353 case STARTED_MOVES_NOHIDE:
3354 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3355 parse[parse_pos + i - oldi] = NULLCHAR;
3356 ParseGameHistory(parse);
3358 if (appData.zippyPlay && first.initDone) {
3359 FeedMovesToProgram(&first, forwardMostMove);
3360 if (gameMode == IcsPlayingWhite) {
3361 if (WhiteOnMove(forwardMostMove)) {
3362 if (first.sendTime) {
3363 if (first.useColors) {
3364 SendToProgram("black\n", &first);
3366 SendTimeRemaining(&first, TRUE);
3368 if (first.useColors) {
3369 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3371 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3372 first.maybeThinking = TRUE;
3374 if (first.usePlayother) {
3375 if (first.sendTime) {
3376 SendTimeRemaining(&first, TRUE);
3378 SendToProgram("playother\n", &first);
3384 } else if (gameMode == IcsPlayingBlack) {
3385 if (!WhiteOnMove(forwardMostMove)) {
3386 if (first.sendTime) {
3387 if (first.useColors) {
3388 SendToProgram("white\n", &first);
3390 SendTimeRemaining(&first, FALSE);
3392 if (first.useColors) {
3393 SendToProgram("black\n", &first);
3395 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3396 first.maybeThinking = TRUE;
3398 if (first.usePlayother) {
3399 if (first.sendTime) {
3400 SendTimeRemaining(&first, FALSE);
3402 SendToProgram("playother\n", &first);
3411 if (gameMode == IcsObserving && ics_gamenum == -1) {
3412 /* Moves came from oldmoves or moves command
3413 while we weren't doing anything else.
3415 currentMove = forwardMostMove;
3416 ClearHighlights();/*!!could figure this out*/
3417 flipView = appData.flipView;
3418 DrawPosition(TRUE, boards[currentMove]);
3419 DisplayBothClocks();
3420 snprintf(str, MSG_SIZ, "%s vs. %s",
3421 gameInfo.white, gameInfo.black);
3425 /* Moves were history of an active game */
3426 if (gameInfo.resultDetails != NULL) {
3427 free(gameInfo.resultDetails);
3428 gameInfo.resultDetails = NULL;
3431 HistorySet(parseList, backwardMostMove,
3432 forwardMostMove, currentMove-1);
3433 DisplayMove(currentMove - 1);
3434 if (started == STARTED_MOVES) next_out = i;
3435 started = STARTED_NONE;
3436 ics_getting_history = H_FALSE;
3439 case STARTED_OBSERVE:
3440 started = STARTED_NONE;
3441 SendToICS(ics_prefix);
3442 SendToICS("refresh\n");
3448 if(bookHit) { // [HGM] book: simulate book reply
3449 static char bookMove[MSG_SIZ]; // a bit generous?
3451 programStats.nodes = programStats.depth = programStats.time =
3452 programStats.score = programStats.got_only_move = 0;
3453 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3455 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3456 strcat(bookMove, bookHit);
3457 HandleMachineMove(bookMove, &first);
3462 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3463 started == STARTED_HOLDINGS ||
3464 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3465 /* Accumulate characters in move list or board */
3466 parse[parse_pos++] = buf[i];
3469 /* Start of game messages. Mostly we detect start of game
3470 when the first board image arrives. On some versions
3471 of the ICS, though, we need to do a "refresh" after starting
3472 to observe in order to get the current board right away. */
3473 if (looking_at(buf, &i, "Adding game * to observation list")) {
3474 started = STARTED_OBSERVE;
3478 /* Handle auto-observe */
3479 if (appData.autoObserve &&
3480 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3481 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3483 /* Choose the player that was highlighted, if any. */
3484 if (star_match[0][0] == '\033' ||
3485 star_match[1][0] != '\033') {
3486 player = star_match[0];
3488 player = star_match[2];
3490 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3491 ics_prefix, StripHighlightAndTitle(player));
3494 /* Save ratings from notify string */
3495 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3496 player1Rating = string_to_rating(star_match[1]);
3497 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3498 player2Rating = string_to_rating(star_match[3]);
3500 if (appData.debugMode)
3502 "Ratings from 'Game notification:' %s %d, %s %d\n",
3503 player1Name, player1Rating,
3504 player2Name, player2Rating);
3509 /* Deal with automatic examine mode after a game,
3510 and with IcsObserving -> IcsExamining transition */
3511 if (looking_at(buf, &i, "Entering examine mode for game *") ||
3512 looking_at(buf, &i, "has made you an examiner of game *")) {
3514 int gamenum = atoi(star_match[0]);
3515 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3516 gamenum == ics_gamenum) {
3517 /* We were already playing or observing this game;
3518 no need to refetch history */
3519 gameMode = IcsExamining;
3521 pauseExamForwardMostMove = forwardMostMove;
3522 } else if (currentMove < forwardMostMove) {
3523 ForwardInner(forwardMostMove);
3526 /* I don't think this case really can happen */
3527 SendToICS(ics_prefix);
3528 SendToICS("refresh\n");
3533 /* Error messages */
3534 // if (ics_user_moved) {
3535 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3536 if (looking_at(buf, &i, "Illegal move") ||
3537 looking_at(buf, &i, "Not a legal move") ||
3538 looking_at(buf, &i, "Your king is in check") ||
3539 looking_at(buf, &i, "It isn't your turn") ||
3540 looking_at(buf, &i, "It is not your move")) {
3542 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3543 currentMove = forwardMostMove-1;
3544 DisplayMove(currentMove - 1); /* before DMError */
3545 DrawPosition(FALSE, boards[currentMove]);
3546 SwitchClocks(forwardMostMove-1); // [HGM] race
3547 DisplayBothClocks();
3549 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3555 if (looking_at(buf, &i, "still have time") ||
3556 looking_at(buf, &i, "not out of time") ||
3557 looking_at(buf, &i, "either player is out of time") ||
3558 looking_at(buf, &i, "has timeseal; checking")) {
3559 /* We must have called his flag a little too soon */
3560 whiteFlag = blackFlag = FALSE;
3564 if (looking_at(buf, &i, "added * seconds to") ||
3565 looking_at(buf, &i, "seconds were added to")) {
3566 /* Update the clocks */
3567 SendToICS(ics_prefix);
3568 SendToICS("refresh\n");
3572 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3573 ics_clock_paused = TRUE;
3578 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3579 ics_clock_paused = FALSE;
3584 /* Grab player ratings from the Creating: message.
3585 Note we have to check for the special case when
3586 the ICS inserts things like [white] or [black]. */
3587 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3588 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3590 0 player 1 name (not necessarily white)
3592 2 empty, white, or black (IGNORED)
3593 3 player 2 name (not necessarily black)
3596 The names/ratings are sorted out when the game
3597 actually starts (below).
3599 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
3600 player1Rating = string_to_rating(star_match[1]);
3601 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
3602 player2Rating = string_to_rating(star_match[4]);
3604 if (appData.debugMode)
3606 "Ratings from 'Creating:' %s %d, %s %d\n",
3607 player1Name, player1Rating,
3608 player2Name, player2Rating);
3613 /* Improved generic start/end-of-game messages */
3614 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3615 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3616 /* If tkind == 0: */
3617 /* star_match[0] is the game number */
3618 /* [1] is the white player's name */
3619 /* [2] is the black player's name */
3620 /* For end-of-game: */
3621 /* [3] is the reason for the game end */
3622 /* [4] is a PGN end game-token, preceded by " " */
3623 /* For start-of-game: */
3624 /* [3] begins with "Creating" or "Continuing" */
3625 /* [4] is " *" or empty (don't care). */
3626 int gamenum = atoi(star_match[0]);
3627 char *whitename, *blackname, *why, *endtoken;
3628 ChessMove endtype = EndOfFile;
3631 whitename = star_match[1];
3632 blackname = star_match[2];
3633 why = star_match[3];
3634 endtoken = star_match[4];
3636 whitename = star_match[1];
3637 blackname = star_match[3];
3638 why = star_match[5];
3639 endtoken = star_match[6];
3642 /* Game start messages */
3643 if (strncmp(why, "Creating ", 9) == 0 ||
3644 strncmp(why, "Continuing ", 11) == 0) {
3645 gs_gamenum = gamenum;
3646 safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
3647 VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
3649 if (appData.zippyPlay) {
3650 ZippyGameStart(whitename, blackname);
3653 partnerBoardValid = FALSE; // [HGM] bughouse
3657 /* Game end messages */
3658 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3659 ics_gamenum != gamenum) {
3662 while (endtoken[0] == ' ') endtoken++;
3663 switch (endtoken[0]) {
3666 endtype = GameUnfinished;
3669 endtype = BlackWins;
3672 if (endtoken[1] == '/')
3673 endtype = GameIsDrawn;
3675 endtype = WhiteWins;
3678 GameEnds(endtype, why, GE_ICS);
3680 if (appData.zippyPlay && first.initDone) {
3681 ZippyGameEnd(endtype, why);
3682 if (first.pr == NULL) {
3683 /* Start the next process early so that we'll
3684 be ready for the next challenge */
3685 StartChessProgram(&first);
3687 /* Send "new" early, in case this command takes
3688 a long time to finish, so that we'll be ready
3689 for the next challenge. */
3690 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3694 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
3698 if (looking_at(buf, &i, "Removing game * from observation") ||
3699 looking_at(buf, &i, "no longer observing game *") ||
3700 looking_at(buf, &i, "Game * (*) has no examiners")) {
3701 if (gameMode == IcsObserving &&
3702 atoi(star_match[0]) == ics_gamenum)
3704 /* icsEngineAnalyze */
3705 if (appData.icsEngineAnalyze) {
3712 ics_user_moved = FALSE;
3717 if (looking_at(buf, &i, "no longer examining game *")) {
3718 if (gameMode == IcsExamining &&
3719 atoi(star_match[0]) == ics_gamenum)
3723 ics_user_moved = FALSE;
3728 /* Advance leftover_start past any newlines we find,
3729 so only partial lines can get reparsed */
3730 if (looking_at(buf, &i, "\n")) {
3731 prevColor = curColor;
3732 if (curColor != ColorNormal) {
3733 if (oldi > next_out) {
3734 SendToPlayer(&buf[next_out], oldi - next_out);
3737 Colorize(ColorNormal, FALSE);
3738 curColor = ColorNormal;
3740 if (started == STARTED_BOARD) {
3741 started = STARTED_NONE;
3742 parse[parse_pos] = NULLCHAR;
3743 ParseBoard12(parse);
3746 /* Send premove here */
3747 if (appData.premove) {
3749 if (currentMove == 0 &&
3750 gameMode == IcsPlayingWhite &&
3751 appData.premoveWhite) {
3752 snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
3753 if (appData.debugMode)
3754 fprintf(debugFP, "Sending premove:\n");
3756 } else if (currentMove == 1 &&
3757 gameMode == IcsPlayingBlack &&
3758 appData.premoveBlack) {
3759 snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
3760 if (appData.debugMode)
3761 fprintf(debugFP, "Sending premove:\n");
3763 } else if (gotPremove) {
3765 ClearPremoveHighlights();
3766 if (appData.debugMode)
3767 fprintf(debugFP, "Sending premove:\n");
3768 UserMoveEvent(premoveFromX, premoveFromY,
3769 premoveToX, premoveToY,
3774 /* Usually suppress following prompt */
3775 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
3776 while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
3777 if (looking_at(buf, &i, "*% ")) {
3778 savingComment = FALSE;
3783 } else if (started == STARTED_HOLDINGS) {
3785 char new_piece[MSG_SIZ];
3786 started = STARTED_NONE;
3787 parse[parse_pos] = NULLCHAR;
3788 if (appData.debugMode)
3789 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
3790 parse, currentMove);
3791 if (sscanf(parse, " game %d", &gamenum) == 1) {
3792 if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
3793 if (gameInfo.variant == VariantNormal) {
3794 /* [HGM] We seem to switch variant during a game!
3795 * Presumably no holdings were displayed, so we have
3796 * to move the position two files to the right to
3797 * create room for them!
3799 VariantClass newVariant;
3800 switch(gameInfo.boardWidth) { // base guess on board width
3801 case 9: newVariant = VariantShogi; break;
3802 case 10: newVariant = VariantGreat; break;
3803 default: newVariant = VariantCrazyhouse; break;
3805 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
3806 /* Get a move list just to see the header, which
3807 will tell us whether this is really bug or zh */
3808 if (ics_getting_history == H_FALSE) {
3809 ics_getting_history = H_REQUESTED;
3810 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
3814 new_piece[0] = NULLCHAR;
3815 sscanf(parse, "game %d white [%s black [%s <- %s",
3816 &gamenum, white_holding, black_holding,
3818 white_holding[strlen(white_holding)-1] = NULLCHAR;
3819 black_holding[strlen(black_holding)-1] = NULLCHAR;
3820 /* [HGM] copy holdings to board holdings area */
3821 CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
3822 CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
3823 boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
3825 if (appData.zippyPlay && first.initDone) {
3826 ZippyHoldings(white_holding, black_holding,
3830 if (tinyLayout || smallLayout) {
3831 char wh[16], bh[16];
3832 PackHolding(wh, white_holding);
3833 PackHolding(bh, black_holding);
3834 snprintf(str, MSG_SIZ,"[%s-%s] %s-%s", wh, bh,
3835 gameInfo.white, gameInfo.black);
3837 snprintf(str, MSG_SIZ, "%s [%s] vs. %s [%s]",
3838 gameInfo.white, white_holding,
3839 gameInfo.black, black_holding);
3841 if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
3842 DrawPosition(FALSE, boards[currentMove]);
3844 } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
3845 sscanf(parse, "game %d white [%s black [%s <- %s",
3846 &gamenum, white_holding, black_holding,
3848 white_holding[strlen(white_holding)-1] = NULLCHAR;
3849 black_holding[strlen(black_holding)-1] = NULLCHAR;
3850 /* [HGM] copy holdings to partner-board holdings area */
3851 CopyHoldings(partnerBoard, white_holding, WhitePawn);
3852 CopyHoldings(partnerBoard, black_holding, BlackPawn);
3853 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
3854 if(partnerUp) DrawPosition(FALSE, partnerBoard);
3855 if(twoBoards) { partnerUp = 0; flipView = !flipView; }
3858 /* Suppress following prompt */
3859 if (looking_at(buf, &i, "*% ")) {
3860 if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
3861 savingComment = FALSE;
3869 i++; /* skip unparsed character and loop back */
3872 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
3873 // started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
3874 // SendToPlayer(&buf[next_out], i - next_out);
3875 started != STARTED_HOLDINGS && leftover_start > next_out) {
3876 SendToPlayer(&buf[next_out], leftover_start - next_out);
3880 leftover_len = buf_len - leftover_start;
3881 /* if buffer ends with something we couldn't parse,
3882 reparse it after appending the next read */
3884 } else if (count == 0) {
3885 RemoveInputSource(isr);
3886 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
3888 DisplayFatalError(_("Error reading from ICS"), error, 1);
3893 /* Board style 12 looks like this:
3895 <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
3897 * The "<12> " is stripped before it gets to this routine. The two
3898 * trailing 0's (flip state and clock ticking) are later addition, and
3899 * some chess servers may not have them, or may have only the first.
3900 * Additional trailing fields may be added in the future.
3903 #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"
3905 #define RELATION_OBSERVING_PLAYED 0
3906 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
3907 #define RELATION_PLAYING_MYMOVE 1
3908 #define RELATION_PLAYING_NOTMYMOVE -1
3909 #define RELATION_EXAMINING 2
3910 #define RELATION_ISOLATED_BOARD -3
3911 #define RELATION_STARTING_POSITION -4 /* FICS only */
3914 ParseBoard12(string)
3917 GameMode newGameMode;
3918 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0, i;
3919 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time, takeback;
3920 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
3921 char to_play, board_chars[200];
3922 char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
3923 char black[32], white[32];
3925 int prevMove = currentMove;
3928 int fromX, fromY, toX, toY;
3930 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
3931 char *bookHit = NULL; // [HGM] book
3932 Boolean weird = FALSE, reqFlag = FALSE;
3934 fromX = fromY = toX = toY = -1;
3938 if (appData.debugMode)
3939 fprintf(debugFP, _("Parsing board: %s\n"), string);
3941 move_str[0] = NULLCHAR;
3942 elapsed_time[0] = NULLCHAR;
3943 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
3945 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
3946 if(string[i] == ' ') { ranks++; files = 0; }
3948 if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
3951 for(j = 0; j <i; j++) board_chars[j] = string[j];
3952 board_chars[i] = '\0';
3955 n = sscanf(string, PATTERN, &to_play, &double_push,
3956 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
3957 &gamenum, white, black, &relation, &basetime, &increment,
3958 &white_stren, &black_stren, &white_time, &black_time,
3959 &moveNum, str, elapsed_time, move_str, &ics_flip,
3963 snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
3964 DisplayError(str, 0);
3968 /* Convert the move number to internal form */
3969 moveNum = (moveNum - 1) * 2;
3970 if (to_play == 'B') moveNum++;
3971 if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
3972 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
3978 case RELATION_OBSERVING_PLAYED:
3979 case RELATION_OBSERVING_STATIC:
3980 if (gamenum == -1) {
3981 /* Old ICC buglet */
3982 relation = RELATION_OBSERVING_STATIC;
3984 newGameMode = IcsObserving;
3986 case RELATION_PLAYING_MYMOVE:
3987 case RELATION_PLAYING_NOTMYMOVE:
3989 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
3990 IcsPlayingWhite : IcsPlayingBlack;
3992 case RELATION_EXAMINING:
3993 newGameMode = IcsExamining;
3995 case RELATION_ISOLATED_BOARD:
3997 /* Just display this board. If user was doing something else,
3998 we will forget about it until the next board comes. */
3999 newGameMode = IcsIdle;
4001 case RELATION_STARTING_POSITION:
4002 newGameMode = gameMode;
4006 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
4007 && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
4008 // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
4010 for (k = 0; k < ranks; k++) {
4011 for (j = 0; j < files; j++)
4012 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4013 if(gameInfo.holdingsWidth > 1) {
4014 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4015 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4018 CopyBoard(partnerBoard, board);
4019 if(toSqr = strchr(str, '/')) { // extract highlights from long move
4020 partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
4021 partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
4022 } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
4023 if(toSqr = strchr(str, '-')) {
4024 partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
4025 partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
4026 } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
4027 if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
4028 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
4029 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4030 if(twoBoards) { partnerUp = 0; flipView = !flipView; } // [HGM] dual
4031 snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time/60000, (white_time%60000)/1000,
4032 (black_time/60000), (black_time%60000)/1000, white_stren, black_stren, to_play);
4033 DisplayMessage(partnerStatus, "");
4034 partnerBoardValid = TRUE;
4038 /* Modify behavior for initial board display on move listing
4041 switch (ics_getting_history) {
4045 case H_GOT_REQ_HEADER:
4046 case H_GOT_UNREQ_HEADER:
4047 /* This is the initial position of the current game */
4048 gamenum = ics_gamenum;
4049 moveNum = 0; /* old ICS bug workaround */
4050 if (to_play == 'B') {
4051 startedFromSetupPosition = TRUE;
4052 blackPlaysFirst = TRUE;
4054 if (forwardMostMove == 0) forwardMostMove = 1;
4055 if (backwardMostMove == 0) backwardMostMove = 1;
4056 if (currentMove == 0) currentMove = 1;
4058 newGameMode = gameMode;
4059 relation = RELATION_STARTING_POSITION; /* ICC needs this */
4061 case H_GOT_UNWANTED_HEADER:
4062 /* This is an initial board that we don't want */
4064 case H_GETTING_MOVES:
4065 /* Should not happen */
4066 DisplayError(_("Error gathering move list: extra board"), 0);
4067 ics_getting_history = H_FALSE;
4071 if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4072 weird && (int)gameInfo.variant < (int)VariantShogi) {
4073 /* [HGM] We seem to have switched variant unexpectedly
4074 * Try to guess new variant from board size
4076 VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4077 if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4078 if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4079 if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4080 if(ranks == 9 && files == 9) newVariant = VariantShogi; else
4081 if(!weird) newVariant = VariantNormal;
4082 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4083 /* Get a move list just to see the header, which
4084 will tell us whether this is really bug or zh */
4085 if (ics_getting_history == H_FALSE) {
4086 ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4087 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4092 /* Take action if this is the first board of a new game, or of a
4093 different game than is currently being displayed. */
4094 if (gamenum != ics_gamenum || newGameMode != gameMode ||
4095 relation == RELATION_ISOLATED_BOARD) {
4097 /* Forget the old game and get the history (if any) of the new one */
4098 if (gameMode != BeginningOfGame) {
4102 if (appData.autoRaiseBoard) BoardToTop();
4104 if (gamenum == -1) {
4105 newGameMode = IcsIdle;
4106 } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4107 appData.getMoveList && !reqFlag) {
4108 /* Need to get game history */
4109 ics_getting_history = H_REQUESTED;
4110 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4114 /* Initially flip the board to have black on the bottom if playing
4115 black or if the ICS flip flag is set, but let the user change
4116 it with the Flip View button. */
4117 flipView = appData.autoFlipView ?
4118 (newGameMode == IcsPlayingBlack) || ics_flip :
4121 /* Done with values from previous mode; copy in new ones */
4122 gameMode = newGameMode;
4124 ics_gamenum = gamenum;
4125 if (gamenum == gs_gamenum) {
4126 int klen = strlen(gs_kind);
4127 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4128 snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4129 gameInfo.event = StrSave(str);
4131 gameInfo.event = StrSave("ICS game");
4133 gameInfo.site = StrSave(appData.icsHost);
4134 gameInfo.date = PGNDate();
4135 gameInfo.round = StrSave("-");
4136 gameInfo.white = StrSave(white);
4137 gameInfo.black = StrSave(black);
4138 timeControl = basetime * 60 * 1000;
4140 timeIncrement = increment * 1000;
4141 movesPerSession = 0;
4142 gameInfo.timeControl = TimeControlTagValue();
4143 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4144 if (appData.debugMode) {
4145 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4146 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4147 setbuf(debugFP, NULL);
4150 gameInfo.outOfBook = NULL;
4152 /* Do we have the ratings? */
4153 if (strcmp(player1Name, white) == 0 &&
4154 strcmp(player2Name, black) == 0) {
4155 if (appData.debugMode)
4156 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4157 player1Rating, player2Rating);
4158 gameInfo.whiteRating = player1Rating;
4159 gameInfo.blackRating = player2Rating;
4160 } else if (strcmp(player2Name, white) == 0 &&
4161 strcmp(player1Name, black) == 0) {
4162 if (appData.debugMode)
4163 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4164 player2Rating, player1Rating);
4165 gameInfo.whiteRating = player2Rating;
4166 gameInfo.blackRating = player1Rating;
4168 player1Name[0] = player2Name[0] = NULLCHAR;
4170 /* Silence shouts if requested */
4171 if (appData.quietPlay &&
4172 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4173 SendToICS(ics_prefix);
4174 SendToICS("set shout 0\n");
4178 /* Deal with midgame name changes */
4180 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4181 if (gameInfo.white) free(gameInfo.white);
4182 gameInfo.white = StrSave(white);
4184 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4185 if (gameInfo.black) free(gameInfo.black);
4186 gameInfo.black = StrSave(black);
4190 /* Throw away game result if anything actually changes in examine mode */
4191 if (gameMode == IcsExamining && !newGame) {
4192 gameInfo.result = GameUnfinished;
4193 if (gameInfo.resultDetails != NULL) {
4194 free(gameInfo.resultDetails);
4195 gameInfo.resultDetails = NULL;
4199 /* In pausing && IcsExamining mode, we ignore boards coming
4200 in if they are in a different variation than we are. */
4201 if (pauseExamInvalid) return;
4202 if (pausing && gameMode == IcsExamining) {
4203 if (moveNum <= pauseExamForwardMostMove) {
4204 pauseExamInvalid = TRUE;
4205 forwardMostMove = pauseExamForwardMostMove;
4210 if (appData.debugMode) {
4211 fprintf(debugFP, "load %dx%d board\n", files, ranks);
4213 /* Parse the board */
4214 for (k = 0; k < ranks; k++) {
4215 for (j = 0; j < files; j++)
4216 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4217 if(gameInfo.holdingsWidth > 1) {
4218 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4219 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4222 CopyBoard(boards[moveNum], board);
4223 boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4225 startedFromSetupPosition =
4226 !CompareBoards(board, initialPosition);
4227 if(startedFromSetupPosition)
4228 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4231 /* [HGM] Set castling rights. Take the outermost Rooks,
4232 to make it also work for FRC opening positions. Note that board12
4233 is really defective for later FRC positions, as it has no way to
4234 indicate which Rook can castle if they are on the same side of King.
4235 For the initial position we grant rights to the outermost Rooks,
4236 and remember thos rights, and we then copy them on positions
4237 later in an FRC game. This means WB might not recognize castlings with
4238 Rooks that have moved back to their original position as illegal,
4239 but in ICS mode that is not its job anyway.
4241 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4242 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4244 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4245 if(board[0][i] == WhiteRook) j = i;
4246 initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4247 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4248 if(board[0][i] == WhiteRook) j = i;
4249 initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4250 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4251 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4252 initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4253 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4254 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4255 initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4257 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4258 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4259 if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4260 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4261 if(board[BOARD_HEIGHT-1][k] == bKing)
4262 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4263 if(gameInfo.variant == VariantTwoKings) {
4264 // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4265 if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4266 if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4269 r = boards[moveNum][CASTLING][0] = initialRights[0];
4270 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4271 r = boards[moveNum][CASTLING][1] = initialRights[1];
4272 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4273 r = boards[moveNum][CASTLING][3] = initialRights[3];
4274 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4275 r = boards[moveNum][CASTLING][4] = initialRights[4];
4276 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4277 /* wildcastle kludge: always assume King has rights */
4278 r = boards[moveNum][CASTLING][2] = initialRights[2];
4279 r = boards[moveNum][CASTLING][5] = initialRights[5];
4281 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4282 boards[moveNum][EP_STATUS] = double_push == -1 ? EP_NONE : double_push + BOARD_LEFT;
4285 if (ics_getting_history == H_GOT_REQ_HEADER ||
4286 ics_getting_history == H_GOT_UNREQ_HEADER) {
4287 /* This was an initial position from a move list, not
4288 the current position */
4292 /* Update currentMove and known move number limits */
4293 newMove = newGame || moveNum > forwardMostMove;
4296 forwardMostMove = backwardMostMove = currentMove = moveNum;
4297 if (gameMode == IcsExamining && moveNum == 0) {
4298 /* Workaround for ICS limitation: we are not told the wild
4299 type when starting to examine a game. But if we ask for
4300 the move list, the move list header will tell us */
4301 ics_getting_history = H_REQUESTED;
4302 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4305 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4306 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4308 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4309 /* [HGM] applied this also to an engine that is silently watching */
4310 if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4311 (gameMode == IcsObserving || gameMode == IcsExamining) &&
4312 gameInfo.variant == currentlyInitializedVariant) {
4313 takeback = forwardMostMove - moveNum;
4314 for (i = 0; i < takeback; i++) {
4315 if (appData.debugMode) fprintf(debugFP, "take back move\n");
4316 SendToProgram("undo\n", &first);
4321 forwardMostMove = moveNum;
4322 if (!pausing || currentMove > forwardMostMove)
4323 currentMove = forwardMostMove;
4325 /* New part of history that is not contiguous with old part */
4326 if (pausing && gameMode == IcsExamining) {
4327 pauseExamInvalid = TRUE;
4328 forwardMostMove = pauseExamForwardMostMove;
4331 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4333 if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4334 // [HGM] when we will receive the move list we now request, it will be
4335 // fed to the engine from the first move on. So if the engine is not
4336 // in the initial position now, bring it there.
4337 InitChessProgram(&first, 0);
4340 ics_getting_history = H_REQUESTED;
4341 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4344 forwardMostMove = backwardMostMove = currentMove = moveNum;
4347 /* Update the clocks */
4348 if (strchr(elapsed_time, '.')) {
4350 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4351 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4353 /* Time is in seconds */
4354 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4355 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4360 if (appData.zippyPlay && newGame &&
4361 gameMode != IcsObserving && gameMode != IcsIdle &&
4362 gameMode != IcsExamining)
4363 ZippyFirstBoard(moveNum, basetime, increment);
4366 /* Put the move on the move list, first converting
4367 to canonical algebraic form. */
4369 if (appData.debugMode) {
4370 if (appData.debugMode) { int f = forwardMostMove;
4371 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4372 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4373 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4375 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4376 fprintf(debugFP, "moveNum = %d\n", moveNum);
4377 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4378 setbuf(debugFP, NULL);
4380 if (moveNum <= backwardMostMove) {
4381 /* We don't know what the board looked like before
4383 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4384 strcat(parseList[moveNum - 1], " ");
4385 strcat(parseList[moveNum - 1], elapsed_time);
4386 moveList[moveNum - 1][0] = NULLCHAR;
4387 } else if (strcmp(move_str, "none") == 0) {
4388 // [HGM] long SAN: swapped order; test for 'none' before parsing move
4389 /* Again, we don't know what the board looked like;
4390 this is really the start of the game. */
4391 parseList[moveNum - 1][0] = NULLCHAR;
4392 moveList[moveNum - 1][0] = NULLCHAR;
4393 backwardMostMove = moveNum;
4394 startedFromSetupPosition = TRUE;
4395 fromX = fromY = toX = toY = -1;
4397 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4398 // So we parse the long-algebraic move string in stead of the SAN move
4399 int valid; char buf[MSG_SIZ], *prom;
4401 if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4402 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4403 // str looks something like "Q/a1-a2"; kill the slash
4405 snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4406 else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4407 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4408 strcat(buf, prom); // long move lacks promo specification!
4409 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4410 if(appData.debugMode)
4411 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4412 safeStrCpy(move_str, buf, MSG_SIZ);
4414 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4415 &fromX, &fromY, &toX, &toY, &promoChar)
4416 || ParseOneMove(buf, moveNum - 1, &moveType,
4417 &fromX, &fromY, &toX, &toY, &promoChar);
4418 // end of long SAN patch
4420 (void) CoordsToAlgebraic(boards[moveNum - 1],
4421 PosFlags(moveNum - 1),
4422 fromY, fromX, toY, toX, promoChar,
4423 parseList[moveNum-1]);
4424 switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4430 if(gameInfo.variant != VariantShogi)
4431 strcat(parseList[moveNum - 1], "+");
4434 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4435 strcat(parseList[moveNum - 1], "#");
4438 strcat(parseList[moveNum - 1], " ");
4439 strcat(parseList[moveNum - 1], elapsed_time);
4440 /* currentMoveString is set as a side-effect of ParseOneMove */
4441 if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4442 safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4443 strcat(moveList[moveNum - 1], "\n");
4445 if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper
4446 && gameInfo.variant != VariantGreat) // inherit info that ICS does not give from previous board
4447 for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4448 ChessSquare old, new = boards[moveNum][k][j];
4449 if(fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4450 old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4451 if(old == new) continue;
4452 if(old == PROMOTED new) boards[moveNum][k][j] = old; // prevent promoted pieces to revert to primordial ones
4453 else if(new == WhiteWazir || new == BlackWazir) {
4454 if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4455 boards[moveNum][k][j] = PROMOTED old; // choose correct type of Gold in promotion
4456 else boards[moveNum][k][j] = old; // preserve type of Gold
4457 } else if((old == WhitePawn || old == BlackPawn) && new != EmptySquare) // Pawn promotions (but not e.p.capture!)
4458 boards[moveNum][k][j] = PROMOTED new; // use non-primordial representation of chosen piece
4461 /* Move from ICS was illegal!? Punt. */
4462 if (appData.debugMode) {
4463 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4464 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4466 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4467 strcat(parseList[moveNum - 1], " ");
4468 strcat(parseList[moveNum - 1], elapsed_time);
4469 moveList[moveNum - 1][0] = NULLCHAR;
4470 fromX = fromY = toX = toY = -1;
4473 if (appData.debugMode) {
4474 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4475 setbuf(debugFP, NULL);
4479 /* Send move to chess program (BEFORE animating it). */
4480 if (appData.zippyPlay && !newGame && newMove &&
4481 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4483 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4484 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4485 if (moveList[moveNum - 1][0] == NULLCHAR) {
4486 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4488 DisplayError(str, 0);
4490 if (first.sendTime) {
4491 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4493 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4494 if (firstMove && !bookHit) {
4496 if (first.useColors) {
4497 SendToProgram(gameMode == IcsPlayingWhite ?
4499 "black\ngo\n", &first);
4501 SendToProgram("go\n", &first);
4503 first.maybeThinking = TRUE;
4506 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4507 if (moveList[moveNum - 1][0] == NULLCHAR) {
4508 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4509 DisplayError(str, 0);
4511 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4512 SendMoveToProgram(moveNum - 1, &first);
4519 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
4520 /* If move comes from a remote source, animate it. If it
4521 isn't remote, it will have already been animated. */
4522 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
4523 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
4525 if (!pausing && appData.highlightLastMove) {
4526 SetHighlights(fromX, fromY, toX, toY);
4530 /* Start the clocks */
4531 whiteFlag = blackFlag = FALSE;
4532 appData.clockMode = !(basetime == 0 && increment == 0);
4534 ics_clock_paused = TRUE;
4536 } else if (ticking == 1) {
4537 ics_clock_paused = FALSE;
4539 if (gameMode == IcsIdle ||
4540 relation == RELATION_OBSERVING_STATIC ||
4541 relation == RELATION_EXAMINING ||
4543 DisplayBothClocks();
4547 /* Display opponents and material strengths */
4548 if (gameInfo.variant != VariantBughouse &&
4549 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
4550 if (tinyLayout || smallLayout) {
4551 if(gameInfo.variant == VariantNormal)
4552 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
4553 gameInfo.white, white_stren, gameInfo.black, black_stren,
4554 basetime, increment);
4556 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
4557 gameInfo.white, white_stren, gameInfo.black, black_stren,
4558 basetime, increment, (int) gameInfo.variant);
4560 if(gameInfo.variant == VariantNormal)
4561 snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d}",
4562 gameInfo.white, white_stren, gameInfo.black, black_stren,
4563 basetime, increment);
4565 snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d %s}",
4566 gameInfo.white, white_stren, gameInfo.black, black_stren,
4567 basetime, increment, VariantName(gameInfo.variant));
4570 if (appData.debugMode) {
4571 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
4576 /* Display the board */
4577 if (!pausing && !appData.noGUI) {
4579 if (appData.premove)
4581 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
4582 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
4583 ClearPremoveHighlights();
4585 j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
4586 if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
4587 DrawPosition(j, boards[currentMove]);
4589 DisplayMove(moveNum - 1);
4590 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
4591 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
4592 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
4593 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
4597 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
4599 if(bookHit) { // [HGM] book: simulate book reply
4600 static char bookMove[MSG_SIZ]; // a bit generous?
4602 programStats.nodes = programStats.depth = programStats.time =
4603 programStats.score = programStats.got_only_move = 0;
4604 sprintf(programStats.movelist, "%s (xbook)", bookHit);
4606 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
4607 strcat(bookMove, bookHit);
4608 HandleMachineMove(bookMove, &first);
4617 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
4618 ics_getting_history = H_REQUESTED;
4619 snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
4625 AnalysisPeriodicEvent(force)
4628 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
4629 && !force) || !appData.periodicUpdates)
4632 /* Send . command to Crafty to collect stats */
4633 SendToProgram(".\n", &first);
4635 /* Don't send another until we get a response (this makes
4636 us stop sending to old Crafty's which don't understand
4637 the "." command (sending illegal cmds resets node count & time,
4638 which looks bad)) */
4639 programStats.ok_to_send = 0;
4642 void ics_update_width(new_width)
4645 ics_printf("set width %d\n", new_width);
4649 SendMoveToProgram(moveNum, cps)
4651 ChessProgramState *cps;
4655 if (cps->useUsermove) {
4656 SendToProgram("usermove ", cps);
4660 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
4661 int len = space - parseList[moveNum];
4662 memcpy(buf, parseList[moveNum], len);
4664 buf[len] = NULLCHAR;
4666 snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
4668 SendToProgram(buf, cps);
4670 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
4671 AlphaRank(moveList[moveNum], 4);
4672 SendToProgram(moveList[moveNum], cps);
4673 AlphaRank(moveList[moveNum], 4); // and back
4675 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
4676 * the engine. It would be nice to have a better way to identify castle
4678 if((gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom)
4679 && cps->useOOCastle) {
4680 int fromX = moveList[moveNum][0] - AAA;
4681 int fromY = moveList[moveNum][1] - ONE;
4682 int toX = moveList[moveNum][2] - AAA;
4683 int toY = moveList[moveNum][3] - ONE;
4684 if((boards[moveNum][fromY][fromX] == WhiteKing
4685 && boards[moveNum][toY][toX] == WhiteRook)
4686 || (boards[moveNum][fromY][fromX] == BlackKing
4687 && boards[moveNum][toY][toX] == BlackRook)) {
4688 if(toX > fromX) SendToProgram("O-O\n", cps);
4689 else SendToProgram("O-O-O\n", cps);
4691 else SendToProgram(moveList[moveNum], cps);
4693 else SendToProgram(moveList[moveNum], cps);
4694 /* End of additions by Tord */
4697 /* [HGM] setting up the opening has brought engine in force mode! */
4698 /* Send 'go' if we are in a mode where machine should play. */
4699 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
4700 (gameMode == TwoMachinesPlay ||
4702 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
4704 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
4705 SendToProgram("go\n", cps);
4706 if (appData.debugMode) {
4707 fprintf(debugFP, "(extra)\n");
4710 setboardSpoiledMachineBlack = 0;
4714 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar)
4716 int fromX, fromY, toX, toY;
4719 char user_move[MSG_SIZ];
4723 snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
4724 (int)moveType, fromX, fromY, toX, toY);
4725 DisplayError(user_move + strlen("say "), 0);
4727 case WhiteKingSideCastle:
4728 case BlackKingSideCastle:
4729 case WhiteQueenSideCastleWild:
4730 case BlackQueenSideCastleWild:
4732 case WhiteHSideCastleFR:
4733 case BlackHSideCastleFR:
4735 snprintf(user_move, MSG_SIZ, "o-o\n");
4737 case WhiteQueenSideCastle:
4738 case BlackQueenSideCastle:
4739 case WhiteKingSideCastleWild:
4740 case BlackKingSideCastleWild:
4742 case WhiteASideCastleFR:
4743 case BlackASideCastleFR:
4745 snprintf(user_move, MSG_SIZ, "o-o-o\n");
4747 case WhiteNonPromotion:
4748 case BlackNonPromotion:
4749 sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4751 case WhitePromotion:
4752 case BlackPromotion:
4753 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
4754 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
4755 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4756 PieceToChar(WhiteFerz));
4757 else if(gameInfo.variant == VariantGreat)
4758 snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
4759 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4760 PieceToChar(WhiteMan));
4762 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
4763 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4769 snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
4770 ToUpper(PieceToChar((ChessSquare) fromX)),
4771 AAA + toX, ONE + toY);
4773 case IllegalMove: /* could be a variant we don't quite understand */
4774 if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
4776 case WhiteCapturesEnPassant:
4777 case BlackCapturesEnPassant:
4778 snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
4779 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4782 SendToICS(user_move);
4783 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
4784 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
4789 { // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
4790 int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
4791 static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
4792 if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
4793 DisplayError("You cannot do this while you are playing or observing", 0);
4796 if(gameMode != IcsExamining) { // is this ever not the case?
4797 char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
4799 if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
4800 snprintf(command,MSG_SIZ, "match %s", ics_handle);
4801 } else { // on FICS we must first go to general examine mode
4802 safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
4804 if(gameInfo.variant != VariantNormal) {
4805 // try figure out wild number, as xboard names are not always valid on ICS
4806 for(i=1; i<=36; i++) {
4807 snprintf(buf, MSG_SIZ, "wild/%d", i);
4808 if(StringToVariant(buf) == gameInfo.variant) break;
4810 if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
4811 else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
4812 else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
4813 } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
4814 SendToICS(ics_prefix);
4816 if(startedFromSetupPosition || backwardMostMove != 0) {
4817 fen = PositionToFEN(backwardMostMove, NULL);
4818 if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
4819 snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
4821 } else { // FICS: everything has to set by separate bsetup commands
4822 p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
4823 snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
4825 if(!WhiteOnMove(backwardMostMove)) {
4826 SendToICS("bsetup tomove black\n");
4828 i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
4829 snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
4831 i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
4832 snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
4834 i = boards[backwardMostMove][EP_STATUS];
4835 if(i >= 0) { // set e.p.
4836 snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
4842 if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
4843 SendToICS("bsetup done\n"); // switch to normal examining.
4845 for(i = backwardMostMove; i<last; i++) {
4847 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
4850 SendToICS(ics_prefix);
4851 SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
4855 CoordsToComputerAlgebraic(rf, ff, rt, ft, promoChar, move)
4860 if (rf == DROP_RANK) {
4861 sprintf(move, "%c@%c%c\n",
4862 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
4864 if (promoChar == 'x' || promoChar == NULLCHAR) {
4865 sprintf(move, "%c%c%c%c\n",
4866 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
4868 sprintf(move, "%c%c%c%c%c\n",
4869 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
4875 ProcessICSInitScript(f)
4880 while (fgets(buf, MSG_SIZ, f)) {
4881 SendToICSDelayed(buf,(long)appData.msLoginDelay);
4888 static int lastX, lastY, selectFlag, dragging;
4893 ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
4894 if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
4895 if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
4896 if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
4897 if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
4898 if(fromY != BOARD_HEIGHT-2 && fromY != 1) pawn = EmptySquare;
4901 if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
4902 else if((int)promoSweep == -1) promoSweep = WhiteKing;
4903 else if(promoSweep == BlackPawn && step < 0) promoSweep = WhitePawn;
4904 else if(promoSweep == WhiteKing && step > 0) promoSweep = BlackKing;
4906 } while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' || promoSweep == pawn ||
4907 appData.testLegality && (promoSweep == king ||
4908 gameInfo.variant == VariantShogi && promoSweep != PROMOTED last && last != PROMOTED promoSweep && last != promoSweep));
4909 ChangeDragPiece(promoSweep);
4912 int PromoScroll(int x, int y)
4916 if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
4917 if(abs(x - lastX) < 15 && abs(y - lastY) < 15) return FALSE;
4918 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
4919 if(!step) return FALSE;
4920 lastX = x; lastY = y;
4921 if((promoSweep < BlackPawn) == flipView) step = -step;
4922 if(step > 0) selectFlag = 1;
4923 if(!selectFlag) Sweep(step);
4930 ChessSquare piece = boards[currentMove][toY][toX];
4933 if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
4934 if((int)pieceSweep == -1) pieceSweep = BlackKing;
4935 if(!step) step = -1;
4936 } while(PieceToChar(pieceSweep) == '.');
4937 boards[currentMove][toY][toX] = pieceSweep;
4938 DrawPosition(FALSE, boards[currentMove]);
4939 boards[currentMove][toY][toX] = piece;
4941 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
4943 AlphaRank(char *move, int n)
4945 // char *p = move, c; int x, y;
4947 if (appData.debugMode) {
4948 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
4952 move[2]>='0' && move[2]<='9' &&
4953 move[3]>='a' && move[3]<='x' ) {
4955 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4956 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4958 if(move[0]>='0' && move[0]<='9' &&
4959 move[1]>='a' && move[1]<='x' &&
4960 move[2]>='0' && move[2]<='9' &&
4961 move[3]>='a' && move[3]<='x' ) {
4962 /* input move, Shogi -> normal */
4963 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
4964 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
4965 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4966 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4969 move[3]>='0' && move[3]<='9' &&
4970 move[2]>='a' && move[2]<='x' ) {
4972 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4973 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4976 move[0]>='a' && move[0]<='x' &&
4977 move[3]>='0' && move[3]<='9' &&
4978 move[2]>='a' && move[2]<='x' ) {
4979 /* output move, normal -> Shogi */
4980 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
4981 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
4982 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4983 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4984 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
4986 if (appData.debugMode) {
4987 fprintf(debugFP, " out = '%s'\n", move);
4991 char yy_textstr[8000];
4993 /* Parser for moves from gnuchess, ICS, or user typein box */
4995 ParseOneMove(move, moveNum, moveType, fromX, fromY, toX, toY, promoChar)
4998 ChessMove *moveType;
4999 int *fromX, *fromY, *toX, *toY;
5002 *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
5004 switch (*moveType) {
5005 case WhitePromotion:
5006 case BlackPromotion:
5007 case WhiteNonPromotion:
5008 case BlackNonPromotion:
5010 case WhiteCapturesEnPassant:
5011 case BlackCapturesEnPassant:
5012 case WhiteKingSideCastle:
5013 case WhiteQueenSideCastle:
5014 case BlackKingSideCastle:
5015 case BlackQueenSideCastle:
5016 case WhiteKingSideCastleWild:
5017 case WhiteQueenSideCastleWild:
5018 case BlackKingSideCastleWild:
5019 case BlackQueenSideCastleWild:
5020 /* Code added by Tord: */
5021 case WhiteHSideCastleFR:
5022 case WhiteASideCastleFR:
5023 case BlackHSideCastleFR:
5024 case BlackASideCastleFR:
5025 /* End of code added by Tord */
5026 case IllegalMove: /* bug or odd chess variant */
5027 *fromX = currentMoveString[0] - AAA;
5028 *fromY = currentMoveString[1] - ONE;
5029 *toX = currentMoveString[2] - AAA;
5030 *toY = currentMoveString[3] - ONE;
5031 *promoChar = currentMoveString[4];
5032 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
5033 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
5034 if (appData.debugMode) {
5035 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
5037 *fromX = *fromY = *toX = *toY = 0;
5040 if (appData.testLegality) {
5041 return (*moveType != IllegalMove);
5043 return !(*fromX == *toX && *fromY == *toY) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
5044 WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
5049 *fromX = *moveType == WhiteDrop ?
5050 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5051 (int) CharToPiece(ToLower(currentMoveString[0]));
5053 *toX = currentMoveString[2] - AAA;
5054 *toY = currentMoveString[3] - ONE;
5055 *promoChar = NULLCHAR;
5059 case ImpossibleMove:
5069 if (appData.debugMode) {
5070 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
5073 *fromX = *fromY = *toX = *toY = 0;
5074 *promoChar = NULLCHAR;
5081 ParsePV(char *pv, Boolean storeComments)
5082 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
5083 int fromX, fromY, toX, toY; char promoChar;
5088 endPV = forwardMostMove;
5090 while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
5091 if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
5092 valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
5093 if(appData.debugMode){
5094 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);
5096 if(!valid && nr == 0 &&
5097 ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
5098 nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
5099 // Hande case where played move is different from leading PV move
5100 CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
5101 CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
5102 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
5103 if(!CompareBoards(boards[endPV], boards[endPV+2])) {
5104 endPV += 2; // if position different, keep this
5105 moveList[endPV-1][0] = fromX + AAA;
5106 moveList[endPV-1][1] = fromY + ONE;
5107 moveList[endPV-1][2] = toX + AAA;
5108 moveList[endPV-1][3] = toY + ONE;
5109 parseList[endPV-1][0] = NULLCHAR;
5110 safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
5113 pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
5114 if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5115 if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5116 if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5117 valid++; // allow comments in PV
5121 if(endPV+1 > framePtr) break; // no space, truncate
5124 CopyBoard(boards[endPV], boards[endPV-1]);
5125 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5126 moveList[endPV-1][0] = fromX + AAA;
5127 moveList[endPV-1][1] = fromY + ONE;
5128 moveList[endPV-1][2] = toX + AAA;
5129 moveList[endPV-1][3] = toY + ONE;
5130 moveList[endPV-1][4] = promoChar;
5131 moveList[endPV-1][5] = NULLCHAR;
5132 strncat(moveList[endPV-1], "\n", MOVE_LEN);
5134 CoordsToAlgebraic(boards[endPV - 1],
5135 PosFlags(endPV - 1),
5136 fromY, fromX, toY, toX, promoChar,
5137 parseList[endPV - 1]);
5139 parseList[endPV-1][0] = NULLCHAR;
5141 currentMove = endPV;
5142 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5143 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5144 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5145 DrawPosition(TRUE, boards[currentMove]);
5149 LoadMultiPV(int x, int y, char *buf, int index, int *start, int *end)
5154 if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5155 lastX = x; lastY = y;
5156 while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5158 while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5159 if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5161 do{ while(buf[index] && buf[index] != '\n') index++;
5162 } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5164 ParsePV(buf+startPV, FALSE);
5165 *start = startPV; *end = index-1;
5170 LoadPV(int x, int y)
5171 { // called on right mouse click to load PV
5172 int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5173 lastX = x; lastY = y;
5174 ParsePV(lastPV[which], FALSE); // load the PV of the thinking engine in the boards array.
5181 if(endPV < 0) return;
5183 currentMove = forwardMostMove;
5184 ClearPremoveHighlights();
5185 DrawPosition(TRUE, boards[currentMove]);
5189 MovePV(int x, int y, int h)
5190 { // step through PV based on mouse coordinates (called on mouse move)
5191 int margin = h>>3, step = 0;
5193 // we must somehow check if right button is still down (might be released off board!)
5194 if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
5195 if(abs(x - lastX) < 7 && abs(y - lastY) < 7) return;
5196 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5198 lastX = x; lastY = y;
5200 if(pieceSweep != EmptySquare) { NextPiece(step); return; }
5201 if(endPV < 0) return;
5202 if(y < margin) step = 1; else
5203 if(y > h - margin) step = -1;
5204 if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5205 currentMove += step;
5206 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5207 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5208 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5209 DrawPosition(FALSE, boards[currentMove]);
5213 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5214 // All positions will have equal probability, but the current method will not provide a unique
5215 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5221 int piecesLeft[(int)BlackPawn];
5222 int seed, nrOfShuffles;
5224 void GetPositionNumber()
5225 { // sets global variable seed
5228 seed = appData.defaultFrcPosition;
5229 if(seed < 0) { // randomize based on time for negative FRC position numbers
5230 for(i=0; i<50; i++) seed += random();
5231 seed = random() ^ random() >> 8 ^ random() << 8;
5232 if(seed<0) seed = -seed;
5236 int put(Board board, int pieceType, int rank, int n, int shade)
5237 // put the piece on the (n-1)-th empty squares of the given shade
5241 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5242 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5243 board[rank][i] = (ChessSquare) pieceType;
5244 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5246 piecesLeft[pieceType]--;
5254 void AddOnePiece(Board board, int pieceType, int rank, int shade)
5255 // calculate where the next piece goes, (any empty square), and put it there
5259 i = seed % squaresLeft[shade];
5260 nrOfShuffles *= squaresLeft[shade];
5261 seed /= squaresLeft[shade];
5262 put(board, pieceType, rank, i, shade);
5265 void AddTwoPieces(Board board, int pieceType, int rank)
5266 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5268 int i, n=squaresLeft[ANY], j=n-1, k;
5270 k = n*(n-1)/2; // nr of possibilities, not counting permutations
5271 i = seed % k; // pick one
5274 while(i >= j) i -= j--;
5275 j = n - 1 - j; i += j;
5276 put(board, pieceType, rank, j, ANY);
5277 put(board, pieceType, rank, i, ANY);
5280 void SetUpShuffle(Board board, int number)
5284 GetPositionNumber(); nrOfShuffles = 1;
5286 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5287 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
5288 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5290 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5292 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5293 p = (int) board[0][i];
5294 if(p < (int) BlackPawn) piecesLeft[p] ++;
5295 board[0][i] = EmptySquare;
5298 if(PosFlags(0) & F_ALL_CASTLE_OK) {
5299 // shuffles restricted to allow normal castling put KRR first
5300 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5301 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5302 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5303 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5304 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5305 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5306 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
5307 put(board, WhiteRook, 0, 0, ANY);
5308 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
5311 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
5312 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
5313 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
5314 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
5315 while(piecesLeft[p] >= 2) {
5316 AddOnePiece(board, p, 0, LITE);
5317 AddOnePiece(board, p, 0, DARK);
5319 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
5322 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
5323 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
5324 // but we leave King and Rooks for last, to possibly obey FRC restriction
5325 if(p == (int)WhiteRook) continue;
5326 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
5327 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
5330 // now everything is placed, except perhaps King (Unicorn) and Rooks
5332 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
5333 // Last King gets castling rights
5334 while(piecesLeft[(int)WhiteUnicorn]) {
5335 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5336 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5339 while(piecesLeft[(int)WhiteKing]) {
5340 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5341 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5346 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
5347 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
5350 // Only Rooks can be left; simply place them all
5351 while(piecesLeft[(int)WhiteRook]) {
5352 i = put(board, WhiteRook, 0, 0, ANY);
5353 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
5356 initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
5358 initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
5361 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
5362 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
5365 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
5368 int SetCharTable( char *table, const char * map )
5369 /* [HGM] moved here from winboard.c because of its general usefulness */
5370 /* Basically a safe strcpy that uses the last character as King */
5372 int result = FALSE; int NrPieces;
5374 if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
5375 && NrPieces >= 12 && !(NrPieces&1)) {
5376 int i; /* [HGM] Accept even length from 12 to 34 */
5378 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
5379 for( i=0; i<NrPieces/2-1; i++ ) {
5381 table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
5383 table[(int) WhiteKing] = map[NrPieces/2-1];
5384 table[(int) BlackKing] = map[NrPieces-1];
5392 void Prelude(Board board)
5393 { // [HGM] superchess: random selection of exo-pieces
5394 int i, j, k; ChessSquare p;
5395 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
5397 GetPositionNumber(); // use FRC position number
5399 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
5400 SetCharTable(pieceToChar, appData.pieceToCharTable);
5401 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
5402 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
5405 j = seed%4; seed /= 4;
5406 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5407 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5408 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5409 j = seed%3 + (seed%3 >= j); seed /= 3;
5410 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5411 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5412 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5413 j = seed%3; seed /= 3;
5414 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5415 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5416 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5417 j = seed%2 + (seed%2 >= j); seed /= 2;
5418 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5419 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5420 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5421 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
5422 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
5423 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
5424 put(board, exoPieces[0], 0, 0, ANY);
5425 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
5429 InitPosition(redraw)
5432 ChessSquare (* pieces)[BOARD_FILES];
5433 int i, j, pawnRow, overrule,
5434 oldx = gameInfo.boardWidth,
5435 oldy = gameInfo.boardHeight,
5436 oldh = gameInfo.holdingsWidth;
5439 if(appData.icsActive) shuffleOpenings = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
5441 /* [AS] Initialize pv info list [HGM] and game status */
5443 for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
5444 pvInfoList[i].depth = 0;
5445 boards[i][EP_STATUS] = EP_NONE;
5446 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
5449 initialRulePlies = 0; /* 50-move counter start */
5451 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
5452 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
5456 /* [HGM] logic here is completely changed. In stead of full positions */
5457 /* the initialized data only consist of the two backranks. The switch */
5458 /* selects which one we will use, which is than copied to the Board */
5459 /* initialPosition, which for the rest is initialized by Pawns and */
5460 /* empty squares. This initial position is then copied to boards[0], */
5461 /* possibly after shuffling, so that it remains available. */
5463 gameInfo.holdingsWidth = 0; /* default board sizes */
5464 gameInfo.boardWidth = 8;
5465 gameInfo.boardHeight = 8;
5466 gameInfo.holdingsSize = 0;
5467 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
5468 for(i=0; i<BOARD_FILES-2; i++)
5469 initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
5470 initialPosition[EP_STATUS] = EP_NONE;
5471 SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
5472 if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
5473 SetCharTable(pieceNickName, appData.pieceNickNames);
5474 else SetCharTable(pieceNickName, "............");
5477 switch (gameInfo.variant) {
5478 case VariantFischeRandom:
5479 shuffleOpenings = TRUE;
5482 case VariantShatranj:
5483 pieces = ShatranjArray;
5484 nrCastlingRights = 0;
5485 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
5488 pieces = makrukArray;
5489 nrCastlingRights = 0;
5490 startedFromSetupPosition = TRUE;
5491 SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
5493 case VariantTwoKings:
5494 pieces = twoKingsArray;
5496 case VariantCapaRandom:
5497 shuffleOpenings = TRUE;
5498 case VariantCapablanca:
5499 pieces = CapablancaArray;
5500 gameInfo.boardWidth = 10;
5501 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5504 pieces = GothicArray;
5505 gameInfo.boardWidth = 10;
5506 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5509 SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
5510 gameInfo.holdingsSize = 7;
5513 pieces = JanusArray;
5514 gameInfo.boardWidth = 10;
5515 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
5516 nrCastlingRights = 6;
5517 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5518 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5519 initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
5520 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5521 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5522 initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
5525 pieces = FalconArray;
5526 gameInfo.boardWidth = 10;
5527 SetCharTable(pieceToChar, "PNBRQ.............FKpnbrq.............fk");
5529 case VariantXiangqi:
5530 pieces = XiangqiArray;
5531 gameInfo.boardWidth = 9;
5532 gameInfo.boardHeight = 10;
5533 nrCastlingRights = 0;
5534 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
5537 pieces = ShogiArray;
5538 gameInfo.boardWidth = 9;
5539 gameInfo.boardHeight = 9;
5540 gameInfo.holdingsSize = 7;
5541 nrCastlingRights = 0;
5542 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
5544 case VariantCourier:
5545 pieces = CourierArray;
5546 gameInfo.boardWidth = 12;
5547 nrCastlingRights = 0;
5548 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
5550 case VariantKnightmate:
5551 pieces = KnightmateArray;
5552 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
5554 case VariantSpartan:
5555 pieces = SpartanArray;
5556 SetCharTable(pieceToChar, "PNBRQ................K......lwg.....c...h..k");
5559 pieces = fairyArray;
5560 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
5563 pieces = GreatArray;
5564 gameInfo.boardWidth = 10;
5565 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
5566 gameInfo.holdingsSize = 8;
5570 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
5571 gameInfo.holdingsSize = 8;
5572 startedFromSetupPosition = TRUE;
5574 case VariantCrazyhouse:
5575 case VariantBughouse:
5577 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
5578 gameInfo.holdingsSize = 5;
5580 case VariantWildCastle:
5582 /* !!?shuffle with kings guaranteed to be on d or e file */
5583 shuffleOpenings = 1;
5585 case VariantNoCastle:
5587 nrCastlingRights = 0;
5588 /* !!?unconstrained back-rank shuffle */
5589 shuffleOpenings = 1;
5594 if(appData.NrFiles >= 0) {
5595 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
5596 gameInfo.boardWidth = appData.NrFiles;
5598 if(appData.NrRanks >= 0) {
5599 gameInfo.boardHeight = appData.NrRanks;
5601 if(appData.holdingsSize >= 0) {
5602 i = appData.holdingsSize;
5603 if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
5604 gameInfo.holdingsSize = i;
5606 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
5607 if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
5608 DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
5610 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
5611 if(pawnRow < 1) pawnRow = 1;
5612 if(gameInfo.variant == VariantMakruk) pawnRow = 2;
5614 /* User pieceToChar list overrules defaults */
5615 if(appData.pieceToCharTable != NULL)
5616 SetCharTable(pieceToChar, appData.pieceToCharTable);
5618 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
5620 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
5621 s = (ChessSquare) 0; /* account holding counts in guard band */
5622 for( i=0; i<BOARD_HEIGHT; i++ )
5623 initialPosition[i][j] = s;
5625 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
5626 initialPosition[0][j] = pieces[0][j-gameInfo.holdingsWidth];
5627 initialPosition[pawnRow][j] = WhitePawn;
5628 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
5629 if(gameInfo.variant == VariantXiangqi) {
5631 initialPosition[pawnRow][j] =
5632 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
5633 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
5634 initialPosition[2][j] = WhiteCannon;
5635 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
5639 initialPosition[BOARD_HEIGHT-1][j] = pieces[1][j-gameInfo.holdingsWidth];
5641 if( (gameInfo.variant == VariantShogi) && !overrule ) {
5644 initialPosition[1][j] = WhiteBishop;
5645 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
5647 initialPosition[1][j] = WhiteRook;
5648 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
5651 if( nrCastlingRights == -1) {
5652 /* [HGM] Build normal castling rights (must be done after board sizing!) */
5653 /* This sets default castling rights from none to normal corners */
5654 /* Variants with other castling rights must set them themselves above */
5655 nrCastlingRights = 6;
5657 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5658 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5659 initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
5660 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5661 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5662 initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
5665 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
5666 if(gameInfo.variant == VariantGreat) { // promotion commoners
5667 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
5668 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
5669 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
5670 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
5672 if( gameInfo.variant == VariantSChess ) {
5673 initialPosition[1][0] = BlackMarshall;
5674 initialPosition[2][0] = BlackAngel;
5675 initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
5676 initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
5677 initialPosition[1][1] = initialPosition[2][1] =
5678 initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
5680 if (appData.debugMode) {
5681 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
5683 if(shuffleOpenings) {
5684 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
5685 startedFromSetupPosition = TRUE;
5687 if(startedFromPositionFile) {
5688 /* [HGM] loadPos: use PositionFile for every new game */
5689 CopyBoard(initialPosition, filePosition);
5690 for(i=0; i<nrCastlingRights; i++)
5691 initialRights[i] = filePosition[CASTLING][i];
5692 startedFromSetupPosition = TRUE;
5695 CopyBoard(boards[0], initialPosition);
5697 if(oldx != gameInfo.boardWidth ||
5698 oldy != gameInfo.boardHeight ||
5699 oldv != gameInfo.variant ||
5700 oldh != gameInfo.holdingsWidth
5702 InitDrawingSizes(-2 ,0);
5704 oldv = gameInfo.variant;
5706 DrawPosition(TRUE, boards[currentMove]);
5710 SendBoard(cps, moveNum)
5711 ChessProgramState *cps;
5714 char message[MSG_SIZ];
5716 if (cps->useSetboard) {
5717 char* fen = PositionToFEN(moveNum, cps->fenOverride);
5718 snprintf(message, MSG_SIZ,"setboard %s\n", fen);
5719 SendToProgram(message, cps);
5725 /* Kludge to set black to move, avoiding the troublesome and now
5726 * deprecated "black" command.
5728 if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
5729 SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn ? "a2a3\n" : "black\n", cps);
5731 SendToProgram("edit\n", cps);
5732 SendToProgram("#\n", cps);
5733 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
5734 bp = &boards[moveNum][i][BOARD_LEFT];
5735 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
5736 if ((int) *bp < (int) BlackPawn) {
5737 snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp),
5739 if(message[0] == '+' || message[0] == '~') {
5740 snprintf(message, MSG_SIZ,"%c%c%c+\n",
5741 PieceToChar((ChessSquare)(DEMOTED *bp)),
5744 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
5745 message[1] = BOARD_RGHT - 1 - j + '1';
5746 message[2] = BOARD_HEIGHT - 1 - i + 'a';
5748 SendToProgram(message, cps);
5753 SendToProgram("c\n", cps);
5754 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
5755 bp = &boards[moveNum][i][BOARD_LEFT];
5756 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
5757 if (((int) *bp != (int) EmptySquare)
5758 && ((int) *bp >= (int) BlackPawn)) {
5759 snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
5761 if(message[0] == '+' || message[0] == '~') {
5762 snprintf(message, MSG_SIZ,"%c%c%c+\n",
5763 PieceToChar((ChessSquare)(DEMOTED *bp)),
5766 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
5767 message[1] = BOARD_RGHT - 1 - j + '1';
5768 message[2] = BOARD_HEIGHT - 1 - i + 'a';
5770 SendToProgram(message, cps);
5775 SendToProgram(".\n", cps);
5777 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
5781 DefaultPromoChoice(int white)
5784 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
5785 result = WhiteFerz; // no choice
5786 else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
5787 result= WhiteKing; // in Suicide Q is the last thing we want
5788 else if(gameInfo.variant == VariantSpartan)
5789 result = white ? WhiteQueen : WhiteAngel;
5790 else result = WhiteQueen;
5791 if(!white) result = WHITE_TO_BLACK result;
5795 static int autoQueen; // [HGM] oneclick
5798 HasPromotionChoice(int fromX, int fromY, int toX, int toY, char *promoChoice)
5800 /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
5801 /* [HGM] add Shogi promotions */
5802 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
5807 if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
5808 if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
5810 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
5811 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
5814 piece = boards[currentMove][fromY][fromX];
5815 if(gameInfo.variant == VariantShogi) {
5816 promotionZoneSize = BOARD_HEIGHT/3;
5817 highestPromotingPiece = (int)WhiteFerz;
5818 } else if(gameInfo.variant == VariantMakruk) {
5819 promotionZoneSize = 3;
5822 // Treat Lance as Pawn when it is not representing Amazon
5823 if(gameInfo.variant != VariantSuper) {
5824 if(piece == WhiteLance) piece = WhitePawn; else
5825 if(piece == BlackLance) piece = BlackPawn;
5828 // next weed out all moves that do not touch the promotion zone at all
5829 if((int)piece >= BlackPawn) {
5830 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
5832 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
5834 if( toY < BOARD_HEIGHT - promotionZoneSize &&
5835 fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
5838 if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
5840 // weed out mandatory Shogi promotions
5841 if(gameInfo.variant == VariantShogi) {
5842 if(piece >= BlackPawn) {
5843 if(toY == 0 && piece == BlackPawn ||
5844 toY == 0 && piece == BlackQueen ||
5845 toY <= 1 && piece == BlackKnight) {
5850 if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
5851 toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
5852 toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
5859 // weed out obviously illegal Pawn moves
5860 if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
5861 if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
5862 if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
5863 if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
5864 if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
5865 // note we are not allowed to test for valid (non-)capture, due to premove
5868 // we either have a choice what to promote to, or (in Shogi) whether to promote
5869 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk) {
5870 *promoChoice = PieceToChar(BlackFerz); // no choice
5873 // no sense asking what we must promote to if it is going to explode...
5874 if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
5875 *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
5878 // give caller the default choice even if we will not make it
5879 *promoChoice = ToLower(PieceToChar(defaultPromoChoice));
5880 if(gameInfo.variant == VariantShogi) *promoChoice = '+';
5881 if(appData.sweepSelect && gameInfo.variant != VariantGreat
5882 && gameInfo.variant != VariantShogi
5883 && gameInfo.variant != VariantSuper) return FALSE;
5884 if(autoQueen) return FALSE; // predetermined
5886 // suppress promotion popup on illegal moves that are not premoves
5887 premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
5888 gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
5889 if(appData.testLegality && !premove) {
5890 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
5891 fromY, fromX, toY, toX, gameInfo.variant == VariantShogi ? '+' : NULLCHAR);
5892 if(moveType != WhitePromotion && moveType != BlackPromotion)
5900 InPalace(row, column)
5902 { /* [HGM] for Xiangqi */
5903 if( (row < 3 || row > BOARD_HEIGHT-4) &&
5904 column < (BOARD_WIDTH + 4)/2 &&
5905 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
5910 PieceForSquare (x, y)
5914 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
5917 return boards[currentMove][y][x];
5921 OKToStartUserMove(x, y)
5924 ChessSquare from_piece;
5927 if (matchMode) return FALSE;
5928 if (gameMode == EditPosition) return TRUE;
5930 if (x >= 0 && y >= 0)
5931 from_piece = boards[currentMove][y][x];
5933 from_piece = EmptySquare;
5935 if (from_piece == EmptySquare) return FALSE;
5937 white_piece = (int)from_piece >= (int)WhitePawn &&
5938 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
5941 case PlayFromGameFile:
5943 case TwoMachinesPlay:
5951 case MachinePlaysWhite:
5952 case IcsPlayingBlack:
5953 if (appData.zippyPlay) return FALSE;
5955 DisplayMoveError(_("You are playing Black"));
5960 case MachinePlaysBlack:
5961 case IcsPlayingWhite:
5962 if (appData.zippyPlay) return FALSE;
5964 DisplayMoveError(_("You are playing White"));
5970 if (!white_piece && WhiteOnMove(currentMove)) {
5971 DisplayMoveError(_("It is White's turn"));
5974 if (white_piece && !WhiteOnMove(currentMove)) {
5975 DisplayMoveError(_("It is Black's turn"));
5978 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
5979 /* Editing correspondence game history */
5980 /* Could disallow this or prompt for confirmation */
5985 case BeginningOfGame:
5986 if (appData.icsActive) return FALSE;
5987 if (!appData.noChessProgram) {
5989 DisplayMoveError(_("You are playing White"));
5996 if (!white_piece && WhiteOnMove(currentMove)) {
5997 DisplayMoveError(_("It is White's turn"));
6000 if (white_piece && !WhiteOnMove(currentMove)) {
6001 DisplayMoveError(_("It is Black's turn"));
6010 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
6011 && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
6012 && gameMode != AnalyzeFile && gameMode != Training) {
6013 DisplayMoveError(_("Displayed position is not current"));
6020 OnlyMove(int *x, int *y, Boolean captures) {
6021 DisambiguateClosure cl;
6022 if (appData.zippyPlay) return FALSE;
6024 case MachinePlaysBlack:
6025 case IcsPlayingWhite:
6026 case BeginningOfGame:
6027 if(!WhiteOnMove(currentMove)) return FALSE;
6029 case MachinePlaysWhite:
6030 case IcsPlayingBlack:
6031 if(WhiteOnMove(currentMove)) return FALSE;
6038 cl.pieceIn = EmptySquare;
6043 cl.promoCharIn = NULLCHAR;
6044 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6045 if( cl.kind == NormalMove ||
6046 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6047 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6048 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6055 if(cl.kind != ImpossibleMove) return FALSE;
6056 cl.pieceIn = EmptySquare;
6061 cl.promoCharIn = NULLCHAR;
6062 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6063 if( cl.kind == NormalMove ||
6064 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6065 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6066 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6071 autoQueen = TRUE; // act as if autoQueen on when we click to-square
6077 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
6078 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
6079 int lastLoadGameUseList = FALSE;
6080 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
6081 ChessMove lastLoadGameStart = EndOfFile;
6084 UserMoveEvent(fromX, fromY, toX, toY, promoChar)
6085 int fromX, fromY, toX, toY;
6089 ChessSquare pdown, pup;
6091 /* Check if the user is playing in turn. This is complicated because we
6092 let the user "pick up" a piece before it is his turn. So the piece he
6093 tried to pick up may have been captured by the time he puts it down!
6094 Therefore we use the color the user is supposed to be playing in this
6095 test, not the color of the piece that is currently on the starting
6096 square---except in EditGame mode, where the user is playing both
6097 sides; fortunately there the capture race can't happen. (It can
6098 now happen in IcsExamining mode, but that's just too bad. The user
6099 will get a somewhat confusing message in that case.)
6103 case PlayFromGameFile:
6105 case TwoMachinesPlay:
6109 /* We switched into a game mode where moves are not accepted,
6110 perhaps while the mouse button was down. */
6113 case MachinePlaysWhite:
6114 /* User is moving for Black */
6115 if (WhiteOnMove(currentMove)) {
6116 DisplayMoveError(_("It is White's turn"));
6121 case MachinePlaysBlack:
6122 /* User is moving for White */
6123 if (!WhiteOnMove(currentMove)) {
6124 DisplayMoveError(_("It is Black's turn"));
6131 case BeginningOfGame:
6134 if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
6135 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
6136 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
6137 /* User is moving for Black */
6138 if (WhiteOnMove(currentMove)) {
6139 DisplayMoveError(_("It is White's turn"));
6143 /* User is moving for White */
6144 if (!WhiteOnMove(currentMove)) {
6145 DisplayMoveError(_("It is Black's turn"));
6151 case IcsPlayingBlack:
6152 /* User is moving for Black */
6153 if (WhiteOnMove(currentMove)) {
6154 if (!appData.premove) {
6155 DisplayMoveError(_("It is White's turn"));
6156 } else if (toX >= 0 && toY >= 0) {
6159 premoveFromX = fromX;
6160 premoveFromY = fromY;
6161 premovePromoChar = promoChar;
6163 if (appData.debugMode)
6164 fprintf(debugFP, "Got premove: fromX %d,"
6165 "fromY %d, toX %d, toY %d\n",
6166 fromX, fromY, toX, toY);
6172 case IcsPlayingWhite:
6173 /* User is moving for White */
6174 if (!WhiteOnMove(currentMove)) {
6175 if (!appData.premove) {
6176 DisplayMoveError(_("It is Black's turn"));
6177 } else if (toX >= 0 && toY >= 0) {
6180 premoveFromX = fromX;
6181 premoveFromY = fromY;
6182 premovePromoChar = promoChar;
6184 if (appData.debugMode)
6185 fprintf(debugFP, "Got premove: fromX %d,"
6186 "fromY %d, toX %d, toY %d\n",
6187 fromX, fromY, toX, toY);
6197 /* EditPosition, empty square, or different color piece;
6198 click-click move is possible */
6199 if (toX == -2 || toY == -2) {
6200 boards[0][fromY][fromX] = EmptySquare;
6201 DrawPosition(FALSE, boards[currentMove]);
6203 } else if (toX >= 0 && toY >= 0) {
6204 boards[0][toY][toX] = boards[0][fromY][fromX];
6205 if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
6206 if(boards[0][fromY][0] != EmptySquare) {
6207 if(boards[0][fromY][1]) boards[0][fromY][1]--;
6208 if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
6211 if(fromX == BOARD_RGHT+1) {
6212 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
6213 if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
6214 if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
6217 boards[0][fromY][fromX] = EmptySquare;
6218 DrawPosition(FALSE, boards[currentMove]);
6224 if(toX < 0 || toY < 0) return;
6225 pdown = boards[currentMove][fromY][fromX];
6226 pup = boards[currentMove][toY][toX];
6228 /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
6229 if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
6230 if( pup != EmptySquare ) return;
6231 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
6232 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
6233 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
6234 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
6235 if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
6236 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
6237 while(PieceToChar(fromX) == '.' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
6241 /* [HGM] always test for legality, to get promotion info */
6242 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6243 fromY, fromX, toY, toX, promoChar);
6244 /* [HGM] but possibly ignore an IllegalMove result */
6245 if (appData.testLegality) {
6246 if (moveType == IllegalMove || moveType == ImpossibleMove) {
6247 DisplayMoveError(_("Illegal move"));
6252 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
6255 /* Common tail of UserMoveEvent and DropMenuEvent */
6257 FinishMove(moveType, fromX, fromY, toX, toY, promoChar)
6259 int fromX, fromY, toX, toY;
6260 /*char*/int promoChar;
6264 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) && promoChar != NULLCHAR) {
6265 // [HGM] superchess: suppress promotions to non-available piece
6266 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
6267 if(WhiteOnMove(currentMove)) {
6268 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
6270 if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
6274 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
6275 move type in caller when we know the move is a legal promotion */
6276 if(moveType == NormalMove && promoChar)
6277 moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
6279 /* [HGM] <popupFix> The following if has been moved here from
6280 UserMoveEvent(). Because it seemed to belong here (why not allow
6281 piece drops in training games?), and because it can only be
6282 performed after it is known to what we promote. */
6283 if (gameMode == Training) {
6284 /* compare the move played on the board to the next move in the
6285 * game. If they match, display the move and the opponent's response.
6286 * If they don't match, display an error message.
6290 CopyBoard(testBoard, boards[currentMove]);
6291 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
6293 if (CompareBoards(testBoard, boards[currentMove+1])) {
6294 ForwardInner(currentMove+1);
6296 /* Autoplay the opponent's response.
6297 * if appData.animate was TRUE when Training mode was entered,
6298 * the response will be animated.
6300 saveAnimate = appData.animate;
6301 appData.animate = animateTraining;
6302 ForwardInner(currentMove+1);
6303 appData.animate = saveAnimate;
6305 /* check for the end of the game */
6306 if (currentMove >= forwardMostMove) {
6307 gameMode = PlayFromGameFile;
6309 SetTrainingModeOff();
6310 DisplayInformation(_("End of game"));
6313 DisplayError(_("Incorrect move"), 0);
6318 /* Ok, now we know that the move is good, so we can kill
6319 the previous line in Analysis Mode */
6320 if ((gameMode == AnalyzeMode || gameMode == EditGame)
6321 && currentMove < forwardMostMove) {
6322 if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
6323 else forwardMostMove = currentMove;
6326 /* If we need the chess program but it's dead, restart it */
6327 ResurrectChessProgram();
6329 /* A user move restarts a paused game*/
6333 thinkOutput[0] = NULLCHAR;
6335 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
6337 if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
6338 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6342 if (gameMode == BeginningOfGame) {
6343 if (appData.noChessProgram) {
6344 gameMode = EditGame;
6348 gameMode = MachinePlaysBlack;
6351 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
6353 if (first.sendName) {
6354 snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
6355 SendToProgram(buf, &first);
6362 /* Relay move to ICS or chess engine */
6363 if (appData.icsActive) {
6364 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
6365 gameMode == IcsExamining) {
6366 if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
6367 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
6369 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6371 // also send plain move, in case ICS does not understand atomic claims
6372 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6376 if (first.sendTime && (gameMode == BeginningOfGame ||
6377 gameMode == MachinePlaysWhite ||
6378 gameMode == MachinePlaysBlack)) {
6379 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
6381 if (gameMode != EditGame && gameMode != PlayFromGameFile) {
6382 // [HGM] book: if program might be playing, let it use book
6383 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
6384 first.maybeThinking = TRUE;
6385 } else SendMoveToProgram(forwardMostMove-1, &first);
6386 if (currentMove == cmailOldMove + 1) {
6387 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
6391 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6395 if(appData.testLegality)
6396 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
6402 if (WhiteOnMove(currentMove)) {
6403 GameEnds(BlackWins, "Black mates", GE_PLAYER);
6405 GameEnds(WhiteWins, "White mates", GE_PLAYER);
6409 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
6414 case MachinePlaysBlack:
6415 case MachinePlaysWhite:
6416 /* disable certain menu options while machine is thinking */
6417 SetMachineThinkingEnables();
6424 userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
6425 promoDefaultAltered = FALSE; // [HGM] fall back on default choice
6427 if(bookHit) { // [HGM] book: simulate book reply
6428 static char bookMove[MSG_SIZ]; // a bit generous?
6430 programStats.nodes = programStats.depth = programStats.time =
6431 programStats.score = programStats.got_only_move = 0;
6432 sprintf(programStats.movelist, "%s (xbook)", bookHit);
6434 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
6435 strcat(bookMove, bookHit);
6436 HandleMachineMove(bookMove, &first);
6442 Mark(board, flags, kind, rf, ff, rt, ft, closure)
6449 typedef char Markers[BOARD_RANKS][BOARD_FILES];
6450 Markers *m = (Markers *) closure;
6451 if(rf == fromY && ff == fromX)
6452 (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
6453 || kind == WhiteCapturesEnPassant
6454 || kind == BlackCapturesEnPassant);
6455 else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3;
6459 MarkTargetSquares(int clear)
6462 if(!appData.markers || !appData.highlightDragging ||
6463 !appData.testLegality || gameMode == EditPosition) return;
6465 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) marker[y][x] = 0;
6468 GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker);
6469 if(PosFlags(0) & F_MANDATORY_CAPTURE) {
6470 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
6472 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
6475 DrawPosition(TRUE, NULL);
6479 Explode(Board board, int fromX, int fromY, int toX, int toY)
6481 if(gameInfo.variant == VariantAtomic &&
6482 (board[toY][toX] != EmptySquare || // capture?
6483 toX != fromX && (board[fromY][fromX] == WhitePawn || // e.p. ?
6484 board[fromY][fromX] == BlackPawn )
6486 AnimateAtomicCapture(board, fromX, fromY, toX, toY);
6492 ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
6494 int CanPromote(ChessSquare piece, int y)
6496 if(gameMode == EditPosition) return FALSE; // no promotions when editing position
6497 // some variants have fixed promotion piece, no promotion at all, or another selection mechanism
6498 if(gameInfo.variant == VariantShogi || gameInfo.variant == VariantXiangqi ||
6499 gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat ||
6500 gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6501 gameInfo.variant == VariantMakruk) return FALSE;
6502 return (piece == BlackPawn && y == 1 ||
6503 piece == WhitePawn && y == BOARD_HEIGHT-2 ||
6504 piece == BlackLance && y == 1 ||
6505 piece == WhiteLance && y == BOARD_HEIGHT-2 );
6508 void LeftClick(ClickType clickType, int xPix, int yPix)
6511 Boolean saveAnimate;
6512 static int second = 0, promotionChoice = 0, clearFlag = 0;
6513 char promoChoice = NULLCHAR;
6516 if(appData.seekGraph && appData.icsActive && loggedOn &&
6517 (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
6518 SeekGraphClick(clickType, xPix, yPix, 0);
6522 if (clickType == Press) ErrorPopDown();
6523 MarkTargetSquares(1);
6525 x = EventToSquare(xPix, BOARD_WIDTH);
6526 y = EventToSquare(yPix, BOARD_HEIGHT);
6527 if (!flipView && y >= 0) {
6528 y = BOARD_HEIGHT - 1 - y;
6530 if (flipView && x >= 0) {
6531 x = BOARD_WIDTH - 1 - x;
6534 if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
6535 defaultPromoChoice = promoSweep;
6536 promoSweep = EmptySquare; // terminate sweep
6537 promoDefaultAltered = TRUE;
6538 if(!selectFlag) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
6541 if(promotionChoice) { // we are waiting for a click to indicate promotion piece
6542 if(clickType == Release) return; // ignore upclick of click-click destination
6543 promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
6544 if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
6545 if(gameInfo.holdingsWidth &&
6546 (WhiteOnMove(currentMove)
6547 ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y > 0
6548 : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT-1) ) {
6549 // click in right holdings, for determining promotion piece
6550 ChessSquare p = boards[currentMove][y][x];
6551 if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
6552 if(p != EmptySquare) {
6553 FinishMove(NormalMove, fromX, fromY, toX, toY, ToLower(PieceToChar(p)));
6558 DrawPosition(FALSE, boards[currentMove]);
6562 /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
6563 if(clickType == Press
6564 && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
6565 || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
6566 || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
6569 if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered)
6570 fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
6572 if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
6573 int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
6574 gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
6575 defaultPromoChoice = DefaultPromoChoice(side);
6578 autoQueen = appData.alwaysPromoteToQueen;
6582 gatingPiece = EmptySquare;
6583 if (clickType != Press) {
6584 if(dragging) { // [HGM] from-square must have been reset due to game end since last press
6585 DragPieceEnd(xPix, yPix); dragging = 0;
6586 DrawPosition(FALSE, NULL);
6590 fromX = x; fromY = y;
6591 if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
6592 // even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
6593 appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
6595 if (OKToStartUserMove(fromX, fromY)) {
6597 MarkTargetSquares(0);
6598 DragPieceBegin(xPix, yPix); dragging = 1;
6599 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
6600 promoSweep = defaultPromoChoice;
6601 selectFlag = 0; lastX = xPix; lastY = yPix;
6602 Sweep(0); // Pawn that is going to promote: preview promotion piece
6603 DisplayMessage("", _("Pull pawn backwards to under-promote"));
6605 if (appData.highlightDragging) {
6606 SetHighlights(fromX, fromY, -1, -1);
6608 } else fromX = fromY = -1;
6614 if (clickType == Press && gameMode != EditPosition) {
6619 // ignore off-board to clicks
6620 if(y < 0 || x < 0) return;
6622 /* Check if clicking again on the same color piece */
6623 fromP = boards[currentMove][fromY][fromX];
6624 toP = boards[currentMove][y][x];
6625 frc = gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom || gameInfo.variant == VariantSChess;
6626 if ((WhitePawn <= fromP && fromP <= WhiteKing &&
6627 WhitePawn <= toP && toP <= WhiteKing &&
6628 !(fromP == WhiteKing && toP == WhiteRook && frc) &&
6629 !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
6630 (BlackPawn <= fromP && fromP <= BlackKing &&
6631 BlackPawn <= toP && toP <= BlackKing &&
6632 !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
6633 !(fromP == BlackKing && toP == BlackRook && frc))) {
6634 /* Clicked again on same color piece -- changed his mind */
6635 second = (x == fromX && y == fromY);
6636 promoDefaultAltered = FALSE;
6637 if(!second || appData.oneClick && !OnlyMove(&x, &y, TRUE)) {
6638 if (appData.highlightDragging) {
6639 SetHighlights(x, y, -1, -1);
6643 if (OKToStartUserMove(x, y)) {
6644 if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
6645 (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
6646 y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
6647 gatingPiece = boards[currentMove][fromY][fromX];
6648 else gatingPiece = EmptySquare;
6650 fromY = y; dragging = 1;
6651 MarkTargetSquares(0);
6652 DragPieceBegin(xPix, yPix);
6653 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
6654 promoSweep = defaultPromoChoice;
6655 selectFlag = 0; lastX = xPix; lastY = yPix;
6656 Sweep(0); // Pawn that is going to promote: preview promotion piece
6660 if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
6663 // ignore clicks on holdings
6664 if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
6667 if (clickType == Release && x == fromX && y == fromY) {
6668 DragPieceEnd(xPix, yPix); dragging = 0;
6670 // a deferred attempt to click-click move an empty square on top of a piece
6671 boards[currentMove][y][x] = EmptySquare;
6673 DrawPosition(FALSE, boards[currentMove]);
6674 fromX = fromY = -1; clearFlag = 0;
6677 if (appData.animateDragging) {
6678 /* Undo animation damage if any */
6679 DrawPosition(FALSE, NULL);
6682 /* Second up/down in same square; just abort move */
6685 gatingPiece = EmptySquare;
6688 ClearPremoveHighlights();
6690 /* First upclick in same square; start click-click mode */
6691 SetHighlights(x, y, -1, -1);
6698 /* we now have a different from- and (possibly off-board) to-square */
6699 /* Completed move */
6702 saveAnimate = appData.animate;
6703 if (clickType == Press) {
6704 if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
6705 // must be Edit Position mode with empty-square selected
6706 fromX = x; fromY = y; DragPieceBegin(xPix, yPix); dragging = 1; // consider this a new attempt to drag
6707 if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
6710 /* Finish clickclick move */
6711 if (appData.animate || appData.highlightLastMove) {
6712 SetHighlights(fromX, fromY, toX, toY);
6717 /* Finish drag move */
6718 if (appData.highlightLastMove) {
6719 SetHighlights(fromX, fromY, toX, toY);
6723 DragPieceEnd(xPix, yPix); dragging = 0;
6724 /* Don't animate move and drag both */
6725 appData.animate = FALSE;
6728 // moves into holding are invalid for now (except in EditPosition, adapting to-square)
6729 if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
6730 ChessSquare piece = boards[currentMove][fromY][fromX];
6731 if(gameMode == EditPosition && piece != EmptySquare &&
6732 fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
6735 if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
6736 n = PieceToNumber(piece - (int)BlackPawn);
6737 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
6738 boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
6739 boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
6741 if(x == BOARD_RGHT+1 && piece < BlackPawn) {
6742 n = PieceToNumber(piece);
6743 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
6744 boards[currentMove][n][BOARD_WIDTH-1] = piece;
6745 boards[currentMove][n][BOARD_WIDTH-2]++;
6747 boards[currentMove][fromY][fromX] = EmptySquare;
6751 DrawPosition(TRUE, boards[currentMove]);
6755 // off-board moves should not be highlighted
6756 if(x < 0 || y < 0) ClearHighlights();
6758 if(gatingPiece != EmptySquare) promoChoice = ToLower(PieceToChar(gatingPiece));
6760 if (HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice)) {
6761 SetHighlights(fromX, fromY, toX, toY);
6762 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
6763 // [HGM] super: promotion to captured piece selected from holdings
6764 ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
6765 promotionChoice = TRUE;
6766 // kludge follows to temporarily execute move on display, without promoting yet
6767 boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
6768 boards[currentMove][toY][toX] = p;
6769 DrawPosition(FALSE, boards[currentMove]);
6770 boards[currentMove][fromY][fromX] = p; // take back, but display stays
6771 boards[currentMove][toY][toX] = q;
6772 DisplayMessage("Click in holdings to choose piece", "");
6777 int oldMove = currentMove;
6778 UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
6779 if (!appData.highlightLastMove || gotPremove) ClearHighlights();
6780 if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
6781 if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
6782 Explode(boards[currentMove-1], fromX, fromY, toX, toY))
6783 DrawPosition(TRUE, boards[currentMove]);
6786 appData.animate = saveAnimate;
6787 if (appData.animate || appData.animateDragging) {
6788 /* Undo animation damage if needed */
6789 DrawPosition(FALSE, NULL);
6793 int RightClick(ClickType action, int x, int y, int *fromX, int *fromY)
6794 { // front-end-free part taken out of PieceMenuPopup
6795 int whichMenu; int xSqr, ySqr;
6797 if(seekGraphUp) { // [HGM] seekgraph
6798 if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
6799 if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
6803 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
6804 && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
6805 if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
6806 if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
6807 if(action == Press) {
6808 originalFlip = flipView;
6809 flipView = !flipView; // temporarily flip board to see game from partners perspective
6810 DrawPosition(TRUE, partnerBoard);
6811 DisplayMessage(partnerStatus, "");
6813 } else if(action == Release) {
6814 flipView = originalFlip;
6815 DrawPosition(TRUE, boards[currentMove]);
6821 xSqr = EventToSquare(x, BOARD_WIDTH);
6822 ySqr = EventToSquare(y, BOARD_HEIGHT);
6823 if (action == Release) {
6824 if(pieceSweep != EmptySquare) {
6825 EditPositionMenuEvent(pieceSweep, toX, toY);
6826 pieceSweep = EmptySquare;
6827 } else UnLoadPV(); // [HGM] pv
6829 if (action != Press) return -2; // return code to be ignored
6832 if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
\r
6834 if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
\r
6835 if (xSqr < 0 || ySqr < 0) return -1;
6836 if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
6837 pieceSweep = shiftKey ? BlackPawn : WhitePawn; // [HGM] sweep: prepare selecting piece by mouse sweep
6838 toX = xSqr; toY = ySqr; lastX = x, lastY = y;
6839 if(flipView) toX = BOARD_WIDTH - 1 - toX; else toY = BOARD_HEIGHT - 1 - toY;
6843 if(!appData.icsEngineAnalyze) return -1;
6844 case IcsPlayingWhite:
6845 case IcsPlayingBlack:
6846 if(!appData.zippyPlay) goto noZip;
6849 case MachinePlaysWhite:
6850 case MachinePlaysBlack:
6851 case TwoMachinesPlay: // [HGM] pv: use for showing PV
6852 if (!appData.dropMenu) {
6854 return 2; // flag front-end to grab mouse events
6856 if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
6857 gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
6860 if (xSqr < 0 || ySqr < 0) return -1;
6861 if (!appData.dropMenu || appData.testLegality &&
6862 gameInfo.variant != VariantBughouse &&
6863 gameInfo.variant != VariantCrazyhouse) return -1;
6864 whichMenu = 1; // drop menu
6870 if (((*fromX = xSqr) < 0) ||
6871 ((*fromY = ySqr) < 0)) {
6872 *fromX = *fromY = -1;
6876 *fromX = BOARD_WIDTH - 1 - *fromX;
6878 *fromY = BOARD_HEIGHT - 1 - *fromY;
6883 void SendProgramStatsToFrontend( ChessProgramState * cps, ChessProgramStats * cpstats )
6885 // char * hint = lastHint;
6886 FrontEndProgramStats stats;
6888 stats.which = cps == &first ? 0 : 1;
6889 stats.depth = cpstats->depth;
6890 stats.nodes = cpstats->nodes;
6891 stats.score = cpstats->score;
6892 stats.time = cpstats->time;
6893 stats.pv = cpstats->movelist;
6894 stats.hint = lastHint;
6895 stats.an_move_index = 0;
6896 stats.an_move_count = 0;
6898 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
6899 stats.hint = cpstats->move_name;
6900 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
6901 stats.an_move_count = cpstats->nr_moves;
6904 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
6906 SetProgramStats( &stats );
6910 Count(Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
6911 { // count all piece types
6913 *nB = *nW = *wStale = *bStale = *bishopColor = 0;
6914 for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
6915 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
6918 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
6919 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
6920 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
6921 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
6922 p == BlackBishop || p == BlackFerz || p == BlackAlfil )
6923 *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
6928 SufficientDefence(int pCnt[], int side, int nMine, int nHis)
6930 int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
6931 int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
6933 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
6934 if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
6935 if(myPawns == 2 && nMine == 3) // KPP
6936 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
6937 if(myPawns == 1 && nMine == 2) // KP
6938 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
6939 if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
6940 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
6941 if(myPawns) return FALSE;
6942 if(pCnt[WhiteRook+side])
6943 return pCnt[BlackRook-side] ||
6944 pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
6945 pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
6946 pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
6947 if(pCnt[WhiteCannon+side]) {
6948 if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
6949 return majorDefense || pCnt[BlackAlfil-side] >= 2;
6951 if(pCnt[WhiteKnight+side])
6952 return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
6957 MatingPotential(int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
6959 VariantClass v = gameInfo.variant;
6961 if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
6962 if(v == VariantShatranj) return TRUE; // always winnable through baring
6963 if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
6964 if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
6966 if(v == VariantXiangqi) {
6967 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
6969 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
6970 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
6971 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
6972 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
6973 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
6974 if(stale) // we have at least one last-rank P plus perhaps C
6975 return majors // KPKX
6976 || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
6978 return pCnt[WhiteFerz+side] // KCAK
6979 || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
6980 || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
6981 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
6983 } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
6984 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
6986 if(nMine == 1) return FALSE; // bare King
6987 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
6988 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
6989 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
6990 // by now we have King + 1 piece (or multiple Bishops on the same color)
6991 if(pCnt[WhiteKnight+side])
6992 return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
6993 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
6994 || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
6996 return (pCnt[BlackKnight-side]); // KBKN, KFKN
6997 if(pCnt[WhiteAlfil+side])
6998 return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
6999 if(pCnt[WhiteWazir+side])
7000 return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
7007 Adjudicate(ChessProgramState *cps)
7008 { // [HGM] some adjudications useful with buggy engines
7009 // [HGM] adjudicate: made into separate routine, which now can be called after every move
7010 // In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
7011 // Actually ending the game is now based on the additional internal condition canAdjudicate.
7012 // Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
7013 int k, count = 0; static int bare = 1;
7014 ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
7015 Boolean canAdjudicate = !appData.icsActive;
7017 // most tests only when we understand the game, i.e. legality-checking on
7018 if( appData.testLegality )
7019 { /* [HGM] Some more adjudications for obstinate engines */
7020 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+1], i;
7021 static int moveCount = 6;
7023 char *reason = NULL;
7025 /* Count what is on board. */
7026 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
7028 /* Some material-based adjudications that have to be made before stalemate test */
7029 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
7030 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
7031 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
7032 if(canAdjudicate && appData.checkMates) {
7034 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7035 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
7036 "Xboard adjudication: King destroyed", GE_XBOARD );
7041 /* Bare King in Shatranj (loses) or Losers (wins) */
7042 if( nrW == 1 || nrB == 1) {
7043 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
7044 boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
7045 if(canAdjudicate && appData.checkMates) {
7047 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
7048 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7049 "Xboard adjudication: Bare king", GE_XBOARD );
7053 if( gameInfo.variant == VariantShatranj && --bare < 0)
7055 boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
7056 if(canAdjudicate && appData.checkMates) {
7057 /* but only adjudicate if adjudication enabled */
7059 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7060 GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
7061 "Xboard adjudication: Bare king", GE_XBOARD );
7068 // don't wait for engine to announce game end if we can judge ourselves
7069 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
7071 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
7072 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
7073 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
7074 if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
7077 reason = "Xboard adjudication: 3rd check";
7078 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
7088 reason = "Xboard adjudication: Stalemate";
7089 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
7090 boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
7091 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
7092 boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
7093 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
7094 boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
7095 ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
7096 EP_CHECKMATE : EP_WINS);
7097 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi)
7098 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
7102 reason = "Xboard adjudication: Checkmate";
7103 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
7107 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
7109 result = GameIsDrawn; break;
7111 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
7113 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
7117 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
7119 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7120 GameEnds( result, reason, GE_XBOARD );
7124 /* Next absolutely insufficient mating material. */
7125 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
7126 !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
7127 { /* includes KBK, KNK, KK of KBKB with like Bishops */
7129 /* always flag draws, for judging claims */
7130 boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
7132 if(canAdjudicate && appData.materialDraws) {
7133 /* but only adjudicate them if adjudication enabled */
7134 if(engineOpponent) {
7135 SendToProgram("force\n", engineOpponent); // suppress reply
7136 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
7138 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
7143 /* Then some trivial draws (only adjudicate, cannot be claimed) */
7144 if(gameInfo.variant == VariantXiangqi ?
7145 SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
7147 ( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
7148 || nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
7149 || nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
7150 || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
7152 if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
7153 { /* if the first 3 moves do not show a tactical win, declare draw */
7154 if(engineOpponent) {
7155 SendToProgram("force\n", engineOpponent); // suppress reply
7156 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7158 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
7161 } else moveCount = 6;
7163 if (appData.debugMode) { int i;
7164 fprintf(debugFP, "repeat test fmm=%d bmm=%d ep=%d, reps=%d\n",
7165 forwardMostMove, backwardMostMove, boards[backwardMostMove][EP_STATUS],
7166 appData.drawRepeats);
7167 for( i=forwardMostMove; i>=backwardMostMove; i-- )
7168 fprintf(debugFP, "%d ep=%d\n", i, (signed char)boards[i][EP_STATUS]);
7172 // Repetition draws and 50-move rule can be applied independently of legality testing
7174 /* Check for rep-draws */
7176 for(k = forwardMostMove-2;
7177 k>=backwardMostMove && k>=forwardMostMove-100 &&
7178 (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
7179 (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE;
7182 if(CompareBoards(boards[k], boards[forwardMostMove])) {
7183 /* compare castling rights */
7184 if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
7185 (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
7186 rights++; /* King lost rights, while rook still had them */
7187 if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
7188 if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
7189 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
7190 rights++; /* but at least one rook lost them */
7192 if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
7193 (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
7195 if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
7196 if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
7197 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
7200 if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
7201 && appData.drawRepeats > 1) {
7202 /* adjudicate after user-specified nr of repeats */
7203 int result = GameIsDrawn;
7204 char *details = "XBoard adjudication: repetition draw";
7205 if(gameInfo.variant == VariantXiangqi && appData.testLegality) {
7206 // [HGM] xiangqi: check for forbidden perpetuals
7207 int m, ourPerpetual = 1, hisPerpetual = 1;
7208 for(m=forwardMostMove; m>k; m-=2) {
7209 if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
7210 ourPerpetual = 0; // the current mover did not always check
7211 if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
7212 hisPerpetual = 0; // the opponent did not always check
7214 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
7215 ourPerpetual, hisPerpetual);
7216 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
7217 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7218 details = "Xboard adjudication: perpetual checking";
7220 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
7221 break; // (or we would have caught him before). Abort repetition-checking loop.
7223 // Now check for perpetual chases
7224 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
7225 hisPerpetual = PerpetualChase(k, forwardMostMove);
7226 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
7227 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
7228 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7229 details = "Xboard adjudication: perpetual chasing";
7231 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
7232 break; // Abort repetition-checking loop.
7234 // if neither of us is checking or chasing all the time, or both are, it is draw
7236 if(engineOpponent) {
7237 SendToProgram("force\n", engineOpponent); // suppress reply
7238 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7240 GameEnds( result, details, GE_XBOARD );
7243 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
7244 boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
7248 /* Now we test for 50-move draws. Determine ply count */
7249 count = forwardMostMove;
7250 /* look for last irreversble move */
7251 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
7253 /* if we hit starting position, add initial plies */
7254 if( count == backwardMostMove )
7255 count -= initialRulePlies;
7256 count = forwardMostMove - count;
7257 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
7258 // adjust reversible move counter for checks in Xiangqi
7259 int i = forwardMostMove - count, inCheck = 0, lastCheck;
7260 if(i < backwardMostMove) i = backwardMostMove;
7261 while(i <= forwardMostMove) {
7262 lastCheck = inCheck; // check evasion does not count
7263 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
7264 if(inCheck || lastCheck) count--; // check does not count
7269 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
7270 /* this is used to judge if draw claims are legal */
7271 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
7272 if(engineOpponent) {
7273 SendToProgram("force\n", engineOpponent); // suppress reply
7274 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7276 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
7280 /* if draw offer is pending, treat it as a draw claim
7281 * when draw condition present, to allow engines a way to
7282 * claim draws before making their move to avoid a race
7283 * condition occurring after their move
7285 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
7287 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
7288 p = "Draw claim: 50-move rule";
7289 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
7290 p = "Draw claim: 3-fold repetition";
7291 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
7292 p = "Draw claim: insufficient mating material";
7293 if( p != NULL && canAdjudicate) {
7294 if(engineOpponent) {
7295 SendToProgram("force\n", engineOpponent); // suppress reply
7296 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7298 GameEnds( GameIsDrawn, p, GE_XBOARD );
7303 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
7304 if(engineOpponent) {
7305 SendToProgram("force\n", engineOpponent); // suppress reply
7306 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7308 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
7314 char *SendMoveToBookUser(int moveNr, ChessProgramState *cps, int initial)
7315 { // [HGM] book: this routine intercepts moves to simulate book replies
7316 char *bookHit = NULL;
7318 //first determine if the incoming move brings opponent into his book
7319 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
7320 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
7321 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
7322 if(bookHit != NULL && !cps->bookSuspend) {
7323 // make sure opponent is not going to reply after receiving move to book position
7324 SendToProgram("force\n", cps);
7325 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
7327 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
7328 // now arrange restart after book miss
7330 // after a book hit we never send 'go', and the code after the call to this routine
7331 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
7333 snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), bookHit); // force book move into program supposed to play it
7334 SendToProgram(buf, cps);
7335 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
7336 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
7337 SendToProgram("go\n", cps);
7338 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
7339 } else { // 'go' might be sent based on 'firstMove' after this routine returns
7340 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
7341 SendToProgram("go\n", cps);
7342 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
7344 return bookHit; // notify caller of hit, so it can take action to send move to opponent
7348 ChessProgramState *savedState;
7349 void DeferredBookMove(void)
7351 if(savedState->lastPing != savedState->lastPong)
7352 ScheduleDelayedEvent(DeferredBookMove, 10);
7354 HandleMachineMove(savedMessage, savedState);
7358 HandleMachineMove(message, cps)
7360 ChessProgramState *cps;
7362 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
7363 char realname[MSG_SIZ];
7364 int fromX, fromY, toX, toY;
7373 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
7375 * Kludge to ignore BEL characters
7377 while (*message == '\007') message++;
7380 * [HGM] engine debug message: ignore lines starting with '#' character
7382 if(cps->debug && *message == '#') return;
7385 * Look for book output
7387 if (cps == &first && bookRequested) {
7388 if (message[0] == '\t' || message[0] == ' ') {
7389 /* Part of the book output is here; append it */
7390 strcat(bookOutput, message);
7391 strcat(bookOutput, " \n");
7393 } else if (bookOutput[0] != NULLCHAR) {
7394 /* All of book output has arrived; display it */
7395 char *p = bookOutput;
7396 while (*p != NULLCHAR) {
7397 if (*p == '\t') *p = ' ';
7400 DisplayInformation(bookOutput);
7401 bookRequested = FALSE;
7402 /* Fall through to parse the current output */
7407 * Look for machine move.
7409 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
7410 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
7412 /* This method is only useful on engines that support ping */
7413 if (cps->lastPing != cps->lastPong) {
7414 if (gameMode == BeginningOfGame) {
7415 /* Extra move from before last new; ignore */
7416 if (appData.debugMode) {
7417 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7420 if (appData.debugMode) {
7421 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7422 cps->which, gameMode);
7425 SendToProgram("undo\n", cps);
7431 case BeginningOfGame:
7432 /* Extra move from before last reset; ignore */
7433 if (appData.debugMode) {
7434 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7441 /* Extra move after we tried to stop. The mode test is
7442 not a reliable way of detecting this problem, but it's
7443 the best we can do on engines that don't support ping.
7445 if (appData.debugMode) {
7446 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7447 cps->which, gameMode);
7449 SendToProgram("undo\n", cps);
7452 case MachinePlaysWhite:
7453 case IcsPlayingWhite:
7454 machineWhite = TRUE;
7457 case MachinePlaysBlack:
7458 case IcsPlayingBlack:
7459 machineWhite = FALSE;
7462 case TwoMachinesPlay:
7463 machineWhite = (cps->twoMachinesColor[0] == 'w');
7466 if (WhiteOnMove(forwardMostMove) != machineWhite) {
7467 if (appData.debugMode) {
7469 "Ignoring move out of turn by %s, gameMode %d"
7470 ", forwardMost %d\n",
7471 cps->which, gameMode, forwardMostMove);
7476 if (appData.debugMode) { int f = forwardMostMove;
7477 fprintf(debugFP, "machine move %d, castling = %d %d %d %d %d %d\n", f,
7478 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
7479 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
7481 if(cps->alphaRank) AlphaRank(machineMove, 4);
7482 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
7483 &fromX, &fromY, &toX, &toY, &promoChar)) {
7484 /* Machine move could not be parsed; ignore it. */
7485 snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
7486 machineMove, _(cps->which));
7487 DisplayError(buf1, 0);
7488 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
7489 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType);
7490 if (gameMode == TwoMachinesPlay) {
7491 GameEnds(machineWhite ? BlackWins : WhiteWins,
7497 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
7498 /* So we have to redo legality test with true e.p. status here, */
7499 /* to make sure an illegal e.p. capture does not slip through, */
7500 /* to cause a forfeit on a justified illegal-move complaint */
7501 /* of the opponent. */
7502 if( gameMode==TwoMachinesPlay && appData.testLegality ) {
7504 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
7505 fromY, fromX, toY, toX, promoChar);
7506 if (appData.debugMode) {
7508 for(i=0; i< nrCastlingRights; i++) fprintf(debugFP, "(%d,%d) ",
7509 boards[forwardMostMove][CASTLING][i], castlingRank[i]);
7510 fprintf(debugFP, "castling rights\n");
7512 if(moveType == IllegalMove) {
7513 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
7514 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
7515 GameEnds(machineWhite ? BlackWins : WhiteWins,
7518 } else if(gameInfo.variant != VariantFischeRandom && gameInfo.variant != VariantCapaRandom)
7519 /* [HGM] Kludge to handle engines that send FRC-style castling
7520 when they shouldn't (like TSCP-Gothic) */
7522 case WhiteASideCastleFR:
7523 case BlackASideCastleFR:
7525 currentMoveString[2]++;
7527 case WhiteHSideCastleFR:
7528 case BlackHSideCastleFR:
7530 currentMoveString[2]--;
7532 default: ; // nothing to do, but suppresses warning of pedantic compilers
7535 hintRequested = FALSE;
7536 lastHint[0] = NULLCHAR;
7537 bookRequested = FALSE;
7538 /* Program may be pondering now */
7539 cps->maybeThinking = TRUE;
7540 if (cps->sendTime == 2) cps->sendTime = 1;
7541 if (cps->offeredDraw) cps->offeredDraw--;
7543 /* [AS] Save move info*/
7544 pvInfoList[ forwardMostMove ].score = programStats.score;
7545 pvInfoList[ forwardMostMove ].depth = programStats.depth;
7546 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
7548 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
7550 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
7551 if( gameMode == TwoMachinesPlay && adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
7554 while( count < adjudicateLossPlies ) {
7555 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
7558 score = -score; /* Flip score for winning side */
7561 if( score > adjudicateLossThreshold ) {
7568 if( count >= adjudicateLossPlies ) {
7569 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7571 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7572 "Xboard adjudication",
7579 if(Adjudicate(cps)) {
7580 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7581 return; // [HGM] adjudicate: for all automatic game ends
7585 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
7587 if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
7588 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
7590 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7592 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7594 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
7595 char buf[3*MSG_SIZ];
7597 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
7598 programStats.score / 100.,
7600 programStats.time / 100.,
7601 (unsigned int)programStats.nodes,
7602 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
7603 programStats.movelist);
7605 if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.nodes, programStats.nodes);
7610 /* [AS] Clear stats for next move */
7611 ClearProgramStats();
7612 thinkOutput[0] = NULLCHAR;
7613 hiddenThinkOutputState = 0;
7616 if (gameMode == TwoMachinesPlay) {
7617 /* [HGM] relaying draw offers moved to after reception of move */
7618 /* and interpreting offer as claim if it brings draw condition */
7619 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
7620 SendToProgram("draw\n", cps->other);
7622 if (cps->other->sendTime) {
7623 SendTimeRemaining(cps->other,
7624 cps->other->twoMachinesColor[0] == 'w');
7626 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
7627 if (firstMove && !bookHit) {
7629 if (cps->other->useColors) {
7630 SendToProgram(cps->other->twoMachinesColor, cps->other);
7632 SendToProgram("go\n", cps->other);
7634 cps->other->maybeThinking = TRUE;
7637 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7639 if (!pausing && appData.ringBellAfterMoves) {
7644 * Reenable menu items that were disabled while
7645 * machine was thinking
7647 if (gameMode != TwoMachinesPlay)
7648 SetUserThinkingEnables();
7650 // [HGM] book: after book hit opponent has received move and is now in force mode
7651 // force the book reply into it, and then fake that it outputted this move by jumping
7652 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
7654 static char bookMove[MSG_SIZ]; // a bit generous?
7656 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
7657 strcat(bookMove, bookHit);
7660 programStats.nodes = programStats.depth = programStats.time =
7661 programStats.score = programStats.got_only_move = 0;
7662 sprintf(programStats.movelist, "%s (xbook)", bookHit);
7664 if(cps->lastPing != cps->lastPong) {
7665 savedMessage = message; // args for deferred call
7667 ScheduleDelayedEvent(DeferredBookMove, 10);
7676 /* Set special modes for chess engines. Later something general
7677 * could be added here; for now there is just one kludge feature,
7678 * needed because Crafty 15.10 and earlier don't ignore SIGINT
7679 * when "xboard" is given as an interactive command.
7681 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
7682 cps->useSigint = FALSE;
7683 cps->useSigterm = FALSE;
7685 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
7686 ParseFeatures(message+8, cps);
7687 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
7690 if (!appData.testLegality && !strncmp(message, "setup ", 6)) { // [HGM] allow first engine to define opening position
7691 int dummy, s=6; char buf[MSG_SIZ];
7692 if(appData.icsActive || forwardMostMove != 0 || cps != &first || startedFromSetupPosition) return;
7693 if(sscanf(message, "setup (%s", buf) == 1) s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTable(pieceToChar, buf);
7694 ParseFEN(boards[0], &dummy, message+s);
7695 DrawPosition(TRUE, boards[0]);
7696 startedFromSetupPosition = TRUE;
7699 /* [HGM] Allow engine to set up a position. Don't ask me why one would
7700 * want this, I was asked to put it in, and obliged.
7702 if (!strncmp(message, "setboard ", 9)) {
7703 Board initial_position;
7705 GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
7707 if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9)) {
7708 DisplayError(_("Bad FEN received from engine"), 0);
7712 CopyBoard(boards[0], initial_position);
7713 initialRulePlies = FENrulePlies;
7714 if(blackPlaysFirst) gameMode = MachinePlaysWhite;
7715 else gameMode = MachinePlaysBlack;
7716 DrawPosition(FALSE, boards[currentMove]);
7722 * Look for communication commands
7724 if (!strncmp(message, "telluser ", 9)) {
7725 if(message[9] == '\\' && message[10] == '\\')
7726 EscapeExpand(message+9, message+11); // [HGM] esc: allow escape sequences in popup box
7727 DisplayNote(message + 9);
7730 if (!strncmp(message, "tellusererror ", 14)) {
7732 if(message[14] == '\\' && message[15] == '\\')
7733 EscapeExpand(message+14, message+16); // [HGM] esc: allow escape sequences in popup box
7734 DisplayError(message + 14, 0);
7737 if (!strncmp(message, "tellopponent ", 13)) {
7738 if (appData.icsActive) {
7740 snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
7744 DisplayNote(message + 13);
7748 if (!strncmp(message, "tellothers ", 11)) {
7749 if (appData.icsActive) {
7751 snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
7757 if (!strncmp(message, "tellall ", 8)) {
7758 if (appData.icsActive) {
7760 snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
7764 DisplayNote(message + 8);
7768 if (strncmp(message, "warning", 7) == 0) {
7769 /* Undocumented feature, use tellusererror in new code */
7770 DisplayError(message, 0);
7773 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
7774 safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
7775 strcat(realname, " query");
7776 AskQuestion(realname, buf2, buf1, cps->pr);
7779 /* Commands from the engine directly to ICS. We don't allow these to be
7780 * sent until we are logged on. Crafty kibitzes have been known to
7781 * interfere with the login process.
7784 if (!strncmp(message, "tellics ", 8)) {
7785 SendToICS(message + 8);
7789 if (!strncmp(message, "tellicsnoalias ", 15)) {
7790 SendToICS(ics_prefix);
7791 SendToICS(message + 15);
7795 /* The following are for backward compatibility only */
7796 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
7797 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
7798 SendToICS(ics_prefix);
7804 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
7808 * If the move is illegal, cancel it and redraw the board.
7809 * Also deal with other error cases. Matching is rather loose
7810 * here to accommodate engines written before the spec.
7812 if (strncmp(message + 1, "llegal move", 11) == 0 ||
7813 strncmp(message, "Error", 5) == 0) {
7814 if (StrStr(message, "name") ||
7815 StrStr(message, "rating") || StrStr(message, "?") ||
7816 StrStr(message, "result") || StrStr(message, "board") ||
7817 StrStr(message, "bk") || StrStr(message, "computer") ||
7818 StrStr(message, "variant") || StrStr(message, "hint") ||
7819 StrStr(message, "random") || StrStr(message, "depth") ||
7820 StrStr(message, "accepted")) {
7823 if (StrStr(message, "protover")) {
7824 /* Program is responding to input, so it's apparently done
7825 initializing, and this error message indicates it is
7826 protocol version 1. So we don't need to wait any longer
7827 for it to initialize and send feature commands. */
7828 FeatureDone(cps, 1);
7829 cps->protocolVersion = 1;
7832 cps->maybeThinking = FALSE;
7834 if (StrStr(message, "draw")) {
7835 /* Program doesn't have "draw" command */
7836 cps->sendDrawOffers = 0;
7839 if (cps->sendTime != 1 &&
7840 (StrStr(message, "time") || StrStr(message, "otim"))) {
7841 /* Program apparently doesn't have "time" or "otim" command */
7845 if (StrStr(message, "analyze")) {
7846 cps->analysisSupport = FALSE;
7847 cps->analyzing = FALSE;
7849 snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
7850 DisplayError(buf2, 0);
7853 if (StrStr(message, "(no matching move)st")) {
7854 /* Special kludge for GNU Chess 4 only */
7855 cps->stKludge = TRUE;
7856 SendTimeControl(cps, movesPerSession, timeControl,
7857 timeIncrement, appData.searchDepth,
7861 if (StrStr(message, "(no matching move)sd")) {
7862 /* Special kludge for GNU Chess 4 only */
7863 cps->sdKludge = TRUE;
7864 SendTimeControl(cps, movesPerSession, timeControl,
7865 timeIncrement, appData.searchDepth,
7869 if (!StrStr(message, "llegal")) {
7872 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
7873 gameMode == IcsIdle) return;
7874 if (forwardMostMove <= backwardMostMove) return;
7875 if (pausing) PauseEvent();
7876 if(appData.forceIllegal) {
7877 // [HGM] illegal: machine refused move; force position after move into it
7878 SendToProgram("force\n", cps);
7879 if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
7880 // we have a real problem now, as SendBoard will use the a2a3 kludge
7881 // when black is to move, while there might be nothing on a2 or black
7882 // might already have the move. So send the board as if white has the move.
7883 // But first we must change the stm of the engine, as it refused the last move
7884 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
7885 if(WhiteOnMove(forwardMostMove)) {
7886 SendToProgram("a7a6\n", cps); // for the engine black still had the move
7887 SendBoard(cps, forwardMostMove); // kludgeless board
7889 SendToProgram("a2a3\n", cps); // for the engine white still had the move
7890 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
7891 SendBoard(cps, forwardMostMove+1); // kludgeless board
7893 } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
7894 if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
7895 gameMode == TwoMachinesPlay)
7896 SendToProgram("go\n", cps);
7899 if (gameMode == PlayFromGameFile) {
7900 /* Stop reading this game file */
7901 gameMode = EditGame;
7904 /* [HGM] illegal-move claim should forfeit game when Xboard */
7905 /* only passes fully legal moves */
7906 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
7907 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
7908 "False illegal-move claim", GE_XBOARD );
7909 return; // do not take back move we tested as valid
7911 currentMove = forwardMostMove-1;
7912 DisplayMove(currentMove-1); /* before DisplayMoveError */
7913 SwitchClocks(forwardMostMove-1); // [HGM] race
7914 DisplayBothClocks();
7915 snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
7916 parseList[currentMove], _(cps->which));
7917 DisplayMoveError(buf1);
7918 DrawPosition(FALSE, boards[currentMove]);
7921 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
7922 /* Program has a broken "time" command that
7923 outputs a string not ending in newline.
7929 * If chess program startup fails, exit with an error message.
7930 * Attempts to recover here are futile.
7932 if ((StrStr(message, "unknown host") != NULL)
7933 || (StrStr(message, "No remote directory") != NULL)
7934 || (StrStr(message, "not found") != NULL)
7935 || (StrStr(message, "No such file") != NULL)
7936 || (StrStr(message, "can't alloc") != NULL)
7937 || (StrStr(message, "Permission denied") != NULL)) {
7939 cps->maybeThinking = FALSE;
7940 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
7941 _(cps->which), cps->program, cps->host, message);
7942 RemoveInputSource(cps->isr);
7943 if(appData.icsActive) DisplayFatalError(buf1, 0, 1); else {
7944 if(cps == &first) appData.noChessProgram = TRUE;
7945 DisplayError(buf1, 0);
7951 * Look for hint output
7953 if (sscanf(message, "Hint: %s", buf1) == 1) {
7954 if (cps == &first && hintRequested) {
7955 hintRequested = FALSE;
7956 if (ParseOneMove(buf1, forwardMostMove, &moveType,
7957 &fromX, &fromY, &toX, &toY, &promoChar)) {
7958 (void) CoordsToAlgebraic(boards[forwardMostMove],
7959 PosFlags(forwardMostMove),
7960 fromY, fromX, toY, toX, promoChar, buf1);
7961 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
7962 DisplayInformation(buf2);
7964 /* Hint move could not be parsed!? */
7965 snprintf(buf2, sizeof(buf2),
7966 _("Illegal hint move \"%s\"\nfrom %s chess program"),
7967 buf1, _(cps->which));
7968 DisplayError(buf2, 0);
7971 safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
7977 * Ignore other messages if game is not in progress
7979 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
7980 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
7983 * look for win, lose, draw, or draw offer
7985 if (strncmp(message, "1-0", 3) == 0) {
7986 char *p, *q, *r = "";
7987 p = strchr(message, '{');
7995 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
7997 } else if (strncmp(message, "0-1", 3) == 0) {
7998 char *p, *q, *r = "";
7999 p = strchr(message, '{');
8007 /* Kludge for Arasan 4.1 bug */
8008 if (strcmp(r, "Black resigns") == 0) {
8009 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
8012 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
8014 } else if (strncmp(message, "1/2", 3) == 0) {
8015 char *p, *q, *r = "";
8016 p = strchr(message, '{');
8025 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
8028 } else if (strncmp(message, "White resign", 12) == 0) {
8029 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8031 } else if (strncmp(message, "Black resign", 12) == 0) {
8032 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8034 } else if (strncmp(message, "White matches", 13) == 0 ||
8035 strncmp(message, "Black matches", 13) == 0 ) {
8036 /* [HGM] ignore GNUShogi noises */
8038 } else if (strncmp(message, "White", 5) == 0 &&
8039 message[5] != '(' &&
8040 StrStr(message, "Black") == NULL) {
8041 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8043 } else if (strncmp(message, "Black", 5) == 0 &&
8044 message[5] != '(') {
8045 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8047 } else if (strcmp(message, "resign") == 0 ||
8048 strcmp(message, "computer resigns") == 0) {
8050 case MachinePlaysBlack:
8051 case IcsPlayingBlack:
8052 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
8054 case MachinePlaysWhite:
8055 case IcsPlayingWhite:
8056 GameEnds(BlackWins, "White resigns", GE_ENGINE);
8058 case TwoMachinesPlay:
8059 if (cps->twoMachinesColor[0] == 'w')
8060 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8062 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8069 } else if (strncmp(message, "opponent mates", 14) == 0) {
8071 case MachinePlaysBlack:
8072 case IcsPlayingBlack:
8073 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8075 case MachinePlaysWhite:
8076 case IcsPlayingWhite:
8077 GameEnds(BlackWins, "Black mates", GE_ENGINE);
8079 case TwoMachinesPlay:
8080 if (cps->twoMachinesColor[0] == 'w')
8081 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8083 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8090 } else if (strncmp(message, "computer mates", 14) == 0) {
8092 case MachinePlaysBlack:
8093 case IcsPlayingBlack:
8094 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
8096 case MachinePlaysWhite:
8097 case IcsPlayingWhite:
8098 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8100 case TwoMachinesPlay:
8101 if (cps->twoMachinesColor[0] == 'w')
8102 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8104 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8111 } else if (strncmp(message, "checkmate", 9) == 0) {
8112 if (WhiteOnMove(forwardMostMove)) {
8113 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8115 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8118 } else if (strstr(message, "Draw") != NULL ||
8119 strstr(message, "game is a draw") != NULL) {
8120 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
8122 } else if (strstr(message, "offer") != NULL &&
8123 strstr(message, "draw") != NULL) {
8125 if (appData.zippyPlay && first.initDone) {
8126 /* Relay offer to ICS */
8127 SendToICS(ics_prefix);
8128 SendToICS("draw\n");
8131 cps->offeredDraw = 2; /* valid until this engine moves twice */
8132 if (gameMode == TwoMachinesPlay) {
8133 if (cps->other->offeredDraw) {
8134 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8135 /* [HGM] in two-machine mode we delay relaying draw offer */
8136 /* until after we also have move, to see if it is really claim */
8138 } else if (gameMode == MachinePlaysWhite ||
8139 gameMode == MachinePlaysBlack) {
8140 if (userOfferedDraw) {
8141 DisplayInformation(_("Machine accepts your draw offer"));
8142 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8144 DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
8151 * Look for thinking output
8153 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
8154 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
8156 int plylev, mvleft, mvtot, curscore, time;
8157 char mvname[MOVE_LEN];
8161 int prefixHint = FALSE;
8162 mvname[0] = NULLCHAR;
8165 case MachinePlaysBlack:
8166 case IcsPlayingBlack:
8167 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8169 case MachinePlaysWhite:
8170 case IcsPlayingWhite:
8171 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8176 case IcsObserving: /* [DM] icsEngineAnalyze */
8177 if (!appData.icsEngineAnalyze) ignore = TRUE;
8179 case TwoMachinesPlay:
8180 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
8190 ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
8192 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8193 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
8195 if (plyext != ' ' && plyext != '\t') {
8199 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8200 if( cps->scoreIsAbsolute &&
8201 ( gameMode == MachinePlaysBlack ||
8202 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
8203 gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
8204 (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
8205 !WhiteOnMove(currentMove)
8208 curscore = -curscore;
8212 tempStats.depth = plylev;
8213 tempStats.nodes = nodes;
8214 tempStats.time = time;
8215 tempStats.score = curscore;
8216 tempStats.got_only_move = 0;
8218 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
8221 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
8222 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
8223 if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
8224 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
8225 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
8226 if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
8227 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
8228 blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
8231 /* Buffer overflow protection */
8232 if (buf1[0] != NULLCHAR) {
8233 if (strlen(buf1) >= sizeof(tempStats.movelist)
8234 && appData.debugMode) {
8236 "PV is too long; using the first %u bytes.\n",
8237 (unsigned) sizeof(tempStats.movelist) - 1);
8240 safeStrCpy( tempStats.movelist, buf1, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
8242 sprintf(tempStats.movelist, " no PV\n");
8245 if (tempStats.seen_stat) {
8246 tempStats.ok_to_send = 1;
8249 if (strchr(tempStats.movelist, '(') != NULL) {
8250 tempStats.line_is_book = 1;
8251 tempStats.nr_moves = 0;
8252 tempStats.moves_left = 0;
8254 tempStats.line_is_book = 0;
8257 if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
8258 programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
8260 SendProgramStatsToFrontend( cps, &tempStats );
8263 [AS] Protect the thinkOutput buffer from overflow... this
8264 is only useful if buf1 hasn't overflowed first!
8266 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s",
8268 (gameMode == TwoMachinesPlay ?
8269 ToUpper(cps->twoMachinesColor[0]) : ' '),
8270 ((double) curscore) / 100.0,
8271 prefixHint ? lastHint : "",
8272 prefixHint ? " " : "" );
8274 if( buf1[0] != NULLCHAR ) {
8275 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
8277 if( strlen(buf1) > max_len ) {
8278 if( appData.debugMode) {
8279 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
8281 buf1[max_len+1] = '\0';
8284 strcat( thinkOutput, buf1 );
8287 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
8288 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8289 DisplayMove(currentMove - 1);
8293 } else if ((p=StrStr(message, "(only move)")) != NULL) {
8294 /* crafty (9.25+) says "(only move) <move>"
8295 * if there is only 1 legal move
8297 sscanf(p, "(only move) %s", buf1);
8298 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
8299 sprintf(programStats.movelist, "%s (only move)", buf1);
8300 programStats.depth = 1;
8301 programStats.nr_moves = 1;
8302 programStats.moves_left = 1;
8303 programStats.nodes = 1;
8304 programStats.time = 1;
8305 programStats.got_only_move = 1;
8307 /* Not really, but we also use this member to
8308 mean "line isn't going to change" (Crafty
8309 isn't searching, so stats won't change) */
8310 programStats.line_is_book = 1;
8312 SendProgramStatsToFrontend( cps, &programStats );
8314 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8315 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8316 DisplayMove(currentMove - 1);
8319 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
8320 &time, &nodes, &plylev, &mvleft,
8321 &mvtot, mvname) >= 5) {
8322 /* The stat01: line is from Crafty (9.29+) in response
8323 to the "." command */
8324 programStats.seen_stat = 1;
8325 cps->maybeThinking = TRUE;
8327 if (programStats.got_only_move || !appData.periodicUpdates)
8330 programStats.depth = plylev;
8331 programStats.time = time;
8332 programStats.nodes = nodes;
8333 programStats.moves_left = mvleft;
8334 programStats.nr_moves = mvtot;
8335 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
8336 programStats.ok_to_send = 1;
8337 programStats.movelist[0] = '\0';
8339 SendProgramStatsToFrontend( cps, &programStats );
8343 } else if (strncmp(message,"++",2) == 0) {
8344 /* Crafty 9.29+ outputs this */
8345 programStats.got_fail = 2;
8348 } else if (strncmp(message,"--",2) == 0) {
8349 /* Crafty 9.29+ outputs this */
8350 programStats.got_fail = 1;
8353 } else if (thinkOutput[0] != NULLCHAR &&
8354 strncmp(message, " ", 4) == 0) {
8355 unsigned message_len;
8358 while (*p && *p == ' ') p++;
8360 message_len = strlen( p );
8362 /* [AS] Avoid buffer overflow */
8363 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
8364 strcat(thinkOutput, " ");
8365 strcat(thinkOutput, p);
8368 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
8369 strcat(programStats.movelist, " ");
8370 strcat(programStats.movelist, p);
8373 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8374 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8375 DisplayMove(currentMove - 1);
8383 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8384 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
8386 ChessProgramStats cpstats;
8388 if (plyext != ' ' && plyext != '\t') {
8392 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8393 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
8394 curscore = -curscore;
8397 cpstats.depth = plylev;
8398 cpstats.nodes = nodes;
8399 cpstats.time = time;
8400 cpstats.score = curscore;
8401 cpstats.got_only_move = 0;
8402 cpstats.movelist[0] = '\0';
8404 if (buf1[0] != NULLCHAR) {
8405 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
8408 cpstats.ok_to_send = 0;
8409 cpstats.line_is_book = 0;
8410 cpstats.nr_moves = 0;
8411 cpstats.moves_left = 0;
8413 SendProgramStatsToFrontend( cps, &cpstats );
8420 /* Parse a game score from the character string "game", and
8421 record it as the history of the current game. The game
8422 score is NOT assumed to start from the standard position.
8423 The display is not updated in any way.
8426 ParseGameHistory(game)
8430 int fromX, fromY, toX, toY, boardIndex;
8435 if (appData.debugMode)
8436 fprintf(debugFP, "Parsing game history: %s\n", game);
8438 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
8439 gameInfo.site = StrSave(appData.icsHost);
8440 gameInfo.date = PGNDate();
8441 gameInfo.round = StrSave("-");
8443 /* Parse out names of players */
8444 while (*game == ' ') game++;
8446 while (*game != ' ') *p++ = *game++;
8448 gameInfo.white = StrSave(buf);
8449 while (*game == ' ') game++;
8451 while (*game != ' ' && *game != '\n') *p++ = *game++;
8453 gameInfo.black = StrSave(buf);
8456 boardIndex = blackPlaysFirst ? 1 : 0;
8459 yyboardindex = boardIndex;
8460 moveType = (ChessMove) Myylex();
8462 case IllegalMove: /* maybe suicide chess, etc. */
8463 if (appData.debugMode) {
8464 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
8465 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8466 setbuf(debugFP, NULL);
8468 case WhitePromotion:
8469 case BlackPromotion:
8470 case WhiteNonPromotion:
8471 case BlackNonPromotion:
8473 case WhiteCapturesEnPassant:
8474 case BlackCapturesEnPassant:
8475 case WhiteKingSideCastle:
8476 case WhiteQueenSideCastle:
8477 case BlackKingSideCastle:
8478 case BlackQueenSideCastle:
8479 case WhiteKingSideCastleWild:
8480 case WhiteQueenSideCastleWild:
8481 case BlackKingSideCastleWild:
8482 case BlackQueenSideCastleWild:
8484 case WhiteHSideCastleFR:
8485 case WhiteASideCastleFR:
8486 case BlackHSideCastleFR:
8487 case BlackASideCastleFR:
8489 fromX = currentMoveString[0] - AAA;
8490 fromY = currentMoveString[1] - ONE;
8491 toX = currentMoveString[2] - AAA;
8492 toY = currentMoveString[3] - ONE;
8493 promoChar = currentMoveString[4];
8497 fromX = moveType == WhiteDrop ?
8498 (int) CharToPiece(ToUpper(currentMoveString[0])) :
8499 (int) CharToPiece(ToLower(currentMoveString[0]));
8501 toX = currentMoveString[2] - AAA;
8502 toY = currentMoveString[3] - ONE;
8503 promoChar = NULLCHAR;
8507 snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
8508 if (appData.debugMode) {
8509 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
8510 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8511 setbuf(debugFP, NULL);
8513 DisplayError(buf, 0);
8515 case ImpossibleMove:
8517 snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
8518 if (appData.debugMode) {
8519 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
8520 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8521 setbuf(debugFP, NULL);
8523 DisplayError(buf, 0);
8526 if (boardIndex < backwardMostMove) {
8527 /* Oops, gap. How did that happen? */
8528 DisplayError(_("Gap in move list"), 0);
8531 backwardMostMove = blackPlaysFirst ? 1 : 0;
8532 if (boardIndex > forwardMostMove) {
8533 forwardMostMove = boardIndex;
8537 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
8538 strcat(parseList[boardIndex-1], " ");
8539 strcat(parseList[boardIndex-1], yy_text);
8551 case GameUnfinished:
8552 if (gameMode == IcsExamining) {
8553 if (boardIndex < backwardMostMove) {
8554 /* Oops, gap. How did that happen? */
8557 backwardMostMove = blackPlaysFirst ? 1 : 0;
8560 gameInfo.result = moveType;
8561 p = strchr(yy_text, '{');
8562 if (p == NULL) p = strchr(yy_text, '(');
8565 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
8567 q = strchr(p, *p == '{' ? '}' : ')');
8568 if (q != NULL) *q = NULLCHAR;
8571 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
8572 gameInfo.resultDetails = StrSave(p);
8575 if (boardIndex >= forwardMostMove &&
8576 !(gameMode == IcsObserving && ics_gamenum == -1)) {
8577 backwardMostMove = blackPlaysFirst ? 1 : 0;
8580 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
8581 fromY, fromX, toY, toX, promoChar,
8582 parseList[boardIndex]);
8583 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
8584 /* currentMoveString is set as a side-effect of yylex */
8585 safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
8586 strcat(moveList[boardIndex], "\n");
8588 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
8589 switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
8595 if(gameInfo.variant != VariantShogi)
8596 strcat(parseList[boardIndex - 1], "+");
8600 strcat(parseList[boardIndex - 1], "#");
8607 /* Apply a move to the given board */
8609 ApplyMove(fromX, fromY, toX, toY, promoChar, board)
8610 int fromX, fromY, toX, toY;
8614 ChessSquare captured = board[toY][toX], piece, king; int p, oldEP = EP_NONE, berolina = 0;
8615 int promoRank = gameInfo.variant == VariantMakruk ? 3 : 1;
8617 /* [HGM] compute & store e.p. status and castling rights for new position */
8618 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
8620 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
8621 oldEP = (signed char)board[EP_STATUS];
8622 board[EP_STATUS] = EP_NONE;
8624 if( board[toY][toX] != EmptySquare )
8625 board[EP_STATUS] = EP_CAPTURE;
8627 if (fromY == DROP_RANK) {
8629 piece = board[toY][toX] = (ChessSquare) fromX;
8633 if( board[fromY][fromX] == WhiteLance || board[fromY][fromX] == BlackLance ) {
8634 if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi )
8635 board[EP_STATUS] = EP_PAWN_MOVE; // Lance is Pawn-like in most variants
8637 if( board[fromY][fromX] == WhitePawn ) {
8638 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
8639 board[EP_STATUS] = EP_PAWN_MOVE;
8641 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
8642 gameInfo.variant != VariantBerolina || toX < fromX)
8643 board[EP_STATUS] = toX | berolina;
8644 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
8645 gameInfo.variant != VariantBerolina || toX > fromX)
8646 board[EP_STATUS] = toX;
8649 if( board[fromY][fromX] == BlackPawn ) {
8650 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
8651 board[EP_STATUS] = EP_PAWN_MOVE;
8652 if( toY-fromY== -2) {
8653 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
8654 gameInfo.variant != VariantBerolina || toX < fromX)
8655 board[EP_STATUS] = toX | berolina;
8656 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
8657 gameInfo.variant != VariantBerolina || toX > fromX)
8658 board[EP_STATUS] = toX;
8662 for(i=0; i<nrCastlingRights; i++) {
8663 if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
8664 board[CASTLING][i] == toX && castlingRank[i] == toY
8665 ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
8668 if (fromX == toX && fromY == toY) return;
8670 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
8671 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
8672 if(gameInfo.variant == VariantKnightmate)
8673 king += (int) WhiteUnicorn - (int) WhiteKing;
8675 /* Code added by Tord: */
8676 /* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
8677 if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
8678 board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
8679 board[fromY][fromX] = EmptySquare;
8680 board[toY][toX] = EmptySquare;
8681 if((toX > fromX) != (piece == WhiteRook)) {
8682 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
8684 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
8686 } else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
8687 board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
8688 board[fromY][fromX] = EmptySquare;
8689 board[toY][toX] = EmptySquare;
8690 if((toX > fromX) != (piece == BlackRook)) {
8691 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
8693 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
8695 /* End of code added by Tord */
8697 } else if (board[fromY][fromX] == king
8698 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8699 && toY == fromY && toX > fromX+1) {
8700 board[fromY][fromX] = EmptySquare;
8701 board[toY][toX] = king;
8702 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
8703 board[fromY][BOARD_RGHT-1] = EmptySquare;
8704 } else if (board[fromY][fromX] == king
8705 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8706 && toY == fromY && toX < fromX-1) {
8707 board[fromY][fromX] = EmptySquare;
8708 board[toY][toX] = king;
8709 board[toY][toX+1] = board[fromY][BOARD_LEFT];
8710 board[fromY][BOARD_LEFT] = EmptySquare;
8711 } else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
8712 board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
8713 && toY >= BOARD_HEIGHT-promoRank
8715 /* white pawn promotion */
8716 board[toY][toX] = CharToPiece(ToUpper(promoChar));
8717 if (board[toY][toX] == EmptySquare) {
8718 board[toY][toX] = WhiteQueen;
8720 if(gameInfo.variant==VariantBughouse ||
8721 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
8722 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
8723 board[fromY][fromX] = EmptySquare;
8724 } else if ((fromY == BOARD_HEIGHT-4)
8726 && gameInfo.variant != VariantXiangqi
8727 && gameInfo.variant != VariantBerolina
8728 && (board[fromY][fromX] == WhitePawn)
8729 && (board[toY][toX] == EmptySquare)) {
8730 board[fromY][fromX] = EmptySquare;
8731 board[toY][toX] = WhitePawn;
8732 captured = board[toY - 1][toX];
8733 board[toY - 1][toX] = EmptySquare;
8734 } else if ((fromY == BOARD_HEIGHT-4)
8736 && gameInfo.variant == VariantBerolina
8737 && (board[fromY][fromX] == WhitePawn)
8738 && (board[toY][toX] == EmptySquare)) {
8739 board[fromY][fromX] = EmptySquare;
8740 board[toY][toX] = WhitePawn;
8741 if(oldEP & EP_BEROLIN_A) {
8742 captured = board[fromY][fromX-1];
8743 board[fromY][fromX-1] = EmptySquare;
8744 }else{ captured = board[fromY][fromX+1];
8745 board[fromY][fromX+1] = EmptySquare;
8747 } else if (board[fromY][fromX] == king
8748 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8749 && toY == fromY && toX > fromX+1) {
8750 board[fromY][fromX] = EmptySquare;
8751 board[toY][toX] = king;
8752 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
8753 board[fromY][BOARD_RGHT-1] = EmptySquare;
8754 } else if (board[fromY][fromX] == king
8755 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8756 && toY == fromY && toX < fromX-1) {
8757 board[fromY][fromX] = EmptySquare;
8758 board[toY][toX] = king;
8759 board[toY][toX+1] = board[fromY][BOARD_LEFT];
8760 board[fromY][BOARD_LEFT] = EmptySquare;
8761 } else if (fromY == 7 && fromX == 3
8762 && board[fromY][fromX] == BlackKing
8763 && toY == 7 && toX == 5) {
8764 board[fromY][fromX] = EmptySquare;
8765 board[toY][toX] = BlackKing;
8766 board[fromY][7] = EmptySquare;
8767 board[toY][4] = BlackRook;
8768 } else if (fromY == 7 && fromX == 3
8769 && board[fromY][fromX] == BlackKing
8770 && toY == 7 && toX == 1) {
8771 board[fromY][fromX] = EmptySquare;
8772 board[toY][toX] = BlackKing;
8773 board[fromY][0] = EmptySquare;
8774 board[toY][2] = BlackRook;
8775 } else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
8776 board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
8779 /* black pawn promotion */
8780 board[toY][toX] = CharToPiece(ToLower(promoChar));
8781 if (board[toY][toX] == EmptySquare) {
8782 board[toY][toX] = BlackQueen;
8784 if(gameInfo.variant==VariantBughouse ||
8785 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
8786 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
8787 board[fromY][fromX] = EmptySquare;
8788 } else if ((fromY == 3)
8790 && gameInfo.variant != VariantXiangqi
8791 && gameInfo.variant != VariantBerolina
8792 && (board[fromY][fromX] == BlackPawn)
8793 && (board[toY][toX] == EmptySquare)) {
8794 board[fromY][fromX] = EmptySquare;
8795 board[toY][toX] = BlackPawn;
8796 captured = board[toY + 1][toX];
8797 board[toY + 1][toX] = EmptySquare;
8798 } else if ((fromY == 3)
8800 && gameInfo.variant == VariantBerolina
8801 && (board[fromY][fromX] == BlackPawn)
8802 && (board[toY][toX] == EmptySquare)) {
8803 board[fromY][fromX] = EmptySquare;
8804 board[toY][toX] = BlackPawn;
8805 if(oldEP & EP_BEROLIN_A) {
8806 captured = board[fromY][fromX-1];
8807 board[fromY][fromX-1] = EmptySquare;
8808 }else{ captured = board[fromY][fromX+1];
8809 board[fromY][fromX+1] = EmptySquare;
8812 board[toY][toX] = board[fromY][fromX];
8813 board[fromY][fromX] = EmptySquare;
8817 if (gameInfo.holdingsWidth != 0) {
8819 /* !!A lot more code needs to be written to support holdings */
8820 /* [HGM] OK, so I have written it. Holdings are stored in the */
8821 /* penultimate board files, so they are automaticlly stored */
8822 /* in the game history. */
8823 if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
8824 && promoChar && piece != WhitePawn && piece != BlackPawn) {
8825 /* Delete from holdings, by decreasing count */
8826 /* and erasing image if necessary */
8827 p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
8828 if(p < (int) BlackPawn) { /* white drop */
8829 p -= (int)WhitePawn;
8830 p = PieceToNumber((ChessSquare)p);
8831 if(p >= gameInfo.holdingsSize) p = 0;
8832 if(--board[p][BOARD_WIDTH-2] <= 0)
8833 board[p][BOARD_WIDTH-1] = EmptySquare;
8834 if((int)board[p][BOARD_WIDTH-2] < 0)
8835 board[p][BOARD_WIDTH-2] = 0;
8836 } else { /* black drop */
8837 p -= (int)BlackPawn;
8838 p = PieceToNumber((ChessSquare)p);
8839 if(p >= gameInfo.holdingsSize) p = 0;
8840 if(--board[BOARD_HEIGHT-1-p][1] <= 0)
8841 board[BOARD_HEIGHT-1-p][0] = EmptySquare;
8842 if((int)board[BOARD_HEIGHT-1-p][1] < 0)
8843 board[BOARD_HEIGHT-1-p][1] = 0;
8846 if (captured != EmptySquare && gameInfo.holdingsSize > 0
8847 && gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess ) {
8848 /* [HGM] holdings: Add to holdings, if holdings exist */
8849 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
8850 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
8851 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
8854 if (p >= (int) BlackPawn) {
8855 p -= (int)BlackPawn;
8856 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
8857 /* in Shogi restore piece to its original first */
8858 captured = (ChessSquare) (DEMOTED captured);
8861 p = PieceToNumber((ChessSquare)p);
8862 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
8863 board[p][BOARD_WIDTH-2]++;
8864 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
8866 p -= (int)WhitePawn;
8867 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
8868 captured = (ChessSquare) (DEMOTED captured);
8871 p = PieceToNumber((ChessSquare)p);
8872 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
8873 board[BOARD_HEIGHT-1-p][1]++;
8874 board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
8877 } else if (gameInfo.variant == VariantAtomic) {
8878 if (captured != EmptySquare) {
8880 for (y = toY-1; y <= toY+1; y++) {
8881 for (x = toX-1; x <= toX+1; x++) {
8882 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
8883 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
8884 board[y][x] = EmptySquare;
8888 board[toY][toX] = EmptySquare;
8891 if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
8892 board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
8894 if(promoChar == '+') {
8895 /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite orinary Pawn promotion) */
8896 board[toY][toX] = (ChessSquare) (PROMOTED piece);
8897 } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
8898 board[toY][toX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
8900 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
8901 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
8902 // [HGM] superchess: take promotion piece out of holdings
8903 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
8904 if((int)piece < (int)BlackPawn) { // determine stm from piece color
8905 if(!--board[k][BOARD_WIDTH-2])
8906 board[k][BOARD_WIDTH-1] = EmptySquare;
8908 if(!--board[BOARD_HEIGHT-1-k][1])
8909 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
8915 /* Updates forwardMostMove */
8917 MakeMove(fromX, fromY, toX, toY, promoChar)
8918 int fromX, fromY, toX, toY;
8921 // forwardMostMove++; // [HGM] bare: moved downstream
8923 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
8924 int timeLeft; static int lastLoadFlag=0; int king, piece;
8925 piece = boards[forwardMostMove][fromY][fromX];
8926 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
8927 if(gameInfo.variant == VariantKnightmate)
8928 king += (int) WhiteUnicorn - (int) WhiteKing;
8929 if(forwardMostMove == 0) {
8931 fprintf(serverMoves, "%s;", second.tidy);
8932 fprintf(serverMoves, "%s;", first.tidy);
8933 if(!blackPlaysFirst)
8934 fprintf(serverMoves, "%s;", second.tidy);
8935 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
8936 lastLoadFlag = loadFlag;
8938 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
8939 // print castling suffix
8940 if( toY == fromY && piece == king ) {
8942 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
8944 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
8947 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
8948 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
8949 boards[forwardMostMove][toY][toX] == EmptySquare
8950 && fromX != toX && fromY != toY)
8951 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
8953 if(promoChar != NULLCHAR)
8954 fprintf(serverMoves, ":%c:%c%c", promoChar, AAA+toX, ONE+toY);
8956 fprintf(serverMoves, "/%d/%d",
8957 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
8958 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
8959 else timeLeft = blackTimeRemaining/1000;
8960 fprintf(serverMoves, "/%d", timeLeft);
8962 fflush(serverMoves);
8965 if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations
8966 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
8970 UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
8971 if (commentList[forwardMostMove+1] != NULL) {
8972 free(commentList[forwardMostMove+1]);
8973 commentList[forwardMostMove+1] = NULL;
8975 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
8976 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
8977 // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
8978 SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
8979 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
8980 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
8981 gameInfo.result = GameUnfinished;
8982 if (gameInfo.resultDetails != NULL) {
8983 free(gameInfo.resultDetails);
8984 gameInfo.resultDetails = NULL;
8986 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
8987 moveList[forwardMostMove - 1]);
8988 (void) CoordsToAlgebraic(boards[forwardMostMove - 1],
8989 PosFlags(forwardMostMove - 1),
8990 fromY, fromX, toY, toX, promoChar,
8991 parseList[forwardMostMove - 1]);
8992 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
8998 if(gameInfo.variant != VariantShogi)
8999 strcat(parseList[forwardMostMove - 1], "+");
9003 strcat(parseList[forwardMostMove - 1], "#");
9006 if (appData.debugMode) {
9007 fprintf(debugFP, "move: %s, parse: %s (%c)\n", moveList[forwardMostMove-1], parseList[forwardMostMove-1], moveList[forwardMostMove-1][4]);
9012 /* Updates currentMove if not pausing */
9014 ShowMove(fromX, fromY, toX, toY)
9016 int instant = (gameMode == PlayFromGameFile) ?
9017 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
9018 if(appData.noGUI) return;
9019 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
9021 if (forwardMostMove == currentMove + 1) {
9022 AnimateMove(boards[forwardMostMove - 1],
9023 fromX, fromY, toX, toY);
9025 if (appData.highlightLastMove) {
9026 SetHighlights(fromX, fromY, toX, toY);
9029 currentMove = forwardMostMove;
9032 if (instant) return;
9034 DisplayMove(currentMove - 1);
9035 DrawPosition(FALSE, boards[currentMove]);
9036 DisplayBothClocks();
9037 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
9040 void SendEgtPath(ChessProgramState *cps)
9041 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
9042 char buf[MSG_SIZ], name[MSG_SIZ], *p;
9044 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
9047 char c, *q = name+1, *r, *s;
9049 name[0] = ','; // extract next format name from feature and copy with prefixed ','
9050 while(*p && *p != ',') *q++ = *p++;
9052 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
9053 strcmp(name, ",nalimov:") == 0 ) {
9054 // take nalimov path from the menu-changeable option first, if it is defined
9055 snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
9056 SendToProgram(buf,cps); // send egtbpath command for nalimov
9058 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
9059 (s = StrStr(appData.egtFormats, name)) != NULL) {
9060 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
9061 s = r = StrStr(s, ":") + 1; // beginning of path info
9062 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
9063 c = *r; *r = 0; // temporarily null-terminate path info
9064 *--q = 0; // strip of trailig ':' from name
9065 snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
9067 SendToProgram(buf,cps); // send egtbpath command for this format
9069 if(*p == ',') p++; // read away comma to position for next format name
9074 InitChessProgram(cps, setup)
9075 ChessProgramState *cps;
9076 int setup; /* [HGM] needed to setup FRC opening position */
9078 char buf[MSG_SIZ], b[MSG_SIZ]; int overruled;
9079 if (appData.noChessProgram) return;
9080 hintRequested = FALSE;
9081 bookRequested = FALSE;
9083 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
9084 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
9085 if(cps->memSize) { /* [HGM] memory */
9086 snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
9087 SendToProgram(buf, cps);
9089 SendEgtPath(cps); /* [HGM] EGT */
9090 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
9091 snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
9092 SendToProgram(buf, cps);
9095 SendToProgram(cps->initString, cps);
9096 if (gameInfo.variant != VariantNormal &&
9097 gameInfo.variant != VariantLoadable
9098 /* [HGM] also send variant if board size non-standard */
9099 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0
9101 char *v = VariantName(gameInfo.variant);
9102 if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) {
9103 /* [HGM] in protocol 1 we have to assume all variants valid */
9104 snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), v, cps->tidy);
9105 DisplayFatalError(buf, 0, 1);
9109 /* [HGM] make prefix for non-standard board size. Awkward testing... */
9110 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9111 if( gameInfo.variant == VariantXiangqi )
9112 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 0;
9113 if( gameInfo.variant == VariantShogi )
9114 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 9 || gameInfo.holdingsSize != 7;
9115 if( gameInfo.variant == VariantBughouse || gameInfo.variant == VariantCrazyhouse )
9116 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 5;
9117 if( gameInfo.variant == VariantCapablanca || gameInfo.variant == VariantCapaRandom ||
9118 gameInfo.variant == VariantGothic || gameInfo.variant == VariantFalcon || gameInfo.variant == VariantJanus )
9119 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9120 if( gameInfo.variant == VariantCourier )
9121 overruled = gameInfo.boardWidth != 12 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9122 if( gameInfo.variant == VariantSuper )
9123 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9124 if( gameInfo.variant == VariantGreat )
9125 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9126 if( gameInfo.variant == VariantSChess )
9127 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 7;
9130 snprintf(b, MSG_SIZ, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
9131 gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
9132 /* [HGM] varsize: try first if this defiant size variant is specifically known */
9133 if(StrStr(cps->variants, b) == NULL) {
9134 // specific sized variant not known, check if general sizing allowed
9135 if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best
9136 if(StrStr(cps->variants, "boardsize") == NULL) {
9137 snprintf(buf, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
9138 gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy);
9139 DisplayFatalError(buf, 0, 1);
9142 /* [HGM] here we really should compare with the maximum supported board size */
9145 } else snprintf(b, MSG_SIZ,"%s", VariantName(gameInfo.variant));
9146 snprintf(buf, MSG_SIZ, "variant %s\n", b);
9147 SendToProgram(buf, cps);
9149 currentlyInitializedVariant = gameInfo.variant;
9151 /* [HGM] send opening position in FRC to first engine */
9153 SendToProgram("force\n", cps);
9155 /* engine is now in force mode! Set flag to wake it up after first move. */
9156 setboardSpoiledMachineBlack = 1;
9160 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
9161 SendToProgram(buf, cps);
9163 cps->maybeThinking = FALSE;
9164 cps->offeredDraw = 0;
9165 if (!appData.icsActive) {
9166 SendTimeControl(cps, movesPerSession, timeControl,
9167 timeIncrement, appData.searchDepth,
9170 if (appData.showThinking
9171 // [HGM] thinking: four options require thinking output to be sent
9172 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
9174 SendToProgram("post\n", cps);
9176 SendToProgram("hard\n", cps);
9177 if (!appData.ponderNextMove) {
9178 /* Warning: "easy" is a toggle in GNU Chess, so don't send
9179 it without being sure what state we are in first. "hard"
9180 is not a toggle, so that one is OK.
9182 SendToProgram("easy\n", cps);
9185 snprintf(buf, MSG_SIZ, "ping %d\n", ++cps->lastPing);
9186 SendToProgram(buf, cps);
9188 cps->initDone = TRUE;
9193 StartChessProgram(cps)
9194 ChessProgramState *cps;
9199 if (appData.noChessProgram) return;
9200 cps->initDone = FALSE;
9202 if (strcmp(cps->host, "localhost") == 0) {
9203 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
9204 } else if (*appData.remoteShell == NULLCHAR) {
9205 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
9207 if (*appData.remoteUser == NULLCHAR) {
9208 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
9211 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
9212 cps->host, appData.remoteUser, cps->program);
9214 err = StartChildProcess(buf, "", &cps->pr);
9218 snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
9219 DisplayFatalError(buf, err, 1);
9225 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
9226 if (cps->protocolVersion > 1) {
9227 snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
9228 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
9229 cps->comboCnt = 0; // and values of combo boxes
9230 SendToProgram(buf, cps);
9232 SendToProgram("xboard\n", cps);
9238 TwoMachinesEventIfReady P((void))
9240 if (first.lastPing != first.lastPong) {
9241 DisplayMessage("", _("Waiting for first chess program"));
9242 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9245 if (second.lastPing != second.lastPong) {
9246 DisplayMessage("", _("Waiting for second chess program"));
9247 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9255 NextMatchGame P((void))
9257 int index; /* [HGM] autoinc: step load index during match */
9259 if (*appData.loadGameFile != NULLCHAR) {
9260 index = appData.loadGameIndex;
9261 if(index < 0) { // [HGM] autoinc
9262 lastIndex = index = (index == -2 && first.twoMachinesColor[0] == 'b') ? lastIndex : lastIndex+1;
9263 if(appData.rewindIndex > 0 && index > appData.rewindIndex) lastIndex = index = 1;
9265 LoadGameFromFile(appData.loadGameFile,
9267 appData.loadGameFile, FALSE);
9268 } else if (*appData.loadPositionFile != NULLCHAR) {
9269 index = appData.loadPositionIndex;
9270 if(index < 0) { // [HGM] autoinc
9271 lastIndex = index = (index == -2 && first.twoMachinesColor[0] == 'b') ? lastIndex : lastIndex+1;
9272 if(appData.rewindIndex > 0 && index > appData.rewindIndex) lastIndex = index = 1;
9274 LoadPositionFromFile(appData.loadPositionFile,
9276 appData.loadPositionFile);
9278 TwoMachinesEventIfReady();
9281 void UserAdjudicationEvent( int result )
9283 ChessMove gameResult = GameIsDrawn;
9286 gameResult = WhiteWins;
9288 else if( result < 0 ) {
9289 gameResult = BlackWins;
9292 if( gameMode == TwoMachinesPlay ) {
9293 GameEnds( gameResult, "User adjudication", GE_XBOARD );
9298 // [HGM] save: calculate checksum of game to make games easily identifiable
9299 int StringCheckSum(char *s)
9302 if(s==NULL) return 0;
9303 while(*s) i = i*259 + *s++;
9310 for(i=backwardMostMove; i<forwardMostMove; i++) {
9311 sum += pvInfoList[i].depth;
9312 sum += StringCheckSum(parseList[i]);
9313 sum += StringCheckSum(commentList[i]);
9316 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
9317 return sum + StringCheckSum(commentList[i]);
9318 } // end of save patch
9321 GameEnds(result, resultDetails, whosays)
9323 char *resultDetails;
9326 GameMode nextGameMode;
9328 char buf[MSG_SIZ], popupRequested = 0;
9330 if(endingGame) return; /* [HGM] crash: forbid recursion */
9332 if(twoBoards) { // [HGM] dual: switch back to one board
9333 twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
9334 DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
9336 if (appData.debugMode) {
9337 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
9338 result, resultDetails ? resultDetails : "(null)", whosays);
9341 fromX = fromY = -1; // [HGM] abort any move the user is entering.
9343 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
9344 /* If we are playing on ICS, the server decides when the
9345 game is over, but the engine can offer to draw, claim
9349 if (appData.zippyPlay && first.initDone) {
9350 if (result == GameIsDrawn) {
9351 /* In case draw still needs to be claimed */
9352 SendToICS(ics_prefix);
9353 SendToICS("draw\n");
9354 } else if (StrCaseStr(resultDetails, "resign")) {
9355 SendToICS(ics_prefix);
9356 SendToICS("resign\n");
9360 endingGame = 0; /* [HGM] crash */
9364 /* If we're loading the game from a file, stop */
9365 if (whosays == GE_FILE) {
9366 (void) StopLoadGameTimer();
9370 /* Cancel draw offers */
9371 first.offeredDraw = second.offeredDraw = 0;
9373 /* If this is an ICS game, only ICS can really say it's done;
9374 if not, anyone can. */
9375 isIcsGame = (gameMode == IcsPlayingWhite ||
9376 gameMode == IcsPlayingBlack ||
9377 gameMode == IcsObserving ||
9378 gameMode == IcsExamining);
9380 if (!isIcsGame || whosays == GE_ICS) {
9381 /* OK -- not an ICS game, or ICS said it was done */
9383 if (!isIcsGame && !appData.noChessProgram)
9384 SetUserThinkingEnables();
9386 /* [HGM] if a machine claims the game end we verify this claim */
9387 if(gameMode == TwoMachinesPlay && appData.testClaims) {
9388 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
9390 ChessMove trueResult = (ChessMove) -1;
9392 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
9393 first.twoMachinesColor[0] :
9394 second.twoMachinesColor[0] ;
9396 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
9397 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
9398 /* [HGM] verify: engine mate claims accepted if they were flagged */
9399 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
9401 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
9402 /* [HGM] verify: engine mate claims accepted if they were flagged */
9403 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
9405 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
9406 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
9409 // now verify win claims, but not in drop games, as we don't understand those yet
9410 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
9411 || gameInfo.variant == VariantGreat) &&
9412 (result == WhiteWins && claimer == 'w' ||
9413 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
9414 if (appData.debugMode) {
9415 fprintf(debugFP, "result=%d sp=%d move=%d\n",
9416 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
9418 if(result != trueResult) {
9419 snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
9420 result = claimer == 'w' ? BlackWins : WhiteWins;
9421 resultDetails = buf;
9424 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
9425 && (forwardMostMove <= backwardMostMove ||
9426 (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
9427 (claimer=='b')==(forwardMostMove&1))
9429 /* [HGM] verify: draws that were not flagged are false claims */
9430 snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
9431 result = claimer == 'w' ? BlackWins : WhiteWins;
9432 resultDetails = buf;
9434 /* (Claiming a loss is accepted no questions asked!) */
9436 /* [HGM] bare: don't allow bare King to win */
9437 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
9438 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
9439 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
9440 && result != GameIsDrawn)
9441 { int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
9442 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
9443 int p = (signed char)boards[forwardMostMove][i][j] - color;
9444 if(p >= 0 && p <= (int)WhiteKing) k++;
9446 if (appData.debugMode) {
9447 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
9448 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
9451 result = GameIsDrawn;
9452 snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
9453 resultDetails = buf;
9459 if(serverMoves != NULL && !loadFlag) { char c = '=';
9460 if(result==WhiteWins) c = '+';
9461 if(result==BlackWins) c = '-';
9462 if(resultDetails != NULL)
9463 fprintf(serverMoves, ";%c;%s\n", c, resultDetails);
9465 if (resultDetails != NULL) {
9466 gameInfo.result = result;
9467 gameInfo.resultDetails = StrSave(resultDetails);
9469 /* display last move only if game was not loaded from file */
9470 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
9471 DisplayMove(currentMove - 1);
9473 if (forwardMostMove != 0) {
9474 if (gameMode != PlayFromGameFile && gameMode != EditGame
9475 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
9477 if (*appData.saveGameFile != NULLCHAR) {
9478 SaveGameToFile(appData.saveGameFile, TRUE);
9479 } else if (appData.autoSaveGames) {
9482 if (*appData.savePositionFile != NULLCHAR) {
9483 SavePositionToFile(appData.savePositionFile);
9488 /* Tell program how game ended in case it is learning */
9489 /* [HGM] Moved this to after saving the PGN, just in case */
9490 /* engine died and we got here through time loss. In that */
9491 /* case we will get a fatal error writing the pipe, which */
9492 /* would otherwise lose us the PGN. */
9493 /* [HGM] crash: not needed anymore, but doesn't hurt; */
9494 /* output during GameEnds should never be fatal anymore */
9495 if (gameMode == MachinePlaysWhite ||
9496 gameMode == MachinePlaysBlack ||
9497 gameMode == TwoMachinesPlay ||
9498 gameMode == IcsPlayingWhite ||
9499 gameMode == IcsPlayingBlack ||
9500 gameMode == BeginningOfGame) {
9502 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
9504 if (first.pr != NoProc) {
9505 SendToProgram(buf, &first);
9507 if (second.pr != NoProc &&
9508 gameMode == TwoMachinesPlay) {
9509 SendToProgram(buf, &second);
9514 if (appData.icsActive) {
9515 if (appData.quietPlay &&
9516 (gameMode == IcsPlayingWhite ||
9517 gameMode == IcsPlayingBlack)) {
9518 SendToICS(ics_prefix);
9519 SendToICS("set shout 1\n");
9521 nextGameMode = IcsIdle;
9522 ics_user_moved = FALSE;
9523 /* clean up premove. It's ugly when the game has ended and the
9524 * premove highlights are still on the board.
9528 ClearPremoveHighlights();
9529 DrawPosition(FALSE, boards[currentMove]);
9531 if (whosays == GE_ICS) {
9534 if (gameMode == IcsPlayingWhite)
9536 else if(gameMode == IcsPlayingBlack)
9540 if (gameMode == IcsPlayingBlack)
9542 else if(gameMode == IcsPlayingWhite)
9549 PlayIcsUnfinishedSound();
9552 } else if (gameMode == EditGame ||
9553 gameMode == PlayFromGameFile ||
9554 gameMode == AnalyzeMode ||
9555 gameMode == AnalyzeFile) {
9556 nextGameMode = gameMode;
9558 nextGameMode = EndOfGame;
9563 nextGameMode = gameMode;
9566 if (appData.noChessProgram) {
9567 gameMode = nextGameMode;
9569 endingGame = 0; /* [HGM] crash */
9574 /* Put first chess program into idle state */
9575 if (first.pr != NoProc &&
9576 (gameMode == MachinePlaysWhite ||
9577 gameMode == MachinePlaysBlack ||
9578 gameMode == TwoMachinesPlay ||
9579 gameMode == IcsPlayingWhite ||
9580 gameMode == IcsPlayingBlack ||
9581 gameMode == BeginningOfGame)) {
9582 SendToProgram("force\n", &first);
9583 if (first.usePing) {
9585 snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
9586 SendToProgram(buf, &first);
9589 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
9590 /* Kill off first chess program */
9591 if (first.isr != NULL)
9592 RemoveInputSource(first.isr);
9595 if (first.pr != NoProc) {
9597 DoSleep( appData.delayBeforeQuit );
9598 SendToProgram("quit\n", &first);
9599 DoSleep( appData.delayAfterQuit );
9600 DestroyChildProcess(first.pr, first.useSigterm);
9605 /* Put second chess program into idle state */
9606 if (second.pr != NoProc &&
9607 gameMode == TwoMachinesPlay) {
9608 SendToProgram("force\n", &second);
9609 if (second.usePing) {
9611 snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
9612 SendToProgram(buf, &second);
9615 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
9616 /* Kill off second chess program */
9617 if (second.isr != NULL)
9618 RemoveInputSource(second.isr);
9621 if (second.pr != NoProc) {
9622 DoSleep( appData.delayBeforeQuit );
9623 SendToProgram("quit\n", &second);
9624 DoSleep( appData.delayAfterQuit );
9625 DestroyChildProcess(second.pr, second.useSigterm);
9630 if (matchMode && gameMode == TwoMachinesPlay) {
9633 if (first.twoMachinesColor[0] == 'w') {
9640 if (first.twoMachinesColor[0] == 'b') {
9649 if (matchGame < appData.matchGames) {
9651 if(appData.sameColorGames <= 1) { /* [HGM] alternate: suppress color swap */
9652 tmp = first.twoMachinesColor;
9653 first.twoMachinesColor = second.twoMachinesColor;
9654 second.twoMachinesColor = tmp;
9656 gameMode = nextGameMode;
9658 if(appData.matchPause>10000 || appData.matchPause<10)
9659 appData.matchPause = 10000; /* [HGM] make pause adjustable */
9660 ScheduleDelayedEvent(NextMatchGame, appData.matchPause);
9661 endingGame = 0; /* [HGM] crash */
9664 gameMode = nextGameMode;
9665 snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
9666 first.tidy, second.tidy,
9667 first.matchWins, second.matchWins,
9668 appData.matchGames - (first.matchWins + second.matchWins));
9669 popupRequested++; // [HGM] crash: postpone to after resetting endingGame
9670 if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
9671 first.twoMachinesColor = "black\n";
9672 second.twoMachinesColor = "white\n";
9674 first.twoMachinesColor = "white\n";
9675 second.twoMachinesColor = "black\n";
9679 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
9680 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
9682 gameMode = nextGameMode;
9684 endingGame = 0; /* [HGM] crash */
9685 if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
9686 if(matchMode == TRUE) DisplayFatalError(buf, 0, 0); else {
9687 matchMode = FALSE; appData.matchGames = matchGame = 0;
9693 /* Assumes program was just initialized (initString sent).
9694 Leaves program in force mode. */
9696 FeedMovesToProgram(cps, upto)
9697 ChessProgramState *cps;
9702 if (appData.debugMode)
9703 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
9704 startedFromSetupPosition ? "position and " : "",
9705 backwardMostMove, upto, cps->which);
9706 if(currentlyInitializedVariant != gameInfo.variant) {
9708 // [HGM] variantswitch: make engine aware of new variant
9709 if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL)
9710 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
9711 snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
9712 SendToProgram(buf, cps);
9713 currentlyInitializedVariant = gameInfo.variant;
9715 SendToProgram("force\n", cps);
9716 if (startedFromSetupPosition) {
9717 SendBoard(cps, backwardMostMove);
9718 if (appData.debugMode) {
9719 fprintf(debugFP, "feedMoves\n");
9722 for (i = backwardMostMove; i < upto; i++) {
9723 SendMoveToProgram(i, cps);
9729 ResurrectChessProgram()
9731 /* The chess program may have exited.
9732 If so, restart it and feed it all the moves made so far. */
9734 if (appData.noChessProgram || first.pr != NoProc) return;
9736 StartChessProgram(&first);
9737 InitChessProgram(&first, FALSE);
9738 FeedMovesToProgram(&first, currentMove);
9740 if (!first.sendTime) {
9741 /* can't tell gnuchess what its clock should read,
9742 so we bow to its notion. */
9744 timeRemaining[0][currentMove] = whiteTimeRemaining;
9745 timeRemaining[1][currentMove] = blackTimeRemaining;
9748 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
9749 appData.icsEngineAnalyze) && first.analysisSupport) {
9750 SendToProgram("analyze\n", &first);
9751 first.analyzing = TRUE;
9764 if (appData.debugMode) {
9765 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
9766 redraw, init, gameMode);
9768 CleanupTail(); // [HGM] vari: delete any stored variations
9769 pausing = pauseExamInvalid = FALSE;
9770 startedFromSetupPosition = blackPlaysFirst = FALSE;
9772 whiteFlag = blackFlag = FALSE;
9773 userOfferedDraw = FALSE;
9774 hintRequested = bookRequested = FALSE;
9775 first.maybeThinking = FALSE;
9776 second.maybeThinking = FALSE;
9777 first.bookSuspend = FALSE; // [HGM] book
9778 second.bookSuspend = FALSE;
9779 thinkOutput[0] = NULLCHAR;
9780 lastHint[0] = NULLCHAR;
9781 ClearGameInfo(&gameInfo);
9782 gameInfo.variant = StringToVariant(appData.variant);
9783 ics_user_moved = ics_clock_paused = FALSE;
9784 ics_getting_history = H_FALSE;
9786 white_holding[0] = black_holding[0] = NULLCHAR;
9787 ClearProgramStats();
9788 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
9792 flipView = appData.flipView;
9793 ClearPremoveHighlights();
9795 alarmSounded = FALSE;
9797 GameEnds(EndOfFile, NULL, GE_PLAYER);
9798 if(appData.serverMovesName != NULL) {
9799 /* [HGM] prepare to make moves file for broadcasting */
9800 clock_t t = clock();
9801 if(serverMoves != NULL) fclose(serverMoves);
9802 serverMoves = fopen(appData.serverMovesName, "r");
9803 if(serverMoves != NULL) {
9804 fclose(serverMoves);
9805 /* delay 15 sec before overwriting, so all clients can see end */
9806 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
9808 serverMoves = fopen(appData.serverMovesName, "w");
9812 gameMode = BeginningOfGame;
9814 if(appData.icsActive) gameInfo.variant = VariantNormal;
9815 currentMove = forwardMostMove = backwardMostMove = 0;
9816 InitPosition(redraw);
9817 for (i = 0; i < MAX_MOVES; i++) {
9818 if (commentList[i] != NULL) {
9819 free(commentList[i]);
9820 commentList[i] = NULL;
9824 timeRemaining[0][0] = whiteTimeRemaining;
9825 timeRemaining[1][0] = blackTimeRemaining;
9826 if (first.pr == NULL) {
9827 StartChessProgram(&first);
9830 InitChessProgram(&first, startedFromSetupPosition);
9833 DisplayMessage("", "");
9834 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
9835 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
9842 if (!AutoPlayOneMove())
9844 if (matchMode || appData.timeDelay == 0)
9846 if (appData.timeDelay < 0)
9848 StartLoadGameTimer((long)(1000.0 * appData.timeDelay));
9857 int fromX, fromY, toX, toY;
9859 if (appData.debugMode) {
9860 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
9863 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
9866 if (gameMode == AnalyzeFile && currentMove > backwardMostMove) {
9867 pvInfoList[currentMove].depth = programStats.depth;
9868 pvInfoList[currentMove].score = programStats.score;
9869 pvInfoList[currentMove].time = 0;
9870 if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
9873 if (currentMove >= forwardMostMove) {
9874 if(gameMode == AnalyzeFile) { ExitAnalyzeMode(); SendToProgram("force\n", &first); }
9875 gameMode = EditGame;
9878 /* [AS] Clear current move marker at the end of a game */
9879 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
9884 toX = moveList[currentMove][2] - AAA;
9885 toY = moveList[currentMove][3] - ONE;
9887 if (moveList[currentMove][1] == '@') {
9888 if (appData.highlightLastMove) {
9889 SetHighlights(-1, -1, toX, toY);
9892 fromX = moveList[currentMove][0] - AAA;
9893 fromY = moveList[currentMove][1] - ONE;
9895 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
9897 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
9899 if (appData.highlightLastMove) {
9900 SetHighlights(fromX, fromY, toX, toY);
9903 DisplayMove(currentMove);
9904 SendMoveToProgram(currentMove++, &first);
9905 DisplayBothClocks();
9906 DrawPosition(FALSE, boards[currentMove]);
9907 // [HGM] PV info: always display, routine tests if empty
9908 DisplayComment(currentMove - 1, commentList[currentMove]);
9914 LoadGameOneMove(readAhead)
9915 ChessMove readAhead;
9917 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
9918 char promoChar = NULLCHAR;
9923 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
9924 gameMode != AnalyzeMode && gameMode != Training) {
9929 yyboardindex = forwardMostMove;
9930 if (readAhead != EndOfFile) {
9931 moveType = readAhead;
9933 if (gameFileFP == NULL)
9935 moveType = (ChessMove) Myylex();
9941 if (appData.debugMode)
9942 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
9945 /* append the comment but don't display it */
9946 AppendComment(currentMove, p, FALSE);
9949 case WhiteCapturesEnPassant:
9950 case BlackCapturesEnPassant:
9951 case WhitePromotion:
9952 case BlackPromotion:
9953 case WhiteNonPromotion:
9954 case BlackNonPromotion:
9956 case WhiteKingSideCastle:
9957 case WhiteQueenSideCastle:
9958 case BlackKingSideCastle:
9959 case BlackQueenSideCastle:
9960 case WhiteKingSideCastleWild:
9961 case WhiteQueenSideCastleWild:
9962 case BlackKingSideCastleWild:
9963 case BlackQueenSideCastleWild:
9965 case WhiteHSideCastleFR:
9966 case WhiteASideCastleFR:
9967 case BlackHSideCastleFR:
9968 case BlackASideCastleFR:
9970 if (appData.debugMode)
9971 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
9972 fromX = currentMoveString[0] - AAA;
9973 fromY = currentMoveString[1] - ONE;
9974 toX = currentMoveString[2] - AAA;
9975 toY = currentMoveString[3] - ONE;
9976 promoChar = currentMoveString[4];
9981 if (appData.debugMode)
9982 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
9983 fromX = moveType == WhiteDrop ?
9984 (int) CharToPiece(ToUpper(currentMoveString[0])) :
9985 (int) CharToPiece(ToLower(currentMoveString[0]));
9987 toX = currentMoveString[2] - AAA;
9988 toY = currentMoveString[3] - ONE;
9994 case GameUnfinished:
9995 if (appData.debugMode)
9996 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
9997 p = strchr(yy_text, '{');
9998 if (p == NULL) p = strchr(yy_text, '(');
10001 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
10003 q = strchr(p, *p == '{' ? '}' : ')');
10004 if (q != NULL) *q = NULLCHAR;
10007 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
10008 GameEnds(moveType, p, GE_FILE);
10010 if (cmailMsgLoaded) {
10012 flipView = WhiteOnMove(currentMove);
10013 if (moveType == GameUnfinished) flipView = !flipView;
10014 if (appData.debugMode)
10015 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
10020 if (appData.debugMode)
10021 fprintf(debugFP, "Parser hit end of file\n");
10022 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
10028 if (WhiteOnMove(currentMove)) {
10029 GameEnds(BlackWins, "Black mates", GE_FILE);
10031 GameEnds(WhiteWins, "White mates", GE_FILE);
10035 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
10041 case MoveNumberOne:
10042 if (lastLoadGameStart == GNUChessGame) {
10043 /* GNUChessGames have numbers, but they aren't move numbers */
10044 if (appData.debugMode)
10045 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
10046 yy_text, (int) moveType);
10047 return LoadGameOneMove(EndOfFile); /* tail recursion */
10049 /* else fall thru */
10054 /* Reached start of next game in file */
10055 if (appData.debugMode)
10056 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
10057 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
10063 if (WhiteOnMove(currentMove)) {
10064 GameEnds(BlackWins, "Black mates", GE_FILE);
10066 GameEnds(WhiteWins, "White mates", GE_FILE);
10070 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
10076 case PositionDiagram: /* should not happen; ignore */
10077 case ElapsedTime: /* ignore */
10078 case NAG: /* ignore */
10079 if (appData.debugMode)
10080 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
10081 yy_text, (int) moveType);
10082 return LoadGameOneMove(EndOfFile); /* tail recursion */
10085 if (appData.testLegality) {
10086 if (appData.debugMode)
10087 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
10088 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
10089 (forwardMostMove / 2) + 1,
10090 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10091 DisplayError(move, 0);
10094 if (appData.debugMode)
10095 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
10096 yy_text, currentMoveString);
10097 fromX = currentMoveString[0] - AAA;
10098 fromY = currentMoveString[1] - ONE;
10099 toX = currentMoveString[2] - AAA;
10100 toY = currentMoveString[3] - ONE;
10101 promoChar = currentMoveString[4];
10105 case AmbiguousMove:
10106 if (appData.debugMode)
10107 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
10108 snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
10109 (forwardMostMove / 2) + 1,
10110 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10111 DisplayError(move, 0);
10116 case ImpossibleMove:
10117 if (appData.debugMode)
10118 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
10119 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
10120 (forwardMostMove / 2) + 1,
10121 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10122 DisplayError(move, 0);
10128 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
10129 DrawPosition(FALSE, boards[currentMove]);
10130 DisplayBothClocks();
10131 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
10132 DisplayComment(currentMove - 1, commentList[currentMove]);
10134 (void) StopLoadGameTimer();
10136 cmailOldMove = forwardMostMove;
10139 /* currentMoveString is set as a side-effect of yylex */
10141 thinkOutput[0] = NULLCHAR;
10142 MakeMove(fromX, fromY, toX, toY, promoChar);
10143 currentMove = forwardMostMove;
10148 /* Load the nth game from the given file */
10150 LoadGameFromFile(filename, n, title, useList)
10154 /*Boolean*/ int useList;
10159 if (strcmp(filename, "-") == 0) {
10163 f = fopen(filename, "rb");
10165 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10166 DisplayError(buf, errno);
10170 if (fseek(f, 0, 0) == -1) {
10171 /* f is not seekable; probably a pipe */
10174 if (useList && n == 0) {
10175 int error = GameListBuild(f);
10177 DisplayError(_("Cannot build game list"), error);
10178 } else if (!ListEmpty(&gameList) &&
10179 ((ListGame *) gameList.tailPred)->number > 1) {
10180 GameListPopUp(f, title);
10187 return LoadGame(f, n, title, FALSE);
10192 MakeRegisteredMove()
10194 int fromX, fromY, toX, toY;
10196 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
10197 switch (cmailMoveType[lastLoadGameNumber - 1]) {
10200 if (appData.debugMode)
10201 fprintf(debugFP, "Restoring %s for game %d\n",
10202 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
10204 thinkOutput[0] = NULLCHAR;
10205 safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
10206 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
10207 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
10208 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
10209 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
10210 promoChar = cmailMove[lastLoadGameNumber - 1][4];
10211 MakeMove(fromX, fromY, toX, toY, promoChar);
10212 ShowMove(fromX, fromY, toX, toY);
10214 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
10221 if (WhiteOnMove(currentMove)) {
10222 GameEnds(BlackWins, "Black mates", GE_PLAYER);
10224 GameEnds(WhiteWins, "White mates", GE_PLAYER);
10229 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
10236 if (WhiteOnMove(currentMove)) {
10237 GameEnds(BlackWins, "White resigns", GE_PLAYER);
10239 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
10244 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
10255 /* Wrapper around LoadGame for use when a Cmail message is loaded */
10257 CmailLoadGame(f, gameNumber, title, useList)
10265 if (gameNumber > nCmailGames) {
10266 DisplayError(_("No more games in this message"), 0);
10269 if (f == lastLoadGameFP) {
10270 int offset = gameNumber - lastLoadGameNumber;
10272 cmailMsg[0] = NULLCHAR;
10273 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
10274 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
10275 nCmailMovesRegistered--;
10277 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
10278 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
10279 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
10282 if (! RegisterMove()) return FALSE;
10286 retVal = LoadGame(f, gameNumber, title, useList);
10288 /* Make move registered during previous look at this game, if any */
10289 MakeRegisteredMove();
10291 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
10292 commentList[currentMove]
10293 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
10294 DisplayComment(currentMove - 1, commentList[currentMove]);
10300 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
10305 int gameNumber = lastLoadGameNumber + offset;
10306 if (lastLoadGameFP == NULL) {
10307 DisplayError(_("No game has been loaded yet"), 0);
10310 if (gameNumber <= 0) {
10311 DisplayError(_("Can't back up any further"), 0);
10314 if (cmailMsgLoaded) {
10315 return CmailLoadGame(lastLoadGameFP, gameNumber,
10316 lastLoadGameTitle, lastLoadGameUseList);
10318 return LoadGame(lastLoadGameFP, gameNumber,
10319 lastLoadGameTitle, lastLoadGameUseList);
10325 /* Load the nth game from open file f */
10327 LoadGame(f, gameNumber, title, useList)
10335 int gn = gameNumber;
10336 ListGame *lg = NULL;
10337 int numPGNTags = 0;
10339 GameMode oldGameMode;
10340 VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
10342 if (appData.debugMode)
10343 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
10345 if (gameMode == Training )
10346 SetTrainingModeOff();
10348 oldGameMode = gameMode;
10349 if (gameMode != BeginningOfGame) {
10350 Reset(FALSE, TRUE);
10354 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
10355 fclose(lastLoadGameFP);
10359 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
10362 fseek(f, lg->offset, 0);
10363 GameListHighlight(gameNumber);
10367 DisplayError(_("Game number out of range"), 0);
10372 if (fseek(f, 0, 0) == -1) {
10373 if (f == lastLoadGameFP ?
10374 gameNumber == lastLoadGameNumber + 1 :
10378 DisplayError(_("Can't seek on game file"), 0);
10383 lastLoadGameFP = f;
10384 lastLoadGameNumber = gameNumber;
10385 safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
10386 lastLoadGameUseList = useList;
10390 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
10391 snprintf(buf, sizeof(buf), "%s vs. %s", lg->gameInfo.white,
10392 lg->gameInfo.black);
10394 } else if (*title != NULLCHAR) {
10395 if (gameNumber > 1) {
10396 snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
10399 DisplayTitle(title);
10403 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
10404 gameMode = PlayFromGameFile;
10408 currentMove = forwardMostMove = backwardMostMove = 0;
10409 CopyBoard(boards[0], initialPosition);
10413 * Skip the first gn-1 games in the file.
10414 * Also skip over anything that precedes an identifiable
10415 * start of game marker, to avoid being confused by
10416 * garbage at the start of the file. Currently
10417 * recognized start of game markers are the move number "1",
10418 * the pattern "gnuchess .* game", the pattern
10419 * "^[#;%] [^ ]* game file", and a PGN tag block.
10420 * A game that starts with one of the latter two patterns
10421 * will also have a move number 1, possibly
10422 * following a position diagram.
10423 * 5-4-02: Let's try being more lenient and allowing a game to
10424 * start with an unnumbered move. Does that break anything?
10426 cm = lastLoadGameStart = EndOfFile;
10428 yyboardindex = forwardMostMove;
10429 cm = (ChessMove) Myylex();
10432 if (cmailMsgLoaded) {
10433 nCmailGames = CMAIL_MAX_GAMES - gn;
10436 DisplayError(_("Game not found in file"), 0);
10443 lastLoadGameStart = cm;
10446 case MoveNumberOne:
10447 switch (lastLoadGameStart) {
10452 case MoveNumberOne:
10454 gn--; /* count this game */
10455 lastLoadGameStart = cm;
10464 switch (lastLoadGameStart) {
10467 case MoveNumberOne:
10469 gn--; /* count this game */
10470 lastLoadGameStart = cm;
10473 lastLoadGameStart = cm; /* game counted already */
10481 yyboardindex = forwardMostMove;
10482 cm = (ChessMove) Myylex();
10483 } while (cm == PGNTag || cm == Comment);
10490 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
10491 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
10492 != CMAIL_OLD_RESULT) {
10494 cmailResult[ CMAIL_MAX_GAMES
10495 - gn - 1] = CMAIL_OLD_RESULT;
10501 /* Only a NormalMove can be at the start of a game
10502 * without a position diagram. */
10503 if (lastLoadGameStart == EndOfFile ) {
10505 lastLoadGameStart = MoveNumberOne;
10514 if (appData.debugMode)
10515 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
10517 if (cm == XBoardGame) {
10518 /* Skip any header junk before position diagram and/or move 1 */
10520 yyboardindex = forwardMostMove;
10521 cm = (ChessMove) Myylex();
10523 if (cm == EndOfFile ||
10524 cm == GNUChessGame || cm == XBoardGame) {
10525 /* Empty game; pretend end-of-file and handle later */
10530 if (cm == MoveNumberOne || cm == PositionDiagram ||
10531 cm == PGNTag || cm == Comment)
10534 } else if (cm == GNUChessGame) {
10535 if (gameInfo.event != NULL) {
10536 free(gameInfo.event);
10538 gameInfo.event = StrSave(yy_text);
10541 startedFromSetupPosition = FALSE;
10542 while (cm == PGNTag) {
10543 if (appData.debugMode)
10544 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
10545 err = ParsePGNTag(yy_text, &gameInfo);
10546 if (!err) numPGNTags++;
10548 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
10549 if(gameInfo.variant != oldVariant) {
10550 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
10551 ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
10552 InitPosition(TRUE);
10553 oldVariant = gameInfo.variant;
10554 if (appData.debugMode)
10555 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
10559 if (gameInfo.fen != NULL) {
10560 Board initial_position;
10561 startedFromSetupPosition = TRUE;
10562 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
10564 DisplayError(_("Bad FEN position in file"), 0);
10567 CopyBoard(boards[0], initial_position);
10568 if (blackPlaysFirst) {
10569 currentMove = forwardMostMove = backwardMostMove = 1;
10570 CopyBoard(boards[1], initial_position);
10571 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10572 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10573 timeRemaining[0][1] = whiteTimeRemaining;
10574 timeRemaining[1][1] = blackTimeRemaining;
10575 if (commentList[0] != NULL) {
10576 commentList[1] = commentList[0];
10577 commentList[0] = NULL;
10580 currentMove = forwardMostMove = backwardMostMove = 0;
10582 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
10584 initialRulePlies = FENrulePlies;
10585 for( i=0; i< nrCastlingRights; i++ )
10586 initialRights[i] = initial_position[CASTLING][i];
10588 yyboardindex = forwardMostMove;
10589 free(gameInfo.fen);
10590 gameInfo.fen = NULL;
10593 yyboardindex = forwardMostMove;
10594 cm = (ChessMove) Myylex();
10596 /* Handle comments interspersed among the tags */
10597 while (cm == Comment) {
10599 if (appData.debugMode)
10600 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10602 AppendComment(currentMove, p, FALSE);
10603 yyboardindex = forwardMostMove;
10604 cm = (ChessMove) Myylex();
10608 /* don't rely on existence of Event tag since if game was
10609 * pasted from clipboard the Event tag may not exist
10611 if (numPGNTags > 0){
10613 if (gameInfo.variant == VariantNormal) {
10614 VariantClass v = StringToVariant(gameInfo.event);
10615 // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
10616 if(v < VariantShogi) gameInfo.variant = v;
10619 if( appData.autoDisplayTags ) {
10620 tags = PGNTags(&gameInfo);
10621 TagsPopUp(tags, CmailMsg());
10626 /* Make something up, but don't display it now */
10631 if (cm == PositionDiagram) {
10634 Board initial_position;
10636 if (appData.debugMode)
10637 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
10639 if (!startedFromSetupPosition) {
10641 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
10642 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
10653 initial_position[i][j++] = CharToPiece(*p);
10656 while (*p == ' ' || *p == '\t' ||
10657 *p == '\n' || *p == '\r') p++;
10659 if (strncmp(p, "black", strlen("black"))==0)
10660 blackPlaysFirst = TRUE;
10662 blackPlaysFirst = FALSE;
10663 startedFromSetupPosition = TRUE;
10665 CopyBoard(boards[0], initial_position);
10666 if (blackPlaysFirst) {
10667 currentMove = forwardMostMove = backwardMostMove = 1;
10668 CopyBoard(boards[1], initial_position);
10669 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10670 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10671 timeRemaining[0][1] = whiteTimeRemaining;
10672 timeRemaining[1][1] = blackTimeRemaining;
10673 if (commentList[0] != NULL) {
10674 commentList[1] = commentList[0];
10675 commentList[0] = NULL;
10678 currentMove = forwardMostMove = backwardMostMove = 0;
10681 yyboardindex = forwardMostMove;
10682 cm = (ChessMove) Myylex();
10685 if (first.pr == NoProc) {
10686 StartChessProgram(&first);
10688 InitChessProgram(&first, FALSE);
10689 SendToProgram("force\n", &first);
10690 if (startedFromSetupPosition) {
10691 SendBoard(&first, forwardMostMove);
10692 if (appData.debugMode) {
10693 fprintf(debugFP, "Load Game\n");
10695 DisplayBothClocks();
10698 /* [HGM] server: flag to write setup moves in broadcast file as one */
10699 loadFlag = appData.suppressLoadMoves;
10701 while (cm == Comment) {
10703 if (appData.debugMode)
10704 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10706 AppendComment(currentMove, p, FALSE);
10707 yyboardindex = forwardMostMove;
10708 cm = (ChessMove) Myylex();
10711 if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
10712 cm == WhiteWins || cm == BlackWins ||
10713 cm == GameIsDrawn || cm == GameUnfinished) {
10714 DisplayMessage("", _("No moves in game"));
10715 if (cmailMsgLoaded) {
10716 if (appData.debugMode)
10717 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
10721 DrawPosition(FALSE, boards[currentMove]);
10722 DisplayBothClocks();
10723 gameMode = EditGame;
10730 // [HGM] PV info: routine tests if comment empty
10731 if (!matchMode && (pausing || appData.timeDelay != 0)) {
10732 DisplayComment(currentMove - 1, commentList[currentMove]);
10734 if (!matchMode && appData.timeDelay != 0)
10735 DrawPosition(FALSE, boards[currentMove]);
10737 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
10738 programStats.ok_to_send = 1;
10741 /* if the first token after the PGN tags is a move
10742 * and not move number 1, retrieve it from the parser
10744 if (cm != MoveNumberOne)
10745 LoadGameOneMove(cm);
10747 /* load the remaining moves from the file */
10748 while (LoadGameOneMove(EndOfFile)) {
10749 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
10750 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
10753 /* rewind to the start of the game */
10754 currentMove = backwardMostMove;
10756 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
10758 if (oldGameMode == AnalyzeFile ||
10759 oldGameMode == AnalyzeMode) {
10760 AnalyzeFileEvent();
10763 if (matchMode || appData.timeDelay == 0) {
10765 gameMode = EditGame;
10767 } else if (appData.timeDelay > 0) {
10768 AutoPlayGameLoop();
10771 if (appData.debugMode)
10772 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
10774 loadFlag = 0; /* [HGM] true game starts */
10778 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
10780 ReloadPosition(offset)
10783 int positionNumber = lastLoadPositionNumber + offset;
10784 if (lastLoadPositionFP == NULL) {
10785 DisplayError(_("No position has been loaded yet"), 0);
10788 if (positionNumber <= 0) {
10789 DisplayError(_("Can't back up any further"), 0);
10792 return LoadPosition(lastLoadPositionFP, positionNumber,
10793 lastLoadPositionTitle);
10796 /* Load the nth position from the given file */
10798 LoadPositionFromFile(filename, n, title)
10806 if (strcmp(filename, "-") == 0) {
10807 return LoadPosition(stdin, n, "stdin");
10809 f = fopen(filename, "rb");
10811 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10812 DisplayError(buf, errno);
10815 return LoadPosition(f, n, title);
10820 /* Load the nth position from the given open file, and close it */
10822 LoadPosition(f, positionNumber, title)
10824 int positionNumber;
10827 char *p, line[MSG_SIZ];
10828 Board initial_position;
10829 int i, j, fenMode, pn;
10831 if (gameMode == Training )
10832 SetTrainingModeOff();
10834 if (gameMode != BeginningOfGame) {
10835 Reset(FALSE, TRUE);
10837 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
10838 fclose(lastLoadPositionFP);
10840 if (positionNumber == 0) positionNumber = 1;
10841 lastLoadPositionFP = f;
10842 lastLoadPositionNumber = positionNumber;
10843 safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
10844 if (first.pr == NoProc) {
10845 StartChessProgram(&first);
10846 InitChessProgram(&first, FALSE);
10848 pn = positionNumber;
10849 if (positionNumber < 0) {
10850 /* Negative position number means to seek to that byte offset */
10851 if (fseek(f, -positionNumber, 0) == -1) {
10852 DisplayError(_("Can't seek on position file"), 0);
10857 if (fseek(f, 0, 0) == -1) {
10858 if (f == lastLoadPositionFP ?
10859 positionNumber == lastLoadPositionNumber + 1 :
10860 positionNumber == 1) {
10863 DisplayError(_("Can't seek on position file"), 0);
10868 /* See if this file is FEN or old-style xboard */
10869 if (fgets(line, MSG_SIZ, f) == NULL) {
10870 DisplayError(_("Position not found in file"), 0);
10873 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
10874 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
10877 if (fenMode || line[0] == '#') pn--;
10879 /* skip positions before number pn */
10880 if (fgets(line, MSG_SIZ, f) == NULL) {
10882 DisplayError(_("Position not found in file"), 0);
10885 if (fenMode || line[0] == '#') pn--;
10890 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
10891 DisplayError(_("Bad FEN position in file"), 0);
10895 (void) fgets(line, MSG_SIZ, f);
10896 (void) fgets(line, MSG_SIZ, f);
10898 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
10899 (void) fgets(line, MSG_SIZ, f);
10900 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
10903 initial_position[i][j++] = CharToPiece(*p);
10907 blackPlaysFirst = FALSE;
10909 (void) fgets(line, MSG_SIZ, f);
10910 if (strncmp(line, "black", strlen("black"))==0)
10911 blackPlaysFirst = TRUE;
10914 startedFromSetupPosition = TRUE;
10916 SendToProgram("force\n", &first);
10917 CopyBoard(boards[0], initial_position);
10918 if (blackPlaysFirst) {
10919 currentMove = forwardMostMove = backwardMostMove = 1;
10920 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10921 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10922 CopyBoard(boards[1], initial_position);
10923 DisplayMessage("", _("Black to play"));
10925 currentMove = forwardMostMove = backwardMostMove = 0;
10926 DisplayMessage("", _("White to play"));
10928 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
10929 SendBoard(&first, forwardMostMove);
10930 if (appData.debugMode) {
10932 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
10933 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
10934 fprintf(debugFP, "Load Position\n");
10937 if (positionNumber > 1) {
10938 snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
10939 DisplayTitle(line);
10941 DisplayTitle(title);
10943 gameMode = EditGame;
10946 timeRemaining[0][1] = whiteTimeRemaining;
10947 timeRemaining[1][1] = blackTimeRemaining;
10948 DrawPosition(FALSE, boards[currentMove]);
10955 CopyPlayerNameIntoFileName(dest, src)
10958 while (*src != NULLCHAR && *src != ',') {
10963 *(*dest)++ = *src++;
10968 char *DefaultFileName(ext)
10971 static char def[MSG_SIZ];
10974 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
10976 CopyPlayerNameIntoFileName(&p, gameInfo.white);
10978 CopyPlayerNameIntoFileName(&p, gameInfo.black);
10980 safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
10987 /* Save the current game to the given file */
10989 SaveGameToFile(filename, append)
10997 if (strcmp(filename, "-") == 0) {
10998 return SaveGame(stdout, 0, NULL);
11000 f = fopen(filename, append ? "a" : "w");
11002 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
11003 DisplayError(buf, errno);
11006 safeStrCpy(buf, lastMsg, MSG_SIZ);
11007 DisplayMessage(_("Waiting for access to save file"), "");
11008 flock(fileno(f), LOCK_EX); // [HGM] lock: lock file while we are writing
11009 DisplayMessage(_("Saving game"), "");
11010 if(lseek(fileno(f), 0, SEEK_END) == -1) DisplayError("Bad Seek", errno); // better safe than sorry...
11011 result = SaveGame(f, 0, NULL);
11012 DisplayMessage(buf, "");
11022 static char buf[MSG_SIZ];
11025 p = strchr(str, ' ');
11026 if (p == NULL) return str;
11027 strncpy(buf, str, p - str);
11028 buf[p - str] = NULLCHAR;
11032 #define PGN_MAX_LINE 75
11034 #define PGN_SIDE_WHITE 0
11035 #define PGN_SIDE_BLACK 1
11038 static int FindFirstMoveOutOfBook( int side )
11042 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
11043 int index = backwardMostMove;
11044 int has_book_hit = 0;
11046 if( (index % 2) != side ) {
11050 while( index < forwardMostMove ) {
11051 /* Check to see if engine is in book */
11052 int depth = pvInfoList[index].depth;
11053 int score = pvInfoList[index].score;
11059 else if( score == 0 && depth == 63 ) {
11060 in_book = 1; /* Zappa */
11062 else if( score == 2 && depth == 99 ) {
11063 in_book = 1; /* Abrok */
11066 has_book_hit += in_book;
11082 void GetOutOfBookInfo( char * buf )
11086 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
11088 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
11089 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
11093 if( oob[0] >= 0 || oob[1] >= 0 ) {
11094 for( i=0; i<2; i++ ) {
11098 if( i > 0 && oob[0] >= 0 ) {
11099 strcat( buf, " " );
11102 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
11103 sprintf( buf+strlen(buf), "%s%.2f",
11104 pvInfoList[idx].score >= 0 ? "+" : "",
11105 pvInfoList[idx].score / 100.0 );
11111 /* Save game in PGN style and close the file */
11116 int i, offset, linelen, newblock;
11120 int movelen, numlen, blank;
11121 char move_buffer[100]; /* [AS] Buffer for move+PV info */
11123 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
11125 tm = time((time_t *) NULL);
11127 PrintPGNTags(f, &gameInfo);
11129 if (backwardMostMove > 0 || startedFromSetupPosition) {
11130 char *fen = PositionToFEN(backwardMostMove, NULL);
11131 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
11132 fprintf(f, "\n{--------------\n");
11133 PrintPosition(f, backwardMostMove);
11134 fprintf(f, "--------------}\n");
11138 /* [AS] Out of book annotation */
11139 if( appData.saveOutOfBookInfo ) {
11142 GetOutOfBookInfo( buf );
11144 if( buf[0] != '\0' ) {
11145 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
11152 i = backwardMostMove;
11156 while (i < forwardMostMove) {
11157 /* Print comments preceding this move */
11158 if (commentList[i] != NULL) {
11159 if (linelen > 0) fprintf(f, "\n");
11160 fprintf(f, "%s", commentList[i]);
11165 /* Format move number */
11167 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
11170 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
11172 numtext[0] = NULLCHAR;
11174 numlen = strlen(numtext);
11177 /* Print move number */
11178 blank = linelen > 0 && numlen > 0;
11179 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
11188 fprintf(f, "%s", numtext);
11192 safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
11193 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
11196 blank = linelen > 0 && movelen > 0;
11197 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
11206 fprintf(f, "%s", move_buffer);
11207 linelen += movelen;
11209 /* [AS] Add PV info if present */
11210 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
11211 /* [HGM] add time */
11212 char buf[MSG_SIZ]; int seconds;
11214 seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
11220 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
11223 seconds = (seconds + 4)/10; // round to full seconds
11225 snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
11227 snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
11230 snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
11231 pvInfoList[i].score >= 0 ? "+" : "",
11232 pvInfoList[i].score / 100.0,
11233 pvInfoList[i].depth,
11236 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
11238 /* Print score/depth */
11239 blank = linelen > 0 && movelen > 0;
11240 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
11249 fprintf(f, "%s", move_buffer);
11250 linelen += movelen;
11256 /* Start a new line */
11257 if (linelen > 0) fprintf(f, "\n");
11259 /* Print comments after last move */
11260 if (commentList[i] != NULL) {
11261 fprintf(f, "%s\n", commentList[i]);
11265 if (gameInfo.resultDetails != NULL &&
11266 gameInfo.resultDetails[0] != NULLCHAR) {
11267 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
11268 PGNResult(gameInfo.result));
11270 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
11274 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
11278 /* Save game in old style and close the file */
11280 SaveGameOldStyle(f)
11286 tm = time((time_t *) NULL);
11288 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
11291 if (backwardMostMove > 0 || startedFromSetupPosition) {
11292 fprintf(f, "\n[--------------\n");
11293 PrintPosition(f, backwardMostMove);
11294 fprintf(f, "--------------]\n");
11299 i = backwardMostMove;
11300 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
11302 while (i < forwardMostMove) {
11303 if (commentList[i] != NULL) {
11304 fprintf(f, "[%s]\n", commentList[i]);
11307 if ((i % 2) == 1) {
11308 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
11311 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
11313 if (commentList[i] != NULL) {
11317 if (i >= forwardMostMove) {
11321 fprintf(f, "%s\n", parseList[i]);
11326 if (commentList[i] != NULL) {
11327 fprintf(f, "[%s]\n", commentList[i]);
11330 /* This isn't really the old style, but it's close enough */
11331 if (gameInfo.resultDetails != NULL &&
11332 gameInfo.resultDetails[0] != NULLCHAR) {
11333 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
11334 gameInfo.resultDetails);
11336 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
11343 /* Save the current game to open file f and close the file */
11345 SaveGame(f, dummy, dummy2)
11350 if (gameMode == EditPosition) EditPositionDone(TRUE);
11351 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
11352 if (appData.oldSaveStyle)
11353 return SaveGameOldStyle(f);
11355 return SaveGamePGN(f);
11358 /* Save the current position to the given file */
11360 SavePositionToFile(filename)
11366 if (strcmp(filename, "-") == 0) {
11367 return SavePosition(stdout, 0, NULL);
11369 f = fopen(filename, "a");
11371 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
11372 DisplayError(buf, errno);
11375 safeStrCpy(buf, lastMsg, MSG_SIZ);
11376 DisplayMessage(_("Waiting for access to save file"), "");
11377 flock(fileno(f), LOCK_EX); // [HGM] lock
11378 DisplayMessage(_("Saving position"), "");
11379 lseek(fileno(f), 0, SEEK_END); // better safe than sorry...
11380 SavePosition(f, 0, NULL);
11381 DisplayMessage(buf, "");
11387 /* Save the current position to the given open file and close the file */
11389 SavePosition(f, dummy, dummy2)
11397 if (gameMode == EditPosition) EditPositionDone(TRUE);
11398 if (appData.oldSaveStyle) {
11399 tm = time((time_t *) NULL);
11401 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
11403 fprintf(f, "[--------------\n");
11404 PrintPosition(f, currentMove);
11405 fprintf(f, "--------------]\n");
11407 fen = PositionToFEN(currentMove, NULL);
11408 fprintf(f, "%s\n", fen);
11416 ReloadCmailMsgEvent(unregister)
11420 static char *inFilename = NULL;
11421 static char *outFilename;
11423 struct stat inbuf, outbuf;
11426 /* Any registered moves are unregistered if unregister is set, */
11427 /* i.e. invoked by the signal handler */
11429 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
11430 cmailMoveRegistered[i] = FALSE;
11431 if (cmailCommentList[i] != NULL) {
11432 free(cmailCommentList[i]);
11433 cmailCommentList[i] = NULL;
11436 nCmailMovesRegistered = 0;
11439 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
11440 cmailResult[i] = CMAIL_NOT_RESULT;
11444 if (inFilename == NULL) {
11445 /* Because the filenames are static they only get malloced once */
11446 /* and they never get freed */
11447 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
11448 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
11450 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
11451 sprintf(outFilename, "%s.out", appData.cmailGameName);
11454 status = stat(outFilename, &outbuf);
11456 cmailMailedMove = FALSE;
11458 status = stat(inFilename, &inbuf);
11459 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
11462 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
11463 counts the games, notes how each one terminated, etc.
11465 It would be nice to remove this kludge and instead gather all
11466 the information while building the game list. (And to keep it
11467 in the game list nodes instead of having a bunch of fixed-size
11468 parallel arrays.) Note this will require getting each game's
11469 termination from the PGN tags, as the game list builder does
11470 not process the game moves. --mann
11472 cmailMsgLoaded = TRUE;
11473 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
11475 /* Load first game in the file or popup game menu */
11476 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
11478 #endif /* !WIN32 */
11486 char string[MSG_SIZ];
11488 if ( cmailMailedMove
11489 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
11490 return TRUE; /* Allow free viewing */
11493 /* Unregister move to ensure that we don't leave RegisterMove */
11494 /* with the move registered when the conditions for registering no */
11496 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11497 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
11498 nCmailMovesRegistered --;
11500 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
11502 free(cmailCommentList[lastLoadGameNumber - 1]);
11503 cmailCommentList[lastLoadGameNumber - 1] = NULL;
11507 if (cmailOldMove == -1) {
11508 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
11512 if (currentMove > cmailOldMove + 1) {
11513 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
11517 if (currentMove < cmailOldMove) {
11518 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
11522 if (forwardMostMove > currentMove) {
11523 /* Silently truncate extra moves */
11527 if ( (currentMove == cmailOldMove + 1)
11528 || ( (currentMove == cmailOldMove)
11529 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
11530 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
11531 if (gameInfo.result != GameUnfinished) {
11532 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
11535 if (commentList[currentMove] != NULL) {
11536 cmailCommentList[lastLoadGameNumber - 1]
11537 = StrSave(commentList[currentMove]);
11539 safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
11541 if (appData.debugMode)
11542 fprintf(debugFP, "Saving %s for game %d\n",
11543 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
11545 snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
11547 f = fopen(string, "w");
11548 if (appData.oldSaveStyle) {
11549 SaveGameOldStyle(f); /* also closes the file */
11551 snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
11552 f = fopen(string, "w");
11553 SavePosition(f, 0, NULL); /* also closes the file */
11555 fprintf(f, "{--------------\n");
11556 PrintPosition(f, currentMove);
11557 fprintf(f, "--------------}\n\n");
11559 SaveGame(f, 0, NULL); /* also closes the file*/
11562 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
11563 nCmailMovesRegistered ++;
11564 } else if (nCmailGames == 1) {
11565 DisplayError(_("You have not made a move yet"), 0);
11576 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
11577 FILE *commandOutput;
11578 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
11579 int nBytes = 0; /* Suppress warnings on uninitialized variables */
11585 if (! cmailMsgLoaded) {
11586 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
11590 if (nCmailGames == nCmailResults) {
11591 DisplayError(_("No unfinished games"), 0);
11595 #if CMAIL_PROHIBIT_REMAIL
11596 if (cmailMailedMove) {
11597 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);
11598 DisplayError(msg, 0);
11603 if (! (cmailMailedMove || RegisterMove())) return;
11605 if ( cmailMailedMove
11606 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
11607 snprintf(string, MSG_SIZ, partCommandString,
11608 appData.debugMode ? " -v" : "", appData.cmailGameName);
11609 commandOutput = popen(string, "r");
11611 if (commandOutput == NULL) {
11612 DisplayError(_("Failed to invoke cmail"), 0);
11614 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
11615 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
11617 if (nBuffers > 1) {
11618 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
11619 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
11620 nBytes = MSG_SIZ - 1;
11622 (void) memcpy(msg, buffer, nBytes);
11624 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
11626 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
11627 cmailMailedMove = TRUE; /* Prevent >1 moves */
11630 for (i = 0; i < nCmailGames; i ++) {
11631 if (cmailResult[i] == CMAIL_NOT_RESULT) {
11636 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
11638 snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
11640 appData.cmailGameName,
11642 LoadGameFromFile(buffer, 1, buffer, FALSE);
11643 cmailMsgLoaded = FALSE;
11647 DisplayInformation(msg);
11648 pclose(commandOutput);
11651 if ((*cmailMsg) != '\0') {
11652 DisplayInformation(cmailMsg);
11657 #endif /* !WIN32 */
11666 int prependComma = 0;
11668 char string[MSG_SIZ]; /* Space for game-list */
11671 if (!cmailMsgLoaded) return "";
11673 if (cmailMailedMove) {
11674 snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
11676 /* Create a list of games left */
11677 snprintf(string, MSG_SIZ, "[");
11678 for (i = 0; i < nCmailGames; i ++) {
11679 if (! ( cmailMoveRegistered[i]
11680 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
11681 if (prependComma) {
11682 snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
11684 snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
11688 strcat(string, number);
11691 strcat(string, "]");
11693 if (nCmailMovesRegistered + nCmailResults == 0) {
11694 switch (nCmailGames) {
11696 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
11700 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
11704 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
11709 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
11711 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
11716 if (nCmailResults == nCmailGames) {
11717 snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
11719 snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
11724 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
11736 if (gameMode == Training)
11737 SetTrainingModeOff();
11740 cmailMsgLoaded = FALSE;
11741 if (appData.icsActive) {
11742 SendToICS(ics_prefix);
11743 SendToICS("refresh\n");
11753 /* Give up on clean exit */
11757 /* Keep trying for clean exit */
11761 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
11763 if (telnetISR != NULL) {
11764 RemoveInputSource(telnetISR);
11766 if (icsPR != NoProc) {
11767 DestroyChildProcess(icsPR, TRUE);
11770 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
11771 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
11773 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
11774 /* make sure this other one finishes before killing it! */
11775 if(endingGame) { int count = 0;
11776 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
11777 while(endingGame && count++ < 10) DoSleep(1);
11778 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
11781 /* Kill off chess programs */
11782 if (first.pr != NoProc) {
11785 DoSleep( appData.delayBeforeQuit );
11786 SendToProgram("quit\n", &first);
11787 DoSleep( appData.delayAfterQuit );
11788 DestroyChildProcess(first.pr, 10 /* [AS] first.useSigterm */ );
11790 if (second.pr != NoProc) {
11791 DoSleep( appData.delayBeforeQuit );
11792 SendToProgram("quit\n", &second);
11793 DoSleep( appData.delayAfterQuit );
11794 DestroyChildProcess(second.pr, 10 /* [AS] second.useSigterm */ );
11796 if (first.isr != NULL) {
11797 RemoveInputSource(first.isr);
11799 if (second.isr != NULL) {
11800 RemoveInputSource(second.isr);
11803 ShutDownFrontEnd();
11810 if (appData.debugMode)
11811 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
11815 if (gameMode == MachinePlaysWhite ||
11816 gameMode == MachinePlaysBlack) {
11819 DisplayBothClocks();
11821 if (gameMode == PlayFromGameFile) {
11822 if (appData.timeDelay >= 0)
11823 AutoPlayGameLoop();
11824 } else if (gameMode == IcsExamining && pauseExamInvalid) {
11825 Reset(FALSE, TRUE);
11826 SendToICS(ics_prefix);
11827 SendToICS("refresh\n");
11828 } else if (currentMove < forwardMostMove) {
11829 ForwardInner(forwardMostMove);
11831 pauseExamInvalid = FALSE;
11833 switch (gameMode) {
11837 pauseExamForwardMostMove = forwardMostMove;
11838 pauseExamInvalid = FALSE;
11841 case IcsPlayingWhite:
11842 case IcsPlayingBlack:
11846 case PlayFromGameFile:
11847 (void) StopLoadGameTimer();
11851 case BeginningOfGame:
11852 if (appData.icsActive) return;
11853 /* else fall through */
11854 case MachinePlaysWhite:
11855 case MachinePlaysBlack:
11856 case TwoMachinesPlay:
11857 if (forwardMostMove == 0)
11858 return; /* don't pause if no one has moved */
11859 if ((gameMode == MachinePlaysWhite &&
11860 !WhiteOnMove(forwardMostMove)) ||
11861 (gameMode == MachinePlaysBlack &&
11862 WhiteOnMove(forwardMostMove))) {
11875 char title[MSG_SIZ];
11877 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
11878 safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
11880 snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
11881 WhiteOnMove(currentMove - 1) ? " " : ".. ",
11882 parseList[currentMove - 1]);
11885 EditCommentPopUp(currentMove, title, commentList[currentMove]);
11892 char *tags = PGNTags(&gameInfo);
11893 EditTagsPopUp(tags, NULL);
11900 if (appData.noChessProgram || gameMode == AnalyzeMode)
11903 if (gameMode != AnalyzeFile) {
11904 if (!appData.icsEngineAnalyze) {
11906 if (gameMode != EditGame) return;
11908 ResurrectChessProgram();
11909 SendToProgram("analyze\n", &first);
11910 first.analyzing = TRUE;
11911 /*first.maybeThinking = TRUE;*/
11912 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11913 EngineOutputPopUp();
11915 if (!appData.icsEngineAnalyze) gameMode = AnalyzeMode;
11920 StartAnalysisClock();
11921 GetTimeMark(&lastNodeCountTime);
11928 if (appData.noChessProgram || gameMode == AnalyzeFile)
11931 if (gameMode != AnalyzeMode) {
11933 if (gameMode != EditGame) return;
11934 ResurrectChessProgram();
11935 SendToProgram("analyze\n", &first);
11936 first.analyzing = TRUE;
11937 /*first.maybeThinking = TRUE;*/
11938 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11939 EngineOutputPopUp();
11941 gameMode = AnalyzeFile;
11946 StartAnalysisClock();
11947 GetTimeMark(&lastNodeCountTime);
11952 MachineWhiteEvent()
11955 char *bookHit = NULL;
11957 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
11961 if (gameMode == PlayFromGameFile ||
11962 gameMode == TwoMachinesPlay ||
11963 gameMode == Training ||
11964 gameMode == AnalyzeMode ||
11965 gameMode == EndOfGame)
11968 if (gameMode == EditPosition)
11969 EditPositionDone(TRUE);
11971 if (!WhiteOnMove(currentMove)) {
11972 DisplayError(_("It is not White's turn"), 0);
11976 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
11979 if (gameMode == EditGame || gameMode == AnalyzeMode ||
11980 gameMode == AnalyzeFile)
11983 ResurrectChessProgram(); /* in case it isn't running */
11984 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
11985 gameMode = MachinePlaysWhite;
11988 gameMode = MachinePlaysWhite;
11992 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
11994 if (first.sendName) {
11995 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
11996 SendToProgram(buf, &first);
11998 if (first.sendTime) {
11999 if (first.useColors) {
12000 SendToProgram("black\n", &first); /*gnu kludge*/
12002 SendTimeRemaining(&first, TRUE);
12004 if (first.useColors) {
12005 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
12007 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
12008 SetMachineThinkingEnables();
12009 first.maybeThinking = TRUE;
12013 if (appData.autoFlipView && !flipView) {
12014 flipView = !flipView;
12015 DrawPosition(FALSE, NULL);
12016 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
12019 if(bookHit) { // [HGM] book: simulate book reply
12020 static char bookMove[MSG_SIZ]; // a bit generous?
12022 programStats.nodes = programStats.depth = programStats.time =
12023 programStats.score = programStats.got_only_move = 0;
12024 sprintf(programStats.movelist, "%s (xbook)", bookHit);
12026 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
12027 strcat(bookMove, bookHit);
12028 HandleMachineMove(bookMove, &first);
12033 MachineBlackEvent()
12036 char *bookHit = NULL;
12038 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
12042 if (gameMode == PlayFromGameFile ||
12043 gameMode == TwoMachinesPlay ||
12044 gameMode == Training ||
12045 gameMode == AnalyzeMode ||
12046 gameMode == EndOfGame)
12049 if (gameMode == EditPosition)
12050 EditPositionDone(TRUE);
12052 if (WhiteOnMove(currentMove)) {
12053 DisplayError(_("It is not Black's turn"), 0);
12057 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
12060 if (gameMode == EditGame || gameMode == AnalyzeMode ||
12061 gameMode == AnalyzeFile)
12064 ResurrectChessProgram(); /* in case it isn't running */
12065 gameMode = MachinePlaysBlack;
12069 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
12071 if (first.sendName) {
12072 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
12073 SendToProgram(buf, &first);
12075 if (first.sendTime) {
12076 if (first.useColors) {
12077 SendToProgram("white\n", &first); /*gnu kludge*/
12079 SendTimeRemaining(&first, FALSE);
12081 if (first.useColors) {
12082 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
12084 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
12085 SetMachineThinkingEnables();
12086 first.maybeThinking = TRUE;
12089 if (appData.autoFlipView && flipView) {
12090 flipView = !flipView;
12091 DrawPosition(FALSE, NULL);
12092 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
12094 if(bookHit) { // [HGM] book: simulate book reply
12095 static char bookMove[MSG_SIZ]; // a bit generous?
12097 programStats.nodes = programStats.depth = programStats.time =
12098 programStats.score = programStats.got_only_move = 0;
12099 sprintf(programStats.movelist, "%s (xbook)", bookHit);
12101 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
12102 strcat(bookMove, bookHit);
12103 HandleMachineMove(bookMove, &first);
12109 DisplayTwoMachinesTitle()
12112 if (appData.matchGames > 0) {
12113 if (first.twoMachinesColor[0] == 'w') {
12114 snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
12115 gameInfo.white, gameInfo.black,
12116 first.matchWins, second.matchWins,
12117 matchGame - 1 - (first.matchWins + second.matchWins));
12119 snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
12120 gameInfo.white, gameInfo.black,
12121 second.matchWins, first.matchWins,
12122 matchGame - 1 - (first.matchWins + second.matchWins));
12125 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
12131 SettingsMenuIfReady()
12133 if (second.lastPing != second.lastPong) {
12134 DisplayMessage("", _("Waiting for second chess program"));
12135 ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
12139 DisplayMessage("", "");
12140 SettingsPopUp(&second);
12144 WaitForEngine(ChessProgramState *cps, DelayedEventCallback retry)
12147 if (cps->pr == NULL) {
12148 StartChessProgram(cps);
12149 if (cps->protocolVersion == 1) {
12152 /* kludge: allow timeout for initial "feature" command */
12154 snprintf(buf, MSG_SIZ, _("Starting %s chess program"), cps->which);
12155 DisplayMessage("", buf);
12156 ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
12164 TwoMachinesEvent P((void))
12168 ChessProgramState *onmove;
12169 char *bookHit = NULL;
12170 static int stalling = 0;
12172 if (appData.noChessProgram) return;
12174 switch (gameMode) {
12175 case TwoMachinesPlay:
12177 case MachinePlaysWhite:
12178 case MachinePlaysBlack:
12179 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
12180 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
12184 case BeginningOfGame:
12185 case PlayFromGameFile:
12188 if (gameMode != EditGame) return;
12191 EditPositionDone(TRUE);
12202 // forwardMostMove = currentMove;
12203 TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
12204 ResurrectChessProgram(); /* in case first program isn't running */
12206 if(WaitForEngine(&second, TwoMachinesEventIfReady)) return;
12207 if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
12208 DisplayMessage("", _("Waiting for first chess program"));
12209 ScheduleDelayedEvent(TwoMachinesEvent, 10);
12213 InitChessProgram(&second, FALSE);
12214 SendToProgram("force\n", &second);
12216 if(second.lastPing != second.lastPong) { // [HGM] second engine might have to reallocate hash
12217 if(!stalling) DisplayMessage("", _("Waiting for second chess program"));
12219 ScheduleDelayedEvent(TwoMachinesEvent, 10);
12223 DisplayMessage("", "");
12224 if (startedFromSetupPosition) {
12225 SendBoard(&second, backwardMostMove);
12226 if (appData.debugMode) {
12227 fprintf(debugFP, "Two Machines\n");
12230 for (i = backwardMostMove; i < forwardMostMove; i++) {
12231 SendMoveToProgram(i, &second);
12234 gameMode = TwoMachinesPlay;
12238 DisplayTwoMachinesTitle();
12240 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
12246 SendToProgram(first.computerString, &first);
12247 if (first.sendName) {
12248 snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
12249 SendToProgram(buf, &first);
12251 SendToProgram(second.computerString, &second);
12252 if (second.sendName) {
12253 snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
12254 SendToProgram(buf, &second);
12258 if (!first.sendTime || !second.sendTime) {
12259 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
12260 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
12262 if (onmove->sendTime) {
12263 if (onmove->useColors) {
12264 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
12266 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
12268 if (onmove->useColors) {
12269 SendToProgram(onmove->twoMachinesColor, onmove);
12271 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
12272 // SendToProgram("go\n", onmove);
12273 onmove->maybeThinking = TRUE;
12274 SetMachineThinkingEnables();
12278 if(bookHit) { // [HGM] book: simulate book reply
12279 static char bookMove[MSG_SIZ]; // a bit generous?
12281 programStats.nodes = programStats.depth = programStats.time =
12282 programStats.score = programStats.got_only_move = 0;
12283 sprintf(programStats.movelist, "%s (xbook)", bookHit);
12285 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
12286 strcat(bookMove, bookHit);
12287 savedMessage = bookMove; // args for deferred call
12288 savedState = onmove;
12289 ScheduleDelayedEvent(DeferredBookMove, 1);
12296 if (gameMode == Training) {
12297 SetTrainingModeOff();
12298 gameMode = PlayFromGameFile;
12299 DisplayMessage("", _("Training mode off"));
12301 gameMode = Training;
12302 animateTraining = appData.animate;
12304 /* make sure we are not already at the end of the game */
12305 if (currentMove < forwardMostMove) {
12306 SetTrainingModeOn();
12307 DisplayMessage("", _("Training mode on"));
12309 gameMode = PlayFromGameFile;
12310 DisplayError(_("Already at end of game"), 0);
12319 if (!appData.icsActive) return;
12320 switch (gameMode) {
12321 case IcsPlayingWhite:
12322 case IcsPlayingBlack:
12325 case BeginningOfGame:
12333 EditPositionDone(TRUE);
12346 gameMode = IcsIdle;
12357 switch (gameMode) {
12359 SetTrainingModeOff();
12361 case MachinePlaysWhite:
12362 case MachinePlaysBlack:
12363 case BeginningOfGame:
12364 SendToProgram("force\n", &first);
12365 SetUserThinkingEnables();
12367 case PlayFromGameFile:
12368 (void) StopLoadGameTimer();
12369 if (gameFileFP != NULL) {
12374 EditPositionDone(TRUE);
12379 SendToProgram("force\n", &first);
12381 case TwoMachinesPlay:
12382 GameEnds(EndOfFile, NULL, GE_PLAYER);
12383 ResurrectChessProgram();
12384 SetUserThinkingEnables();
12387 ResurrectChessProgram();
12389 case IcsPlayingBlack:
12390 case IcsPlayingWhite:
12391 DisplayError(_("Warning: You are still playing a game"), 0);
12394 DisplayError(_("Warning: You are still observing a game"), 0);
12397 DisplayError(_("Warning: You are still examining a game"), 0);
12408 first.offeredDraw = second.offeredDraw = 0;
12410 if (gameMode == PlayFromGameFile) {
12411 whiteTimeRemaining = timeRemaining[0][currentMove];
12412 blackTimeRemaining = timeRemaining[1][currentMove];
12416 if (gameMode == MachinePlaysWhite ||
12417 gameMode == MachinePlaysBlack ||
12418 gameMode == TwoMachinesPlay ||
12419 gameMode == EndOfGame) {
12420 i = forwardMostMove;
12421 while (i > currentMove) {
12422 SendToProgram("undo\n", &first);
12425 whiteTimeRemaining = timeRemaining[0][currentMove];
12426 blackTimeRemaining = timeRemaining[1][currentMove];
12427 DisplayBothClocks();
12428 if (whiteFlag || blackFlag) {
12429 whiteFlag = blackFlag = 0;
12434 gameMode = EditGame;
12441 EditPositionEvent()
12443 if (gameMode == EditPosition) {
12449 if (gameMode != EditGame) return;
12451 gameMode = EditPosition;
12454 if (currentMove > 0)
12455 CopyBoard(boards[0], boards[currentMove]);
12457 blackPlaysFirst = !WhiteOnMove(currentMove);
12459 currentMove = forwardMostMove = backwardMostMove = 0;
12460 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12467 /* [DM] icsEngineAnalyze - possible call from other functions */
12468 if (appData.icsEngineAnalyze) {
12469 appData.icsEngineAnalyze = FALSE;
12471 DisplayMessage("",_("Close ICS engine analyze..."));
12473 if (first.analysisSupport && first.analyzing) {
12474 SendToProgram("exit\n", &first);
12475 first.analyzing = FALSE;
12477 thinkOutput[0] = NULLCHAR;
12481 EditPositionDone(Boolean fakeRights)
12483 int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
12485 startedFromSetupPosition = TRUE;
12486 InitChessProgram(&first, FALSE);
12487 if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
12488 boards[0][EP_STATUS] = EP_NONE;
12489 boards[0][CASTLING][2] = boards[0][CASTLING][5] = BOARD_WIDTH>>1;
12490 if(boards[0][0][BOARD_WIDTH>>1] == king) {
12491 boards[0][CASTLING][1] = boards[0][0][BOARD_LEFT] == WhiteRook ? 0 : NoRights;
12492 boards[0][CASTLING][0] = boards[0][0][BOARD_RGHT-1] == WhiteRook ? BOARD_RGHT-1 : NoRights;
12493 } else boards[0][CASTLING][2] = NoRights;
12494 if(boards[0][BOARD_HEIGHT-1][BOARD_WIDTH>>1] == WHITE_TO_BLACK king) {
12495 boards[0][CASTLING][4] = boards[0][BOARD_HEIGHT-1][BOARD_LEFT] == BlackRook ? 0 : NoRights;
12496 boards[0][CASTLING][3] = boards[0][BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook ? BOARD_RGHT-1 : NoRights;
12497 } else boards[0][CASTLING][5] = NoRights;
12499 SendToProgram("force\n", &first);
12500 if (blackPlaysFirst) {
12501 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12502 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12503 currentMove = forwardMostMove = backwardMostMove = 1;
12504 CopyBoard(boards[1], boards[0]);
12506 currentMove = forwardMostMove = backwardMostMove = 0;
12508 SendBoard(&first, forwardMostMove);
12509 if (appData.debugMode) {
12510 fprintf(debugFP, "EditPosDone\n");
12513 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
12514 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
12515 gameMode = EditGame;
12517 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12518 ClearHighlights(); /* [AS] */
12521 /* Pause for `ms' milliseconds */
12522 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
12532 } while (SubtractTimeMarks(&m2, &m1) < ms);
12535 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
12537 SendMultiLineToICS(buf)
12540 char temp[MSG_SIZ+1], *p;
12547 strncpy(temp, buf, len);
12552 if (*p == '\n' || *p == '\r')
12557 strcat(temp, "\n");
12559 SendToPlayer(temp, strlen(temp));
12563 SetWhiteToPlayEvent()
12565 if (gameMode == EditPosition) {
12566 blackPlaysFirst = FALSE;
12567 DisplayBothClocks(); /* works because currentMove is 0 */
12568 } else if (gameMode == IcsExamining) {
12569 SendToICS(ics_prefix);
12570 SendToICS("tomove white\n");
12575 SetBlackToPlayEvent()
12577 if (gameMode == EditPosition) {
12578 blackPlaysFirst = TRUE;
12579 currentMove = 1; /* kludge */
12580 DisplayBothClocks();
12582 } else if (gameMode == IcsExamining) {
12583 SendToICS(ics_prefix);
12584 SendToICS("tomove black\n");
12589 EditPositionMenuEvent(selection, x, y)
12590 ChessSquare selection;
12594 ChessSquare piece = boards[0][y][x];
12596 if (gameMode != EditPosition && gameMode != IcsExamining) return;
12598 switch (selection) {
12600 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
12601 SendToICS(ics_prefix);
12602 SendToICS("bsetup clear\n");
12603 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
12604 SendToICS(ics_prefix);
12605 SendToICS("clearboard\n");
12607 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
12608 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
12609 for (y = 0; y < BOARD_HEIGHT; y++) {
12610 if (gameMode == IcsExamining) {
12611 if (boards[currentMove][y][x] != EmptySquare) {
12612 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
12617 boards[0][y][x] = p;
12622 if (gameMode == EditPosition) {
12623 DrawPosition(FALSE, boards[0]);
12628 SetWhiteToPlayEvent();
12632 SetBlackToPlayEvent();
12636 if (gameMode == IcsExamining) {
12637 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
12638 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
12641 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
12642 if(x == BOARD_LEFT-2) {
12643 if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
12644 boards[0][y][1] = 0;
12646 if(x == BOARD_RGHT+1) {
12647 if(y >= gameInfo.holdingsSize) break;
12648 boards[0][y][BOARD_WIDTH-2] = 0;
12651 boards[0][y][x] = EmptySquare;
12652 DrawPosition(FALSE, boards[0]);
12657 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
12658 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
12659 selection = (ChessSquare) (PROMOTED piece);
12660 } else if(piece == EmptySquare) selection = WhiteSilver;
12661 else selection = (ChessSquare)((int)piece - 1);
12665 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
12666 piece > (int)BlackMan && piece <= (int)BlackKing ) {
12667 selection = (ChessSquare) (DEMOTED piece);
12668 } else if(piece == EmptySquare) selection = BlackSilver;
12669 else selection = (ChessSquare)((int)piece + 1);
12674 if(gameInfo.variant == VariantShatranj ||
12675 gameInfo.variant == VariantXiangqi ||
12676 gameInfo.variant == VariantCourier ||
12677 gameInfo.variant == VariantMakruk )
12678 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
12683 if(gameInfo.variant == VariantXiangqi)
12684 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
12685 if(gameInfo.variant == VariantKnightmate)
12686 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
12689 if (gameMode == IcsExamining) {
12690 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
12691 snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
12692 PieceToChar(selection), AAA + x, ONE + y);
12695 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
12697 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
12698 n = PieceToNumber(selection - BlackPawn);
12699 if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
12700 boards[0][BOARD_HEIGHT-1-n][0] = selection;
12701 boards[0][BOARD_HEIGHT-1-n][1]++;
12703 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
12704 n = PieceToNumber(selection);
12705 if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
12706 boards[0][n][BOARD_WIDTH-1] = selection;
12707 boards[0][n][BOARD_WIDTH-2]++;
12710 boards[0][y][x] = selection;
12711 DrawPosition(TRUE, boards[0]);
12719 DropMenuEvent(selection, x, y)
12720 ChessSquare selection;
12723 ChessMove moveType;
12725 switch (gameMode) {
12726 case IcsPlayingWhite:
12727 case MachinePlaysBlack:
12728 if (!WhiteOnMove(currentMove)) {
12729 DisplayMoveError(_("It is Black's turn"));
12732 moveType = WhiteDrop;
12734 case IcsPlayingBlack:
12735 case MachinePlaysWhite:
12736 if (WhiteOnMove(currentMove)) {
12737 DisplayMoveError(_("It is White's turn"));
12740 moveType = BlackDrop;
12743 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
12749 if (moveType == BlackDrop && selection < BlackPawn) {
12750 selection = (ChessSquare) ((int) selection
12751 + (int) BlackPawn - (int) WhitePawn);
12753 if (boards[currentMove][y][x] != EmptySquare) {
12754 DisplayMoveError(_("That square is occupied"));
12758 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
12764 /* Accept a pending offer of any kind from opponent */
12766 if (appData.icsActive) {
12767 SendToICS(ics_prefix);
12768 SendToICS("accept\n");
12769 } else if (cmailMsgLoaded) {
12770 if (currentMove == cmailOldMove &&
12771 commentList[cmailOldMove] != NULL &&
12772 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12773 "Black offers a draw" : "White offers a draw")) {
12775 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12776 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
12778 DisplayError(_("There is no pending offer on this move"), 0);
12779 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12782 /* Not used for offers from chess program */
12789 /* Decline a pending offer of any kind from opponent */
12791 if (appData.icsActive) {
12792 SendToICS(ics_prefix);
12793 SendToICS("decline\n");
12794 } else if (cmailMsgLoaded) {
12795 if (currentMove == cmailOldMove &&
12796 commentList[cmailOldMove] != NULL &&
12797 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12798 "Black offers a draw" : "White offers a draw")) {
12800 AppendComment(cmailOldMove, "Draw declined", TRUE);
12801 DisplayComment(cmailOldMove - 1, "Draw declined");
12804 DisplayError(_("There is no pending offer on this move"), 0);
12807 /* Not used for offers from chess program */
12814 /* Issue ICS rematch command */
12815 if (appData.icsActive) {
12816 SendToICS(ics_prefix);
12817 SendToICS("rematch\n");
12824 /* Call your opponent's flag (claim a win on time) */
12825 if (appData.icsActive) {
12826 SendToICS(ics_prefix);
12827 SendToICS("flag\n");
12829 switch (gameMode) {
12832 case MachinePlaysWhite:
12835 GameEnds(GameIsDrawn, "Both players ran out of time",
12838 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
12840 DisplayError(_("Your opponent is not out of time"), 0);
12843 case MachinePlaysBlack:
12846 GameEnds(GameIsDrawn, "Both players ran out of time",
12849 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
12851 DisplayError(_("Your opponent is not out of time"), 0);
12859 ClockClick(int which)
12860 { // [HGM] code moved to back-end from winboard.c
12861 if(which) { // black clock
12862 if (gameMode == EditPosition || gameMode == IcsExamining) {
12863 if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
12864 SetBlackToPlayEvent();
12865 } else if (gameMode == EditGame || shiftKey) {
12866 AdjustClock(which, -1);
12867 } else if (gameMode == IcsPlayingWhite ||
12868 gameMode == MachinePlaysBlack) {
12871 } else { // white clock
12872 if (gameMode == EditPosition || gameMode == IcsExamining) {
12873 if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
12874 SetWhiteToPlayEvent();
12875 } else if (gameMode == EditGame || shiftKey) {
12876 AdjustClock(which, -1);
12877 } else if (gameMode == IcsPlayingBlack ||
12878 gameMode == MachinePlaysWhite) {
12887 /* Offer draw or accept pending draw offer from opponent */
12889 if (appData.icsActive) {
12890 /* Note: tournament rules require draw offers to be
12891 made after you make your move but before you punch
12892 your clock. Currently ICS doesn't let you do that;
12893 instead, you immediately punch your clock after making
12894 a move, but you can offer a draw at any time. */
12896 SendToICS(ics_prefix);
12897 SendToICS("draw\n");
12898 userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
12899 } else if (cmailMsgLoaded) {
12900 if (currentMove == cmailOldMove &&
12901 commentList[cmailOldMove] != NULL &&
12902 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12903 "Black offers a draw" : "White offers a draw")) {
12904 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12905 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
12906 } else if (currentMove == cmailOldMove + 1) {
12907 char *offer = WhiteOnMove(cmailOldMove) ?
12908 "White offers a draw" : "Black offers a draw";
12909 AppendComment(currentMove, offer, TRUE);
12910 DisplayComment(currentMove - 1, offer);
12911 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
12913 DisplayError(_("You must make your move before offering a draw"), 0);
12914 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12916 } else if (first.offeredDraw) {
12917 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
12919 if (first.sendDrawOffers) {
12920 SendToProgram("draw\n", &first);
12921 userOfferedDraw = TRUE;
12929 /* Offer Adjourn or accept pending Adjourn offer from opponent */
12931 if (appData.icsActive) {
12932 SendToICS(ics_prefix);
12933 SendToICS("adjourn\n");
12935 /* Currently GNU Chess doesn't offer or accept Adjourns */
12943 /* Offer Abort or accept pending Abort offer from opponent */
12945 if (appData.icsActive) {
12946 SendToICS(ics_prefix);
12947 SendToICS("abort\n");
12949 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
12956 /* Resign. You can do this even if it's not your turn. */
12958 if (appData.icsActive) {
12959 SendToICS(ics_prefix);
12960 SendToICS("resign\n");
12962 switch (gameMode) {
12963 case MachinePlaysWhite:
12964 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12966 case MachinePlaysBlack:
12967 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12970 if (cmailMsgLoaded) {
12972 if (WhiteOnMove(cmailOldMove)) {
12973 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12975 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12977 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
12988 StopObservingEvent()
12990 /* Stop observing current games */
12991 SendToICS(ics_prefix);
12992 SendToICS("unobserve\n");
12996 StopExaminingEvent()
12998 /* Stop observing current game */
12999 SendToICS(ics_prefix);
13000 SendToICS("unexamine\n");
13004 ForwardInner(target)
13009 if (appData.debugMode)
13010 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
13011 target, currentMove, forwardMostMove);
13013 if (gameMode == EditPosition)
13016 if (gameMode == PlayFromGameFile && !pausing)
13019 if (gameMode == IcsExamining && pausing)
13020 limit = pauseExamForwardMostMove;
13022 limit = forwardMostMove;
13024 if (target > limit) target = limit;
13026 if (target > 0 && moveList[target - 1][0]) {
13027 int fromX, fromY, toX, toY;
13028 toX = moveList[target - 1][2] - AAA;
13029 toY = moveList[target - 1][3] - ONE;
13030 if (moveList[target - 1][1] == '@') {
13031 if (appData.highlightLastMove) {
13032 SetHighlights(-1, -1, toX, toY);
13035 fromX = moveList[target - 1][0] - AAA;
13036 fromY = moveList[target - 1][1] - ONE;
13037 if (target == currentMove + 1) {
13038 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
13040 if (appData.highlightLastMove) {
13041 SetHighlights(fromX, fromY, toX, toY);
13045 if (gameMode == EditGame || gameMode == AnalyzeMode ||
13046 gameMode == Training || gameMode == PlayFromGameFile ||
13047 gameMode == AnalyzeFile) {
13048 while (currentMove < target) {
13049 SendMoveToProgram(currentMove++, &first);
13052 currentMove = target;
13055 if (gameMode == EditGame || gameMode == EndOfGame) {
13056 whiteTimeRemaining = timeRemaining[0][currentMove];
13057 blackTimeRemaining = timeRemaining[1][currentMove];
13059 DisplayBothClocks();
13060 DisplayMove(currentMove - 1);
13061 DrawPosition(FALSE, boards[currentMove]);
13062 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
13063 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
13064 DisplayComment(currentMove - 1, commentList[currentMove]);
13072 if (gameMode == IcsExamining && !pausing) {
13073 SendToICS(ics_prefix);
13074 SendToICS("forward\n");
13076 ForwardInner(currentMove + 1);
13083 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13084 /* to optimze, we temporarily turn off analysis mode while we feed
13085 * the remaining moves to the engine. Otherwise we get analysis output
13088 if (first.analysisSupport) {
13089 SendToProgram("exit\nforce\n", &first);
13090 first.analyzing = FALSE;
13094 if (gameMode == IcsExamining && !pausing) {
13095 SendToICS(ics_prefix);
13096 SendToICS("forward 999999\n");
13098 ForwardInner(forwardMostMove);
13101 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13102 /* we have fed all the moves, so reactivate analysis mode */
13103 SendToProgram("analyze\n", &first);
13104 first.analyzing = TRUE;
13105 /*first.maybeThinking = TRUE;*/
13106 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13111 BackwardInner(target)
13114 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
13116 if (appData.debugMode)
13117 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
13118 target, currentMove, forwardMostMove);
13120 if (gameMode == EditPosition) return;
13121 if (currentMove <= backwardMostMove) {
13123 DrawPosition(full_redraw, boards[currentMove]);
13126 if (gameMode == PlayFromGameFile && !pausing)
13129 if (moveList[target][0]) {
13130 int fromX, fromY, toX, toY;
13131 toX = moveList[target][2] - AAA;
13132 toY = moveList[target][3] - ONE;
13133 if (moveList[target][1] == '@') {
13134 if (appData.highlightLastMove) {
13135 SetHighlights(-1, -1, toX, toY);
13138 fromX = moveList[target][0] - AAA;
13139 fromY = moveList[target][1] - ONE;
13140 if (target == currentMove - 1) {
13141 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
13143 if (appData.highlightLastMove) {
13144 SetHighlights(fromX, fromY, toX, toY);
13148 if (gameMode == EditGame || gameMode==AnalyzeMode ||
13149 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
13150 while (currentMove > target) {
13151 SendToProgram("undo\n", &first);
13155 currentMove = target;
13158 if (gameMode == EditGame || gameMode == EndOfGame) {
13159 whiteTimeRemaining = timeRemaining[0][currentMove];
13160 blackTimeRemaining = timeRemaining[1][currentMove];
13162 DisplayBothClocks();
13163 DisplayMove(currentMove - 1);
13164 DrawPosition(full_redraw, boards[currentMove]);
13165 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
13166 // [HGM] PV info: routine tests if comment empty
13167 DisplayComment(currentMove - 1, commentList[currentMove]);
13173 if (gameMode == IcsExamining && !pausing) {
13174 SendToICS(ics_prefix);
13175 SendToICS("backward\n");
13177 BackwardInner(currentMove - 1);
13184 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13185 /* to optimize, we temporarily turn off analysis mode while we undo
13186 * all the moves. Otherwise we get analysis output after each undo.
13188 if (first.analysisSupport) {
13189 SendToProgram("exit\nforce\n", &first);
13190 first.analyzing = FALSE;
13194 if (gameMode == IcsExamining && !pausing) {
13195 SendToICS(ics_prefix);
13196 SendToICS("backward 999999\n");
13198 BackwardInner(backwardMostMove);
13201 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13202 /* we have fed all the moves, so reactivate analysis mode */
13203 SendToProgram("analyze\n", &first);
13204 first.analyzing = TRUE;
13205 /*first.maybeThinking = TRUE;*/
13206 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13213 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
13214 if (to >= forwardMostMove) to = forwardMostMove;
13215 if (to <= backwardMostMove) to = backwardMostMove;
13216 if (to < currentMove) {
13224 RevertEvent(Boolean annotate)
13226 if(PopTail(annotate)) { // [HGM] vari: restore old game tail
13229 if (gameMode != IcsExamining) {
13230 DisplayError(_("You are not examining a game"), 0);
13234 DisplayError(_("You can't revert while pausing"), 0);
13237 SendToICS(ics_prefix);
13238 SendToICS("revert\n");
13244 switch (gameMode) {
13245 case MachinePlaysWhite:
13246 case MachinePlaysBlack:
13247 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
13248 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
13251 if (forwardMostMove < 2) return;
13252 currentMove = forwardMostMove = forwardMostMove - 2;
13253 whiteTimeRemaining = timeRemaining[0][currentMove];
13254 blackTimeRemaining = timeRemaining[1][currentMove];
13255 DisplayBothClocks();
13256 DisplayMove(currentMove - 1);
13257 ClearHighlights();/*!! could figure this out*/
13258 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
13259 SendToProgram("remove\n", &first);
13260 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
13263 case BeginningOfGame:
13267 case IcsPlayingWhite:
13268 case IcsPlayingBlack:
13269 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
13270 SendToICS(ics_prefix);
13271 SendToICS("takeback 2\n");
13273 SendToICS(ics_prefix);
13274 SendToICS("takeback 1\n");
13283 ChessProgramState *cps;
13285 switch (gameMode) {
13286 case MachinePlaysWhite:
13287 if (!WhiteOnMove(forwardMostMove)) {
13288 DisplayError(_("It is your turn"), 0);
13293 case MachinePlaysBlack:
13294 if (WhiteOnMove(forwardMostMove)) {
13295 DisplayError(_("It is your turn"), 0);
13300 case TwoMachinesPlay:
13301 if (WhiteOnMove(forwardMostMove) ==
13302 (first.twoMachinesColor[0] == 'w')) {
13308 case BeginningOfGame:
13312 SendToProgram("?\n", cps);
13316 TruncateGameEvent()
13319 if (gameMode != EditGame) return;
13326 CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
13327 if (forwardMostMove > currentMove) {
13328 if (gameInfo.resultDetails != NULL) {
13329 free(gameInfo.resultDetails);
13330 gameInfo.resultDetails = NULL;
13331 gameInfo.result = GameUnfinished;
13333 forwardMostMove = currentMove;
13334 HistorySet(parseList, backwardMostMove, forwardMostMove,
13342 if (appData.noChessProgram) return;
13343 switch (gameMode) {
13344 case MachinePlaysWhite:
13345 if (WhiteOnMove(forwardMostMove)) {
13346 DisplayError(_("Wait until your turn"), 0);
13350 case BeginningOfGame:
13351 case MachinePlaysBlack:
13352 if (!WhiteOnMove(forwardMostMove)) {
13353 DisplayError(_("Wait until your turn"), 0);
13358 DisplayError(_("No hint available"), 0);
13361 SendToProgram("hint\n", &first);
13362 hintRequested = TRUE;
13368 if (appData.noChessProgram) return;
13369 switch (gameMode) {
13370 case MachinePlaysWhite:
13371 if (WhiteOnMove(forwardMostMove)) {
13372 DisplayError(_("Wait until your turn"), 0);
13376 case BeginningOfGame:
13377 case MachinePlaysBlack:
13378 if (!WhiteOnMove(forwardMostMove)) {
13379 DisplayError(_("Wait until your turn"), 0);
13384 EditPositionDone(TRUE);
13386 case TwoMachinesPlay:
13391 SendToProgram("bk\n", &first);
13392 bookOutput[0] = NULLCHAR;
13393 bookRequested = TRUE;
13399 char *tags = PGNTags(&gameInfo);
13400 TagsPopUp(tags, CmailMsg());
13404 /* end button procedures */
13407 PrintPosition(fp, move)
13413 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
13414 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
13415 char c = PieceToChar(boards[move][i][j]);
13416 fputc(c == 'x' ? '.' : c, fp);
13417 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
13420 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
13421 fprintf(fp, "white to play\n");
13423 fprintf(fp, "black to play\n");
13430 if (gameInfo.white != NULL) {
13431 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
13437 /* Find last component of program's own name, using some heuristics */
13439 TidyProgramName(prog, host, buf)
13440 char *prog, *host, buf[MSG_SIZ];
13443 int local = (strcmp(host, "localhost") == 0);
13444 while (!local && (p = strchr(prog, ';')) != NULL) {
13446 while (*p == ' ') p++;
13449 if (*prog == '"' || *prog == '\'') {
13450 q = strchr(prog + 1, *prog);
13452 q = strchr(prog, ' ');
13454 if (q == NULL) q = prog + strlen(prog);
13456 while (p >= prog && *p != '/' && *p != '\\') p--;
13458 if(p == prog && *p == '"') p++;
13459 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) q -= 4;
13460 memcpy(buf, p, q - p);
13461 buf[q - p] = NULLCHAR;
13469 TimeControlTagValue()
13472 if (!appData.clockMode) {
13473 safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
13474 } else if (movesPerSession > 0) {
13475 snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
13476 } else if (timeIncrement == 0) {
13477 snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
13479 snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
13481 return StrSave(buf);
13487 /* This routine is used only for certain modes */
13488 VariantClass v = gameInfo.variant;
13489 ChessMove r = GameUnfinished;
13492 if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
13493 r = gameInfo.result;
13494 p = gameInfo.resultDetails;
13495 gameInfo.resultDetails = NULL;
13497 ClearGameInfo(&gameInfo);
13498 gameInfo.variant = v;
13500 switch (gameMode) {
13501 case MachinePlaysWhite:
13502 gameInfo.event = StrSave( appData.pgnEventHeader );
13503 gameInfo.site = StrSave(HostName());
13504 gameInfo.date = PGNDate();
13505 gameInfo.round = StrSave("-");
13506 gameInfo.white = StrSave(first.tidy);
13507 gameInfo.black = StrSave(UserName());
13508 gameInfo.timeControl = TimeControlTagValue();
13511 case MachinePlaysBlack:
13512 gameInfo.event = StrSave( appData.pgnEventHeader );
13513 gameInfo.site = StrSave(HostName());
13514 gameInfo.date = PGNDate();
13515 gameInfo.round = StrSave("-");
13516 gameInfo.white = StrSave(UserName());
13517 gameInfo.black = StrSave(first.tidy);
13518 gameInfo.timeControl = TimeControlTagValue();
13521 case TwoMachinesPlay:
13522 gameInfo.event = StrSave( appData.pgnEventHeader );
13523 gameInfo.site = StrSave(HostName());
13524 gameInfo.date = PGNDate();
13525 if (matchGame > 0) {
13527 snprintf(buf, MSG_SIZ, "%d", matchGame);
13528 gameInfo.round = StrSave(buf);
13530 gameInfo.round = StrSave("-");
13532 if (first.twoMachinesColor[0] == 'w') {
13533 gameInfo.white = StrSave(first.tidy);
13534 gameInfo.black = StrSave(second.tidy);
13536 gameInfo.white = StrSave(second.tidy);
13537 gameInfo.black = StrSave(first.tidy);
13539 gameInfo.timeControl = TimeControlTagValue();
13543 gameInfo.event = StrSave("Edited game");
13544 gameInfo.site = StrSave(HostName());
13545 gameInfo.date = PGNDate();
13546 gameInfo.round = StrSave("-");
13547 gameInfo.white = StrSave("-");
13548 gameInfo.black = StrSave("-");
13549 gameInfo.result = r;
13550 gameInfo.resultDetails = p;
13554 gameInfo.event = StrSave("Edited position");
13555 gameInfo.site = StrSave(HostName());
13556 gameInfo.date = PGNDate();
13557 gameInfo.round = StrSave("-");
13558 gameInfo.white = StrSave("-");
13559 gameInfo.black = StrSave("-");
13562 case IcsPlayingWhite:
13563 case IcsPlayingBlack:
13568 case PlayFromGameFile:
13569 gameInfo.event = StrSave("Game from non-PGN file");
13570 gameInfo.site = StrSave(HostName());
13571 gameInfo.date = PGNDate();
13572 gameInfo.round = StrSave("-");
13573 gameInfo.white = StrSave("?");
13574 gameInfo.black = StrSave("?");
13583 ReplaceComment(index, text)
13591 if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
13592 pvInfoList[index-1].depth == len &&
13593 fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
13594 (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
13595 while (*text == '\n') text++;
13596 len = strlen(text);
13597 while (len > 0 && text[len - 1] == '\n') len--;
13599 if (commentList[index] != NULL)
13600 free(commentList[index]);
13603 commentList[index] = NULL;
13606 if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
13607 *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
13608 *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
13609 commentList[index] = (char *) malloc(len + 2);
13610 strncpy(commentList[index], text, len);
13611 commentList[index][len] = '\n';
13612 commentList[index][len + 1] = NULLCHAR;
13614 // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
13616 commentList[index] = (char *) malloc(len + 7);
13617 safeStrCpy(commentList[index], "{\n", 3);
13618 safeStrCpy(commentList[index]+2, text, len+1);
13619 commentList[index][len+2] = NULLCHAR;
13620 while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
13621 strcat(commentList[index], "\n}\n");
13635 if (ch == '\r') continue;
13637 } while (ch != '\0');
13641 AppendComment(index, text, addBraces)
13644 Boolean addBraces; // [HGM] braces: tells if we should add {}
13649 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces); fflush(debugFP);
13650 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
13653 while (*text == '\n') text++;
13654 len = strlen(text);
13655 while (len > 0 && text[len - 1] == '\n') len--;
13657 if (len == 0) return;
13659 if (commentList[index] != NULL) {
13660 old = commentList[index];
13661 oldlen = strlen(old);
13662 while(commentList[index][oldlen-1] == '\n')
13663 commentList[index][--oldlen] = NULLCHAR;
13664 commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
13665 safeStrCpy(commentList[index], old, oldlen + len + 6);
13667 // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
13668 if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
13669 if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
13670 while (*text == '\n') { text++; len--; }
13671 commentList[index][--oldlen] = NULLCHAR;
13673 if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
13674 else strcat(commentList[index], "\n");
13675 strcat(commentList[index], text);
13676 if(addBraces) strcat(commentList[index], addBraces == 2 ? ")\n" : "\n}\n");
13677 else strcat(commentList[index], "\n");
13679 commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
13681 safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
13682 else commentList[index][0] = NULLCHAR;
13683 strcat(commentList[index], text);
13684 strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
13685 if(addBraces == TRUE) strcat(commentList[index], "}\n");
13689 static char * FindStr( char * text, char * sub_text )
13691 char * result = strstr( text, sub_text );
13693 if( result != NULL ) {
13694 result += strlen( sub_text );
13700 /* [AS] Try to extract PV info from PGN comment */
13701 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
13702 char *GetInfoFromComment( int index, char * text )
13704 char * sep = text, *p;
13706 if( text != NULL && index > 0 ) {
13709 int time = -1, sec = 0, deci;
13710 char * s_eval = FindStr( text, "[%eval " );
13711 char * s_emt = FindStr( text, "[%emt " );
13713 if( s_eval != NULL || s_emt != NULL ) {
13717 if( s_eval != NULL ) {
13718 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
13722 if( delim != ']' ) {
13727 if( s_emt != NULL ) {
13732 /* We expect something like: [+|-]nnn.nn/dd */
13735 if(*text != '{') return text; // [HGM] braces: must be normal comment
13737 sep = strchr( text, '/' );
13738 if( sep == NULL || sep < (text+4) ) {
13743 if(p[1] == '(') { // comment starts with PV
13744 p = strchr(p, ')'); // locate end of PV
13745 if(p == NULL || sep < p+5) return text;
13746 // at this point we have something like "{(.*) +0.23/6 ..."
13747 p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
13748 *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
13749 // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
13751 time = -1; sec = -1; deci = -1;
13752 if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
13753 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
13754 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
13755 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
13759 if( score_lo < 0 || score_lo >= 100 ) {
13763 if(sec >= 0) time = 600*time + 10*sec; else
13764 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
13766 score = score >= 0 ? score*100 + score_lo : score*100 - score_lo;
13768 /* [HGM] PV time: now locate end of PV info */
13769 while( *++sep >= '0' && *sep <= '9'); // strip depth
13771 while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
13773 while( *++sep >= '0' && *sep <= '9'); // strip seconds
13775 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
13776 while(*sep == ' ') sep++;
13787 pvInfoList[index-1].depth = depth;
13788 pvInfoList[index-1].score = score;
13789 pvInfoList[index-1].time = 10*time; // centi-sec
13790 if(*sep == '}') *sep = 0; else *--sep = '{';
13791 if(p != text) { while(*p++ = *sep++); sep = text; } // squeeze out space between PV and comment, and return both
13797 SendToProgram(message, cps)
13799 ChessProgramState *cps;
13801 int count, outCount, error;
13804 if (cps->pr == NULL) return;
13807 if (appData.debugMode) {
13810 fprintf(debugFP, "%ld >%-6s: %s",
13811 SubtractTimeMarks(&now, &programStartTime),
13812 cps->which, message);
13815 count = strlen(message);
13816 outCount = OutputToProcess(cps->pr, message, count, &error);
13817 if (outCount < count && !exiting
13818 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
13819 if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
13820 snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
13821 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
13822 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
13823 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
13824 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
13826 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
13828 gameInfo.resultDetails = StrSave(buf);
13830 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
13835 ReceiveFromProgram(isr, closure, message, count, error)
13836 InputSourceRef isr;
13844 ChessProgramState *cps = (ChessProgramState *)closure;
13846 if (isr != cps->isr) return; /* Killed intentionally */
13849 snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
13850 _(cps->which), cps->program);
13851 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
13852 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
13853 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
13854 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
13856 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
13858 gameInfo.resultDetails = StrSave(buf);
13860 RemoveInputSource(cps->isr);
13861 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
13863 snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
13864 _(cps->which), cps->program);
13865 RemoveInputSource(cps->isr);
13867 /* [AS] Program is misbehaving badly... kill it */
13868 if( count == -2 ) {
13869 DestroyChildProcess( cps->pr, 9 );
13873 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
13878 if ((end_str = strchr(message, '\r')) != NULL)
13879 *end_str = NULLCHAR;
13880 if ((end_str = strchr(message, '\n')) != NULL)
13881 *end_str = NULLCHAR;
13883 if (appData.debugMode) {
13884 TimeMark now; int print = 1;
13885 char *quote = ""; char c; int i;
13887 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
13888 char start = message[0];
13889 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
13890 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
13891 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
13892 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
13893 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
13894 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
13895 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
13896 sscanf(message, "setboard %c", &c)!=1 && sscanf(message, "setup %c", &c)!=1 &&
13897 sscanf(message, "hint: %c", &c)!=1 &&
13898 sscanf(message, "pong %c", &c)!=1 && start != '#') {
13899 quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
13900 print = (appData.engineComments >= 2);
13902 message[0] = start; // restore original message
13906 fprintf(debugFP, "%ld <%-6s: %s%s\n",
13907 SubtractTimeMarks(&now, &programStartTime), cps->which,
13913 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
13914 if (appData.icsEngineAnalyze) {
13915 if (strstr(message, "whisper") != NULL ||
13916 strstr(message, "kibitz") != NULL ||
13917 strstr(message, "tellics") != NULL) return;
13920 HandleMachineMove(message, cps);
13925 SendTimeControl(cps, mps, tc, inc, sd, st)
13926 ChessProgramState *cps;
13927 int mps, inc, sd, st;
13933 if( timeControl_2 > 0 ) {
13934 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
13935 tc = timeControl_2;
13938 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
13939 inc /= cps->timeOdds;
13940 st /= cps->timeOdds;
13942 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
13945 /* Set exact time per move, normally using st command */
13946 if (cps->stKludge) {
13947 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
13949 if (seconds == 0) {
13950 snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
13952 snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
13955 snprintf(buf, MSG_SIZ, "st %d\n", st);
13958 /* Set conventional or incremental time control, using level command */
13959 if (seconds == 0) {
13960 /* Note old gnuchess bug -- minutes:seconds used to not work.
13961 Fixed in later versions, but still avoid :seconds
13962 when seconds is 0. */
13963 snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
13965 snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
13966 seconds, inc/1000.);
13969 SendToProgram(buf, cps);
13971 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
13972 /* Orthogonally, limit search to given depth */
13974 if (cps->sdKludge) {
13975 snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
13977 snprintf(buf, MSG_SIZ, "sd %d\n", sd);
13979 SendToProgram(buf, cps);
13982 if(cps->nps >= 0) { /* [HGM] nps */
13983 if(cps->supportsNPS == FALSE)
13984 cps->nps = -1; // don't use if engine explicitly says not supported!
13986 snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
13987 SendToProgram(buf, cps);
13992 ChessProgramState *WhitePlayer()
13993 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
13995 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
13996 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
14002 SendTimeRemaining(cps, machineWhite)
14003 ChessProgramState *cps;
14004 int /*boolean*/ machineWhite;
14006 char message[MSG_SIZ];
14009 /* Note: this routine must be called when the clocks are stopped
14010 or when they have *just* been set or switched; otherwise
14011 it will be off by the time since the current tick started.
14013 if (machineWhite) {
14014 time = whiteTimeRemaining / 10;
14015 otime = blackTimeRemaining / 10;
14017 time = blackTimeRemaining / 10;
14018 otime = whiteTimeRemaining / 10;
14020 /* [HGM] translate opponent's time by time-odds factor */
14021 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
14022 if (appData.debugMode) {
14023 fprintf(debugFP, "time odds: %f %f \n", cps->timeOdds, cps->other->timeOdds);
14026 if (time <= 0) time = 1;
14027 if (otime <= 0) otime = 1;
14029 snprintf(message, MSG_SIZ, "time %ld\n", time);
14030 SendToProgram(message, cps);
14032 snprintf(message, MSG_SIZ, "otim %ld\n", otime);
14033 SendToProgram(message, cps);
14037 BoolFeature(p, name, loc, cps)
14041 ChessProgramState *cps;
14044 int len = strlen(name);
14047 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
14049 sscanf(*p, "%d", &val);
14051 while (**p && **p != ' ')
14053 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
14054 SendToProgram(buf, cps);
14061 IntFeature(p, name, loc, cps)
14065 ChessProgramState *cps;
14068 int len = strlen(name);
14069 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
14071 sscanf(*p, "%d", loc);
14072 while (**p && **p != ' ') (*p)++;
14073 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
14074 SendToProgram(buf, cps);
14081 StringFeature(p, name, loc, cps)
14085 ChessProgramState *cps;
14088 int len = strlen(name);
14089 if (strncmp((*p), name, len) == 0
14090 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
14092 sscanf(*p, "%[^\"]", loc);
14093 while (**p && **p != '\"') (*p)++;
14094 if (**p == '\"') (*p)++;
14095 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
14096 SendToProgram(buf, cps);
14103 ParseOption(Option *opt, ChessProgramState *cps)
14104 // [HGM] options: process the string that defines an engine option, and determine
14105 // name, type, default value, and allowed value range
14107 char *p, *q, buf[MSG_SIZ];
14108 int n, min = (-1)<<31, max = 1<<31, def;
14110 if(p = strstr(opt->name, " -spin ")) {
14111 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
14112 if(max < min) max = min; // enforce consistency
14113 if(def < min) def = min;
14114 if(def > max) def = max;
14119 } else if((p = strstr(opt->name, " -slider "))) {
14120 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
14121 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
14122 if(max < min) max = min; // enforce consistency
14123 if(def < min) def = min;
14124 if(def > max) def = max;
14128 opt->type = Spin; // Slider;
14129 } else if((p = strstr(opt->name, " -string "))) {
14130 opt->textValue = p+9;
14131 opt->type = TextBox;
14132 } else if((p = strstr(opt->name, " -file "))) {
14133 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
14134 opt->textValue = p+7;
14135 opt->type = FileName; // FileName;
14136 } else if((p = strstr(opt->name, " -path "))) {
14137 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
14138 opt->textValue = p+7;
14139 opt->type = PathName; // PathName;
14140 } else if(p = strstr(opt->name, " -check ")) {
14141 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
14142 opt->value = (def != 0);
14143 opt->type = CheckBox;
14144 } else if(p = strstr(opt->name, " -combo ")) {
14145 opt->textValue = (char*) (&cps->comboList[cps->comboCnt]); // cheat with pointer type
14146 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
14147 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
14148 opt->value = n = 0;
14149 while(q = StrStr(q, " /// ")) {
14150 n++; *q = 0; // count choices, and null-terminate each of them
14152 if(*q == '*') { // remember default, which is marked with * prefix
14156 cps->comboList[cps->comboCnt++] = q;
14158 cps->comboList[cps->comboCnt++] = NULL;
14160 opt->type = ComboBox;
14161 } else if(p = strstr(opt->name, " -button")) {
14162 opt->type = Button;
14163 } else if(p = strstr(opt->name, " -save")) {
14164 opt->type = SaveButton;
14165 } else return FALSE;
14166 *p = 0; // terminate option name
14167 // now look if the command-line options define a setting for this engine option.
14168 if(cps->optionSettings && cps->optionSettings[0])
14169 p = strstr(cps->optionSettings, opt->name); else p = NULL;
14170 if(p && (p == cps->optionSettings || p[-1] == ',')) {
14171 snprintf(buf, MSG_SIZ, "option %s", p);
14172 if(p = strstr(buf, ",")) *p = 0;
14173 if(q = strchr(buf, '=')) switch(opt->type) {
14175 for(n=0; n<opt->max; n++)
14176 if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
14179 safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
14183 opt->value = atoi(q+1);
14188 SendToProgram(buf, cps);
14194 FeatureDone(cps, val)
14195 ChessProgramState* cps;
14198 DelayedEventCallback cb = GetDelayedEvent();
14199 if ((cb == InitBackEnd3 && cps == &first) ||
14200 (cb == SettingsMenuIfReady && cps == &second) ||
14201 (cb == LoadEngine) ||
14202 (cb == TwoMachinesEventIfReady && cps == &second)) {
14203 CancelDelayedEvent();
14204 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
14206 cps->initDone = val;
14209 /* Parse feature command from engine */
14211 ParseFeatures(args, cps)
14213 ChessProgramState *cps;
14221 while (*p == ' ') p++;
14222 if (*p == NULLCHAR) return;
14224 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
14225 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
14226 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
14227 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
14228 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
14229 if (BoolFeature(&p, "reuse", &val, cps)) {
14230 /* Engine can disable reuse, but can't enable it if user said no */
14231 if (!val) cps->reuse = FALSE;
14234 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
14235 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
14236 if (gameMode == TwoMachinesPlay) {
14237 DisplayTwoMachinesTitle();
14243 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
14244 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
14245 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
14246 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
14247 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
14248 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
14249 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
14250 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
14251 if (BoolFeature(&p, "pause", &val, cps)) continue; /* unused at present */
14252 if (IntFeature(&p, "done", &val, cps)) {
14253 FeatureDone(cps, val);
14256 /* Added by Tord: */
14257 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
14258 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
14259 /* End of additions by Tord */
14261 /* [HGM] added features: */
14262 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
14263 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
14264 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
14265 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
14266 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
14267 if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
14268 if (StringFeature(&p, "option", &(cps->option[cps->nrOptions].name), cps)) {
14269 if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
14270 snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
14271 SendToProgram(buf, cps);
14274 if(cps->nrOptions >= MAX_OPTIONS) {
14276 snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
14277 DisplayError(buf, 0);
14281 /* End of additions by HGM */
14283 /* unknown feature: complain and skip */
14285 while (*q && *q != '=') q++;
14286 snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
14287 SendToProgram(buf, cps);
14293 while (*p && *p != '\"') p++;
14294 if (*p == '\"') p++;
14296 while (*p && *p != ' ') p++;
14304 PeriodicUpdatesEvent(newState)
14307 if (newState == appData.periodicUpdates)
14310 appData.periodicUpdates=newState;
14312 /* Display type changes, so update it now */
14313 // DisplayAnalysis();
14315 /* Get the ball rolling again... */
14317 AnalysisPeriodicEvent(1);
14318 StartAnalysisClock();
14323 PonderNextMoveEvent(newState)
14326 if (newState == appData.ponderNextMove) return;
14327 if (gameMode == EditPosition) EditPositionDone(TRUE);
14329 SendToProgram("hard\n", &first);
14330 if (gameMode == TwoMachinesPlay) {
14331 SendToProgram("hard\n", &second);
14334 SendToProgram("easy\n", &first);
14335 thinkOutput[0] = NULLCHAR;
14336 if (gameMode == TwoMachinesPlay) {
14337 SendToProgram("easy\n", &second);
14340 appData.ponderNextMove = newState;
14344 NewSettingEvent(option, feature, command, value)
14346 int option, value, *feature;
14350 if (gameMode == EditPosition) EditPositionDone(TRUE);
14351 snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
14352 if(feature == NULL || *feature) SendToProgram(buf, &first);
14353 if (gameMode == TwoMachinesPlay) {
14354 if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
14359 ShowThinkingEvent()
14360 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
14362 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
14363 int newState = appData.showThinking
14364 // [HGM] thinking: other features now need thinking output as well
14365 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
14367 if (oldState == newState) return;
14368 oldState = newState;
14369 if (gameMode == EditPosition) EditPositionDone(TRUE);
14371 SendToProgram("post\n", &first);
14372 if (gameMode == TwoMachinesPlay) {
14373 SendToProgram("post\n", &second);
14376 SendToProgram("nopost\n", &first);
14377 thinkOutput[0] = NULLCHAR;
14378 if (gameMode == TwoMachinesPlay) {
14379 SendToProgram("nopost\n", &second);
14382 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
14386 AskQuestionEvent(title, question, replyPrefix, which)
14387 char *title; char *question; char *replyPrefix; char *which;
14389 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
14390 if (pr == NoProc) return;
14391 AskQuestion(title, question, replyPrefix, pr);
14395 TypeInEvent(char firstChar)
14397 if ((gameMode == BeginningOfGame && !appData.icsActive) ||
\r
14398 gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
\r
14399 gameMode == AnalyzeMode || gameMode == EditGame ||
\r
14400 gameMode == EditPosition || gameMode == IcsExamining ||
\r
14401 gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
\r
14402 isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
\r
14403 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
\r
14404 gameMode == IcsObserving || gameMode == TwoMachinesPlay ) ||
\r
14405 gameMode == Training) PopUpMoveDialog(firstChar);
14409 TypeInDoneEvent(char *move)
14412 int n, fromX, fromY, toX, toY;
14414 ChessMove moveType;
\r
14417 if(gameMode == EditPosition && ParseFEN(board, &n, move) ) {
\r
14418 EditPositionPasteFEN(move);
\r
14421 // [HGM] movenum: allow move number to be typed in any mode
\r
14422 if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
\r
14423 ToNrEvent(2*n-1);
\r
14427 if (gameMode != EditGame && currentMove != forwardMostMove &&
\r
14428 gameMode != Training) {
\r
14429 DisplayMoveError(_("Displayed move is not current"));
\r
14431 int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
\r
14432 &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
\r
14433 if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
\r
14434 if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
\r
14435 &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
\r
14436 UserMoveEvent(fromX, fromY, toX, toY, promoChar);
\r
14438 DisplayMoveError(_("Could not parse move"));
\r
14444 DisplayMove(moveNumber)
14447 char message[MSG_SIZ];
14449 char cpThinkOutput[MSG_SIZ];
14451 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
14453 if (moveNumber == forwardMostMove - 1 ||
14454 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14456 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
14458 if (strchr(cpThinkOutput, '\n')) {
14459 *strchr(cpThinkOutput, '\n') = NULLCHAR;
14462 *cpThinkOutput = NULLCHAR;
14465 /* [AS] Hide thinking from human user */
14466 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
14467 *cpThinkOutput = NULLCHAR;
14468 if( thinkOutput[0] != NULLCHAR ) {
14471 for( i=0; i<=hiddenThinkOutputState; i++ ) {
14472 cpThinkOutput[i] = '.';
14474 cpThinkOutput[i] = NULLCHAR;
14475 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
14479 if (moveNumber == forwardMostMove - 1 &&
14480 gameInfo.resultDetails != NULL) {
14481 if (gameInfo.resultDetails[0] == NULLCHAR) {
14482 snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
14484 snprintf(res, MSG_SIZ, " {%s} %s",
14485 T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
14491 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
14492 DisplayMessage(res, cpThinkOutput);
14494 snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
14495 WhiteOnMove(moveNumber) ? " " : ".. ",
14496 parseList[moveNumber], res);
14497 DisplayMessage(message, cpThinkOutput);
14502 DisplayComment(moveNumber, text)
14506 char title[MSG_SIZ];
14507 char buf[8000]; // comment can be long!
14510 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
14511 safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
14513 snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
14514 WhiteOnMove(moveNumber) ? " " : ".. ",
14515 parseList[moveNumber]);
14517 // [HGM] PV info: display PV info together with (or as) comment
14518 if(moveNumber >= 0 && (depth = pvInfoList[moveNumber].depth) > 0) {
14519 if(text == NULL) text = "";
14520 score = pvInfoList[moveNumber].score;
14521 snprintf(buf,sizeof(buf)/sizeof(buf[0]), "%s%.2f/%d %d\n%s", score>0 ? "+" : "", score/100.,
14522 depth, (pvInfoList[moveNumber].time+50)/100, text);
14525 if (text != NULL && (appData.autoDisplayComment || commentUp))
14526 CommentPopUp(title, text);
14529 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
14530 * might be busy thinking or pondering. It can be omitted if your
14531 * gnuchess is configured to stop thinking immediately on any user
14532 * input. However, that gnuchess feature depends on the FIONREAD
14533 * ioctl, which does not work properly on some flavors of Unix.
14537 ChessProgramState *cps;
14540 if (!cps->useSigint) return;
14541 if (appData.noChessProgram || (cps->pr == NoProc)) return;
14542 switch (gameMode) {
14543 case MachinePlaysWhite:
14544 case MachinePlaysBlack:
14545 case TwoMachinesPlay:
14546 case IcsPlayingWhite:
14547 case IcsPlayingBlack:
14550 /* Skip if we know it isn't thinking */
14551 if (!cps->maybeThinking) return;
14552 if (appData.debugMode)
14553 fprintf(debugFP, "Interrupting %s\n", cps->which);
14554 InterruptChildProcess(cps->pr);
14555 cps->maybeThinking = FALSE;
14560 #endif /*ATTENTION*/
14566 if (whiteTimeRemaining <= 0) {
14569 if (appData.icsActive) {
14570 if (appData.autoCallFlag &&
14571 gameMode == IcsPlayingBlack && !blackFlag) {
14572 SendToICS(ics_prefix);
14573 SendToICS("flag\n");
14577 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
14579 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
14580 if (appData.autoCallFlag) {
14581 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
14588 if (blackTimeRemaining <= 0) {
14591 if (appData.icsActive) {
14592 if (appData.autoCallFlag &&
14593 gameMode == IcsPlayingWhite && !whiteFlag) {
14594 SendToICS(ics_prefix);
14595 SendToICS("flag\n");
14599 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
14601 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
14602 if (appData.autoCallFlag) {
14603 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
14616 if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
14617 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
14620 * add time to clocks when time control is achieved ([HGM] now also used for increment)
14622 if ( !WhiteOnMove(forwardMostMove) ) {
14623 /* White made time control */
14624 lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
14625 whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
14626 /* [HGM] time odds: correct new time quota for time odds! */
14627 / WhitePlayer()->timeOdds;
14628 lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
14630 lastBlack -= blackTimeRemaining;
14631 /* Black made time control */
14632 blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
14633 / WhitePlayer()->other->timeOdds;
14634 lastWhite = whiteTimeRemaining;
14639 DisplayBothClocks()
14641 int wom = gameMode == EditPosition ?
14642 !blackPlaysFirst : WhiteOnMove(currentMove);
14643 DisplayWhiteClock(whiteTimeRemaining, wom);
14644 DisplayBlackClock(blackTimeRemaining, !wom);
14648 /* Timekeeping seems to be a portability nightmare. I think everyone
14649 has ftime(), but I'm really not sure, so I'm including some ifdefs
14650 to use other calls if you don't. Clocks will be less accurate if
14651 you have neither ftime nor gettimeofday.
14654 /* VS 2008 requires the #include outside of the function */
14655 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
14656 #include <sys/timeb.h>
14659 /* Get the current time as a TimeMark */
14664 #if HAVE_GETTIMEOFDAY
14666 struct timeval timeVal;
14667 struct timezone timeZone;
14669 gettimeofday(&timeVal, &timeZone);
14670 tm->sec = (long) timeVal.tv_sec;
14671 tm->ms = (int) (timeVal.tv_usec / 1000L);
14673 #else /*!HAVE_GETTIMEOFDAY*/
14676 // include <sys/timeb.h> / moved to just above start of function
14677 struct timeb timeB;
14680 tm->sec = (long) timeB.time;
14681 tm->ms = (int) timeB.millitm;
14683 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
14684 tm->sec = (long) time(NULL);
14690 /* Return the difference in milliseconds between two
14691 time marks. We assume the difference will fit in a long!
14694 SubtractTimeMarks(tm2, tm1)
14695 TimeMark *tm2, *tm1;
14697 return 1000L*(tm2->sec - tm1->sec) +
14698 (long) (tm2->ms - tm1->ms);
14703 * Code to manage the game clocks.
14705 * In tournament play, black starts the clock and then white makes a move.
14706 * We give the human user a slight advantage if he is playing white---the
14707 * clocks don't run until he makes his first move, so it takes zero time.
14708 * Also, we don't account for network lag, so we could get out of sync
14709 * with GNU Chess's clock -- but then, referees are always right.
14712 static TimeMark tickStartTM;
14713 static long intendedTickLength;
14716 NextTickLength(timeRemaining)
14717 long timeRemaining;
14719 long nominalTickLength, nextTickLength;
14721 if (timeRemaining > 0L && timeRemaining <= 10000L)
14722 nominalTickLength = 100L;
14724 nominalTickLength = 1000L;
14725 nextTickLength = timeRemaining % nominalTickLength;
14726 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
14728 return nextTickLength;
14731 /* Adjust clock one minute up or down */
14733 AdjustClock(Boolean which, int dir)
14735 if(which) blackTimeRemaining += 60000*dir;
14736 else whiteTimeRemaining += 60000*dir;
14737 DisplayBothClocks();
14740 /* Stop clocks and reset to a fresh time control */
14744 (void) StopClockTimer();
14745 if (appData.icsActive) {
14746 whiteTimeRemaining = blackTimeRemaining = 0;
14747 } else if (searchTime) {
14748 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
14749 blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
14750 } else { /* [HGM] correct new time quote for time odds */
14751 whiteTC = blackTC = fullTimeControlString;
14752 whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
14753 blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
14755 if (whiteFlag || blackFlag) {
14757 whiteFlag = blackFlag = FALSE;
14759 lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
14760 DisplayBothClocks();
14763 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
14765 /* Decrement running clock by amount of time that has passed */
14769 long timeRemaining;
14770 long lastTickLength, fudge;
14773 if (!appData.clockMode) return;
14774 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
14778 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14780 /* Fudge if we woke up a little too soon */
14781 fudge = intendedTickLength - lastTickLength;
14782 if (fudge < 0 || fudge > FUDGE) fudge = 0;
14784 if (WhiteOnMove(forwardMostMove)) {
14785 if(whiteNPS >= 0) lastTickLength = 0;
14786 timeRemaining = whiteTimeRemaining -= lastTickLength;
14787 if(timeRemaining < 0 && !appData.icsActive) {
14788 GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
14789 if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
14790 whiteStartMove = forwardMostMove; whiteTC = nextSession;
14791 lastWhite= timeRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
14794 DisplayWhiteClock(whiteTimeRemaining - fudge,
14795 WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
14797 if(blackNPS >= 0) lastTickLength = 0;
14798 timeRemaining = blackTimeRemaining -= lastTickLength;
14799 if(timeRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
14800 GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
14802 blackStartMove = forwardMostMove;
14803 lastBlack = timeRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
14806 DisplayBlackClock(blackTimeRemaining - fudge,
14807 !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
14809 if (CheckFlags()) return;
14812 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
14813 StartClockTimer(intendedTickLength);
14815 /* if the time remaining has fallen below the alarm threshold, sound the
14816 * alarm. if the alarm has sounded and (due to a takeback or time control
14817 * with increment) the time remaining has increased to a level above the
14818 * threshold, reset the alarm so it can sound again.
14821 if (appData.icsActive && appData.icsAlarm) {
14823 /* make sure we are dealing with the user's clock */
14824 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
14825 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
14828 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
14829 alarmSounded = FALSE;
14830 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
14832 alarmSounded = TRUE;
14838 /* A player has just moved, so stop the previously running
14839 clock and (if in clock mode) start the other one.
14840 We redisplay both clocks in case we're in ICS mode, because
14841 ICS gives us an update to both clocks after every move.
14842 Note that this routine is called *after* forwardMostMove
14843 is updated, so the last fractional tick must be subtracted
14844 from the color that is *not* on move now.
14847 SwitchClocks(int newMoveNr)
14849 long lastTickLength;
14851 int flagged = FALSE;
14855 if (StopClockTimer() && appData.clockMode) {
14856 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14857 if (!WhiteOnMove(forwardMostMove)) {
14858 if(blackNPS >= 0) lastTickLength = 0;
14859 blackTimeRemaining -= lastTickLength;
14860 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
14861 // if(pvInfoList[forwardMostMove].time == -1)
14862 pvInfoList[forwardMostMove].time = // use GUI time
14863 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
14865 if(whiteNPS >= 0) lastTickLength = 0;
14866 whiteTimeRemaining -= lastTickLength;
14867 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
14868 // if(pvInfoList[forwardMostMove].time == -1)
14869 pvInfoList[forwardMostMove].time =
14870 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
14872 flagged = CheckFlags();
14874 forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
14875 CheckTimeControl();
14877 if (flagged || !appData.clockMode) return;
14879 switch (gameMode) {
14880 case MachinePlaysBlack:
14881 case MachinePlaysWhite:
14882 case BeginningOfGame:
14883 if (pausing) return;
14887 case PlayFromGameFile:
14895 if (searchTime) { // [HGM] st: set clock of player that has to move to max time
14896 if(WhiteOnMove(forwardMostMove))
14897 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
14898 else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
14902 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
14903 whiteTimeRemaining : blackTimeRemaining);
14904 StartClockTimer(intendedTickLength);
14908 /* Stop both clocks */
14912 long lastTickLength;
14915 if (!StopClockTimer()) return;
14916 if (!appData.clockMode) return;
14920 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14921 if (WhiteOnMove(forwardMostMove)) {
14922 if(whiteNPS >= 0) lastTickLength = 0;
14923 whiteTimeRemaining -= lastTickLength;
14924 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
14926 if(blackNPS >= 0) lastTickLength = 0;
14927 blackTimeRemaining -= lastTickLength;
14928 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
14933 /* Start clock of player on move. Time may have been reset, so
14934 if clock is already running, stop and restart it. */
14938 (void) StopClockTimer(); /* in case it was running already */
14939 DisplayBothClocks();
14940 if (CheckFlags()) return;
14942 if (!appData.clockMode) return;
14943 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
14945 GetTimeMark(&tickStartTM);
14946 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
14947 whiteTimeRemaining : blackTimeRemaining);
14949 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
14950 whiteNPS = blackNPS = -1;
14951 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
14952 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
14953 whiteNPS = first.nps;
14954 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
14955 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
14956 blackNPS = first.nps;
14957 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
14958 whiteNPS = second.nps;
14959 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
14960 blackNPS = second.nps;
14961 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
14963 StartClockTimer(intendedTickLength);
14970 long second, minute, hour, day;
14972 static char buf[32];
14974 if (ms > 0 && ms <= 9900) {
14975 /* convert milliseconds to tenths, rounding up */
14976 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
14978 snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
14982 /* convert milliseconds to seconds, rounding up */
14983 /* use floating point to avoid strangeness of integer division
14984 with negative dividends on many machines */
14985 second = (long) floor(((double) (ms + 999L)) / 1000.0);
14992 day = second / (60 * 60 * 24);
14993 second = second % (60 * 60 * 24);
14994 hour = second / (60 * 60);
14995 second = second % (60 * 60);
14996 minute = second / 60;
14997 second = second % 60;
15000 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ",
15001 sign, day, hour, minute, second);
15003 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
15005 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second);
15012 * This is necessary because some C libraries aren't ANSI C compliant yet.
15015 StrStr(string, match)
15016 char *string, *match;
15020 length = strlen(match);
15022 for (i = strlen(string) - length; i >= 0; i--, string++)
15023 if (!strncmp(match, string, length))
15030 StrCaseStr(string, match)
15031 char *string, *match;
15035 length = strlen(match);
15037 for (i = strlen(string) - length; i >= 0; i--, string++) {
15038 for (j = 0; j < length; j++) {
15039 if (ToLower(match[j]) != ToLower(string[j]))
15042 if (j == length) return string;
15056 c1 = ToLower(*s1++);
15057 c2 = ToLower(*s2++);
15058 if (c1 > c2) return 1;
15059 if (c1 < c2) return -1;
15060 if (c1 == NULLCHAR) return 0;
15069 return isupper(c) ? tolower(c) : c;
15077 return islower(c) ? toupper(c) : c;
15079 #endif /* !_amigados */
15087 if ((ret = (char *) malloc(strlen(s) + 1)))
15089 safeStrCpy(ret, s, strlen(s)+1);
15095 StrSavePtr(s, savePtr)
15096 char *s, **savePtr;
15101 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
15102 safeStrCpy(*savePtr, s, strlen(s)+1);
15114 clock = time((time_t *)NULL);
15115 tm = localtime(&clock);
15116 snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
15117 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
15118 return StrSave(buf);
15123 PositionToFEN(move, overrideCastling)
15125 char *overrideCastling;
15127 int i, j, fromX, fromY, toX, toY;
15134 whiteToPlay = (gameMode == EditPosition) ?
15135 !blackPlaysFirst : (move % 2 == 0);
15138 /* Piece placement data */
15139 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
15141 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
15142 if (boards[move][i][j] == EmptySquare) {
15144 } else { ChessSquare piece = boards[move][i][j];
15145 if (emptycount > 0) {
15146 if(emptycount<10) /* [HGM] can be >= 10 */
15147 *p++ = '0' + emptycount;
15148 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
15151 if(PieceToChar(piece) == '+') {
15152 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
15154 piece = (ChessSquare)(DEMOTED piece);
15156 *p++ = PieceToChar(piece);
15158 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
15159 p[-1] = PieceToChar((ChessSquare)(DEMOTED piece));
15164 if (emptycount > 0) {
15165 if(emptycount<10) /* [HGM] can be >= 10 */
15166 *p++ = '0' + emptycount;
15167 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
15174 /* [HGM] print Crazyhouse or Shogi holdings */
15175 if( gameInfo.holdingsWidth ) {
15176 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
15178 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
15179 piece = boards[move][i][BOARD_WIDTH-1];
15180 if( piece != EmptySquare )
15181 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
15182 *p++ = PieceToChar(piece);
15184 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
15185 piece = boards[move][BOARD_HEIGHT-i-1][0];
15186 if( piece != EmptySquare )
15187 for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
15188 *p++ = PieceToChar(piece);
15191 if( q == p ) *p++ = '-';
15197 *p++ = whiteToPlay ? 'w' : 'b';
15200 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
15201 while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' '; else --p;
15203 if(nrCastlingRights) {
15205 if(gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) {
15206 /* [HGM] write directly from rights */
15207 if(boards[move][CASTLING][2] != NoRights &&
15208 boards[move][CASTLING][0] != NoRights )
15209 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
15210 if(boards[move][CASTLING][2] != NoRights &&
15211 boards[move][CASTLING][1] != NoRights )
15212 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
15213 if(boards[move][CASTLING][5] != NoRights &&
15214 boards[move][CASTLING][3] != NoRights )
15215 *p++ = boards[move][CASTLING][3] + AAA;
15216 if(boards[move][CASTLING][5] != NoRights &&
15217 boards[move][CASTLING][4] != NoRights )
15218 *p++ = boards[move][CASTLING][4] + AAA;
15221 /* [HGM] write true castling rights */
15222 if( nrCastlingRights == 6 ) {
15223 if(boards[move][CASTLING][0] == BOARD_RGHT-1 &&
15224 boards[move][CASTLING][2] != NoRights ) *p++ = 'K';
15225 if(boards[move][CASTLING][1] == BOARD_LEFT &&
15226 boards[move][CASTLING][2] != NoRights ) *p++ = 'Q';
15227 if(boards[move][CASTLING][3] == BOARD_RGHT-1 &&
15228 boards[move][CASTLING][5] != NoRights ) *p++ = 'k';
15229 if(boards[move][CASTLING][4] == BOARD_LEFT &&
15230 boards[move][CASTLING][5] != NoRights ) *p++ = 'q';
15233 if (q == p) *p++ = '-'; /* No castling rights */
15237 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
15238 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
15239 /* En passant target square */
15240 if (move > backwardMostMove) {
15241 fromX = moveList[move - 1][0] - AAA;
15242 fromY = moveList[move - 1][1] - ONE;
15243 toX = moveList[move - 1][2] - AAA;
15244 toY = moveList[move - 1][3] - ONE;
15245 if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
15246 toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
15247 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
15249 /* 2-square pawn move just happened */
15251 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
15255 } else if(move == backwardMostMove) {
15256 // [HGM] perhaps we should always do it like this, and forget the above?
15257 if((signed char)boards[move][EP_STATUS] >= 0) {
15258 *p++ = boards[move][EP_STATUS] + AAA;
15259 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
15270 /* [HGM] find reversible plies */
15271 { int i = 0, j=move;
15273 if (appData.debugMode) { int k;
15274 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
15275 for(k=backwardMostMove; k<=forwardMostMove; k++)
15276 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
15280 while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
15281 if( j == backwardMostMove ) i += initialRulePlies;
15282 sprintf(p, "%d ", i);
15283 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
15285 /* Fullmove number */
15286 sprintf(p, "%d", (move / 2) + 1);
15288 return StrSave(buf);
15292 ParseFEN(board, blackPlaysFirst, fen)
15294 int *blackPlaysFirst;
15304 /* [HGM] by default clear Crazyhouse holdings, if present */
15305 if(gameInfo.holdingsWidth) {
15306 for(i=0; i<BOARD_HEIGHT; i++) {
15307 board[i][0] = EmptySquare; /* black holdings */
15308 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
15309 board[i][1] = (ChessSquare) 0; /* black counts */
15310 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
15314 /* Piece placement data */
15315 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
15318 if (*p == '/' || *p == ' ' || (*p == '[' && i == 0) ) {
15319 if (*p == '/') p++;
15320 emptycount = gameInfo.boardWidth - j;
15321 while (emptycount--)
15322 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
15324 #if(BOARD_FILES >= 10)
15325 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
15326 p++; emptycount=10;
15327 if (j + emptycount > gameInfo.boardWidth) return FALSE;
15328 while (emptycount--)
15329 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
15331 } else if (isdigit(*p)) {
15332 emptycount = *p++ - '0';
15333 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
15334 if (j + emptycount > gameInfo.boardWidth) return FALSE;
15335 while (emptycount--)
15336 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
15337 } else if (*p == '+' || isalpha(*p)) {
15338 if (j >= gameInfo.boardWidth) return FALSE;
15340 piece = CharToPiece(*++p);
15341 if(piece == EmptySquare) return FALSE; /* unknown piece */
15342 piece = (ChessSquare) (PROMOTED piece ); p++;
15343 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
15344 } else piece = CharToPiece(*p++);
15346 if(piece==EmptySquare) return FALSE; /* unknown piece */
15347 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
15348 piece = (ChessSquare) (PROMOTED piece);
15349 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
15352 board[i][(j++)+gameInfo.holdingsWidth] = piece;
15358 while (*p == '/' || *p == ' ') p++;
15360 /* [HGM] look for Crazyhouse holdings here */
15361 while(*p==' ') p++;
15362 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
15364 if(*p == '-' ) p++; /* empty holdings */ else {
15365 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
15366 /* if we would allow FEN reading to set board size, we would */
15367 /* have to add holdings and shift the board read so far here */
15368 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
15370 if((int) piece >= (int) BlackPawn ) {
15371 i = (int)piece - (int)BlackPawn;
15372 i = PieceToNumber((ChessSquare)i);
15373 if( i >= gameInfo.holdingsSize ) return FALSE;
15374 board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
15375 board[BOARD_HEIGHT-1-i][1]++; /* black counts */
15377 i = (int)piece - (int)WhitePawn;
15378 i = PieceToNumber((ChessSquare)i);
15379 if( i >= gameInfo.holdingsSize ) return FALSE;
15380 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
15381 board[i][BOARD_WIDTH-2]++; /* black holdings */
15388 while(*p == ' ') p++;
15392 if(appData.colorNickNames) {
15393 if( c == appData.colorNickNames[0] ) c = 'w'; else
15394 if( c == appData.colorNickNames[1] ) c = 'b';
15398 *blackPlaysFirst = FALSE;
15401 *blackPlaysFirst = TRUE;
15407 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
15408 /* return the extra info in global variiables */
15410 /* set defaults in case FEN is incomplete */
15411 board[EP_STATUS] = EP_UNKNOWN;
15412 for(i=0; i<nrCastlingRights; i++ ) {
15413 board[CASTLING][i] =
15414 gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom ? NoRights : initialRights[i];
15415 } /* assume possible unless obviously impossible */
15416 if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
15417 if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
15418 if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
15419 && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
15420 if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
15421 if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
15422 if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
15423 && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
15426 while(*p==' ') p++;
15427 if(nrCastlingRights) {
15428 if(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-') {
15429 /* castling indicator present, so default becomes no castlings */
15430 for(i=0; i<nrCastlingRights; i++ ) {
15431 board[CASTLING][i] = NoRights;
15434 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
15435 (gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) &&
15436 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
15437 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
15438 char c = *p++; int whiteKingFile=NoRights, blackKingFile=NoRights;
15440 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
15441 if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
15442 if(board[0 ][i] == WhiteKing) whiteKingFile = i;
15444 if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
15445 whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
15446 if(whiteKingFile == NoRights || board[0][whiteKingFile] != WhiteUnicorn
15447 && board[0][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
15448 if(blackKingFile == NoRights || board[BOARD_HEIGHT-1][blackKingFile] != BlackUnicorn
15449 && board[BOARD_HEIGHT-1][blackKingFile] != BlackKing) blackKingFile = NoRights;
15452 for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
15453 board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
15454 board[CASTLING][2] = whiteKingFile;
15457 for(i=BOARD_LEFT; i<BOARD_RGHT && board[0][i]!=WhiteRook && i<whiteKingFile; i++);
15458 board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
15459 board[CASTLING][2] = whiteKingFile;
15462 for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
15463 board[CASTLING][3] = i != blackKingFile ? i : NoRights;
15464 board[CASTLING][5] = blackKingFile;
15467 for(i=BOARD_LEFT; i<BOARD_RGHT && board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
15468 board[CASTLING][4] = i != blackKingFile ? i : NoRights;
15469 board[CASTLING][5] = blackKingFile;
15472 default: /* FRC castlings */
15473 if(c >= 'a') { /* black rights */
15474 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
15475 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
15476 if(i == BOARD_RGHT) break;
15477 board[CASTLING][5] = i;
15479 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
15480 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
15482 board[CASTLING][3] = c;
15484 board[CASTLING][4] = c;
15485 } else { /* white rights */
15486 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
15487 if(board[0][i] == WhiteKing) break;
15488 if(i == BOARD_RGHT) break;
15489 board[CASTLING][2] = i;
15490 c -= AAA - 'a' + 'A';
15491 if(board[0][c] >= WhiteKing) break;
15493 board[CASTLING][0] = c;
15495 board[CASTLING][1] = c;
15499 for(i=0; i<nrCastlingRights; i++)
15500 if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
15501 if (appData.debugMode) {
15502 fprintf(debugFP, "FEN castling rights:");
15503 for(i=0; i<nrCastlingRights; i++)
15504 fprintf(debugFP, " %d", board[CASTLING][i]);
15505 fprintf(debugFP, "\n");
15508 while(*p==' ') p++;
15511 /* read e.p. field in games that know e.p. capture */
15512 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
15513 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
15515 p++; board[EP_STATUS] = EP_NONE;
15517 char c = *p++ - AAA;
15519 if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
15520 if(*p >= '0' && *p <='9') p++;
15521 board[EP_STATUS] = c;
15526 if(sscanf(p, "%d", &i) == 1) {
15527 FENrulePlies = i; /* 50-move ply counter */
15528 /* (The move number is still ignored) */
15535 EditPositionPasteFEN(char *fen)
15538 Board initial_position;
15540 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
15541 DisplayError(_("Bad FEN position in clipboard"), 0);
15544 int savedBlackPlaysFirst = blackPlaysFirst;
15545 EditPositionEvent();
15546 blackPlaysFirst = savedBlackPlaysFirst;
15547 CopyBoard(boards[0], initial_position);
15548 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
15549 EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
15550 DisplayBothClocks();
15551 DrawPosition(FALSE, boards[currentMove]);
15556 static char cseq[12] = "\\ ";
15558 Boolean set_cont_sequence(char *new_seq)
15563 // handle bad attempts to set the sequence
15565 return 0; // acceptable error - no debug
15567 len = strlen(new_seq);
15568 ret = (len > 0) && (len < sizeof(cseq));
15570 safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
15571 else if (appData.debugMode)
15572 fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
15577 reformat a source message so words don't cross the width boundary. internal
15578 newlines are not removed. returns the wrapped size (no null character unless
15579 included in source message). If dest is NULL, only calculate the size required
15580 for the dest buffer. lp argument indicats line position upon entry, and it's
15581 passed back upon exit.
15583 int wrap(char *dest, char *src, int count, int width, int *lp)
15585 int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
15587 cseq_len = strlen(cseq);
15588 old_line = line = *lp;
15589 ansi = len = clen = 0;
15591 for (i=0; i < count; i++)
15593 if (src[i] == '\033')
15596 // if we hit the width, back up
15597 if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
15599 // store i & len in case the word is too long
15600 old_i = i, old_len = len;
15602 // find the end of the last word
15603 while (i && src[i] != ' ' && src[i] != '\n')
15609 // word too long? restore i & len before splitting it
15610 if ((old_i-i+clen) >= width)
15617 if (i && src[i-1] == ' ')
15620 if (src[i] != ' ' && src[i] != '\n')
15627 // now append the newline and continuation sequence
15632 strncpy(dest+len, cseq, cseq_len);
15640 dest[len] = src[i];
15644 if (src[i] == '\n')
15649 if (dest && appData.debugMode)
15651 fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
15652 count, width, line, len, *lp);
15653 show_bytes(debugFP, src, count);
15654 fprintf(debugFP, "\ndest: ");
15655 show_bytes(debugFP, dest, len);
15656 fprintf(debugFP, "\n");
15658 *lp = dest ? line : old_line;
15663 // [HGM] vari: routines for shelving variations
15666 PushTail(int firstMove, int lastMove)
15668 int i, j, nrMoves = lastMove - firstMove;
15670 if(appData.icsActive) { // only in local mode
15671 forwardMostMove = currentMove; // mimic old ICS behavior
15674 if(storedGames >= MAX_VARIATIONS-1) return;
15676 // push current tail of game on stack
15677 savedResult[storedGames] = gameInfo.result;
15678 savedDetails[storedGames] = gameInfo.resultDetails;
15679 gameInfo.resultDetails = NULL;
15680 savedFirst[storedGames] = firstMove;
15681 savedLast [storedGames] = lastMove;
15682 savedFramePtr[storedGames] = framePtr;
15683 framePtr -= nrMoves; // reserve space for the boards
15684 for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
15685 CopyBoard(boards[framePtr+i], boards[firstMove+i]);
15686 for(j=0; j<MOVE_LEN; j++)
15687 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
15688 for(j=0; j<2*MOVE_LEN; j++)
15689 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
15690 timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
15691 timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
15692 pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
15693 pvInfoList[firstMove+i-1].depth = 0;
15694 commentList[framePtr+i] = commentList[firstMove+i];
15695 commentList[firstMove+i] = NULL;
15699 forwardMostMove = firstMove; // truncate game so we can start variation
15700 if(storedGames == 1) GreyRevert(FALSE);
15704 PopTail(Boolean annotate)
15707 char buf[8000], moveBuf[20];
15709 if(appData.icsActive) return FALSE; // only in local mode
15710 if(!storedGames) return FALSE; // sanity
15711 CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
15714 ToNrEvent(savedFirst[storedGames]); // sets currentMove
15715 nrMoves = savedLast[storedGames] - currentMove;
15718 if(!WhiteOnMove(currentMove))
15719 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
15720 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
15721 for(i=currentMove; i<forwardMostMove; i++) {
15723 snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
15724 else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
15725 strcat(buf, moveBuf);
15726 if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
15727 if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
15731 for(i=1; i<=nrMoves; i++) { // copy last variation back
15732 CopyBoard(boards[currentMove+i], boards[framePtr+i]);
15733 for(j=0; j<MOVE_LEN; j++)
15734 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
15735 for(j=0; j<2*MOVE_LEN; j++)
15736 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
15737 timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
15738 timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
15739 pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
15740 if(commentList[currentMove+i]) free(commentList[currentMove+i]);
15741 commentList[currentMove+i] = commentList[framePtr+i];
15742 commentList[framePtr+i] = NULL;
15744 if(annotate) AppendComment(currentMove+1, buf, FALSE);
15745 framePtr = savedFramePtr[storedGames];
15746 gameInfo.result = savedResult[storedGames];
15747 if(gameInfo.resultDetails != NULL) {
15748 free(gameInfo.resultDetails);
15750 gameInfo.resultDetails = savedDetails[storedGames];
15751 forwardMostMove = currentMove + nrMoves;
15752 if(storedGames == 0) GreyRevert(TRUE);
15758 { // remove all shelved variations
15760 for(i=0; i<storedGames; i++) {
15761 if(savedDetails[i])
15762 free(savedDetails[i]);
15763 savedDetails[i] = NULL;
15765 for(i=framePtr; i<MAX_MOVES; i++) {
15766 if(commentList[i]) free(commentList[i]);
15767 commentList[i] = NULL;
15769 framePtr = MAX_MOVES-1;
15774 LoadVariation(int index, char *text)
15775 { // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
15776 char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
15777 int level = 0, move;
15779 if(gameMode != EditGame && gameMode != AnalyzeMode) return;
15780 // first find outermost bracketing variation
15781 while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
15782 if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
15783 if(*p == '{') wait = '}'; else
15784 if(*p == '[') wait = ']'; else
15785 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
15786 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
15788 if(*p == wait) wait = NULLCHAR; // closing ]} found
15791 if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
15792 if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
15793 end[1] = NULLCHAR; // clip off comment beyond variation
15794 ToNrEvent(currentMove-1);
15795 PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
15796 // kludge: use ParsePV() to append variation to game
15797 move = currentMove;
15798 ParsePV(start, TRUE);
15799 forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
15800 ClearPremoveHighlights();
15802 ToNrEvent(currentMove+1);