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) );
62 #define DoSleep( n ) if( (n) >= 0) sleep(n)
72 #include <sys/types.h>
81 #else /* not STDC_HEADERS */
84 # else /* not HAVE_STRING_H */
86 # endif /* not HAVE_STRING_H */
87 #endif /* not STDC_HEADERS */
90 # include <sys/fcntl.h>
91 #else /* not HAVE_SYS_FCNTL_H */
94 # endif /* HAVE_FCNTL_H */
95 #endif /* not HAVE_SYS_FCNTL_H */
97 #if TIME_WITH_SYS_TIME
98 # include <sys/time.h>
102 # include <sys/time.h>
108 #if defined(_amigados) && !defined(__GNUC__)
113 extern int gettimeofday(struct timeval *, struct timezone *);
121 #include "frontend.h"
128 #include "backendz.h"
132 # define _(s) gettext (s)
133 # define N_(s) gettext_noop (s)
134 # define T_(s) gettext(s)
147 /* A point in time */
149 long sec; /* Assuming this is >= 32 bits */
150 int ms; /* Assuming this is >= 16 bits */
153 int establish P((void));
154 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
155 char *buf, int count, int error));
156 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
157 char *buf, int count, int error));
158 void ics_printf P((char *format, ...));
159 void SendToICS P((char *s));
160 void SendToICSDelayed P((char *s, long msdelay));
161 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar));
162 void HandleMachineMove P((char *message, ChessProgramState *cps));
163 int AutoPlayOneMove P((void));
164 int LoadGameOneMove P((ChessMove readAhead));
165 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
166 int LoadPositionFromFile P((char *filename, int n, char *title));
167 int SavePositionToFile P((char *filename));
168 void ApplyMove P((int fromX, int fromY, int toX, int toY, int promoChar,
170 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
171 void ShowMove P((int fromX, int fromY, int toX, int toY));
172 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
173 /*char*/int promoChar));
174 void BackwardInner P((int target));
175 void ForwardInner P((int target));
176 int Adjudicate P((ChessProgramState *cps));
177 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
178 void EditPositionDone P((Boolean fakeRights));
179 void PrintOpponents P((FILE *fp));
180 void PrintPosition P((FILE *fp, int move));
181 void StartChessProgram P((ChessProgramState *cps));
182 void SendToProgram P((char *message, ChessProgramState *cps));
183 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
184 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
185 char *buf, int count, int error));
186 void SendTimeControl P((ChessProgramState *cps,
187 int mps, long tc, int inc, int sd, int st));
188 char *TimeControlTagValue P((void));
189 void Attention P((ChessProgramState *cps));
190 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
191 void ResurrectChessProgram P((void));
192 void DisplayComment P((int moveNumber, char *text));
193 void DisplayMove P((int moveNumber));
195 void ParseGameHistory P((char *game));
196 void ParseBoard12 P((char *string));
197 void KeepAlive P((void));
198 void StartClocks P((void));
199 void SwitchClocks P((int nr));
200 void StopClocks P((void));
201 void ResetClocks P((void));
202 char *PGNDate P((void));
203 void SetGameInfo P((void));
204 Boolean ParseFEN P((Board board, int *blackPlaysFirst, char *fen));
205 int RegisterMove P((void));
206 void MakeRegisteredMove P((void));
207 void TruncateGame P((void));
208 int looking_at P((char *, int *, char *));
209 void CopyPlayerNameIntoFileName P((char **, char *));
210 char *SavePart P((char *));
211 int SaveGameOldStyle P((FILE *));
212 int SaveGamePGN P((FILE *));
213 void GetTimeMark P((TimeMark *));
214 long SubtractTimeMarks P((TimeMark *, TimeMark *));
215 int CheckFlags P((void));
216 long NextTickLength P((long));
217 void CheckTimeControl P((void));
218 void show_bytes P((FILE *, char *, int));
219 int string_to_rating P((char *str));
220 void ParseFeatures P((char* args, ChessProgramState *cps));
221 void InitBackEnd3 P((void));
222 void FeatureDone P((ChessProgramState* cps, int val));
223 void InitChessProgram P((ChessProgramState *cps, int setup));
224 void OutputKibitz(int window, char *text);
225 int PerpetualChase(int first, int last);
226 int EngineOutputIsUp();
227 void InitDrawingSizes(int x, int y);
230 extern void ConsoleCreate();
233 ChessProgramState *WhitePlayer();
234 void InsertIntoMemo P((int which, char *text)); // [HGM] kibitz: in engineo.c
235 int VerifyDisplayMode P(());
237 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
238 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
239 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
240 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
241 void ics_update_width P((int new_width));
242 extern char installDir[MSG_SIZ];
243 VariantClass startVariant; /* [HGM] nicks: initial variant */
245 extern int tinyLayout, smallLayout;
246 ChessProgramStats programStats;
247 char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
249 static int exiting = 0; /* [HGM] moved to top */
250 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
251 int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
252 Board partnerBoard; /* [HGM] bughouse: for peeking at partner game */
253 int partnerHighlight[2];
254 Boolean partnerBoardValid = 0;
255 char partnerStatus[MSG_SIZ];
257 Boolean originalFlip;
258 Boolean twoBoards = 0;
259 char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
260 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
261 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
262 int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
263 Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing */
264 int opponentKibitzes;
265 int lastSavedGame; /* [HGM] save: ID of game */
266 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
267 extern int chatCount;
269 char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
270 ChessSquare pieceSweep = EmptySquare;
271 ChessSquare promoSweep = EmptySquare, defaultPromoChoice;
272 int promoDefaultAltered;
274 /* States for ics_getting_history */
276 #define H_REQUESTED 1
277 #define H_GOT_REQ_HEADER 2
278 #define H_GOT_UNREQ_HEADER 3
279 #define H_GETTING_MOVES 4
280 #define H_GOT_UNWANTED_HEADER 5
282 /* whosays values for GameEnds */
291 /* Maximum number of games in a cmail message */
292 #define CMAIL_MAX_GAMES 20
294 /* Different types of move when calling RegisterMove */
296 #define CMAIL_RESIGN 1
298 #define CMAIL_ACCEPT 3
300 /* Different types of result to remember for each game */
301 #define CMAIL_NOT_RESULT 0
302 #define CMAIL_OLD_RESULT 1
303 #define CMAIL_NEW_RESULT 2
305 /* Telnet protocol constants */
316 safeStrCpy( char *dst, const char *src, size_t count )
319 assert( dst != NULL );
320 assert( src != NULL );
323 for(i=0; i<count; i++) if((dst[i] = src[i]) == NULLCHAR) break;
324 if( i == count && dst[count-1] != NULLCHAR)
326 dst[ count-1 ] = '\0'; // make sure incomplete copy still null-terminated
327 if(appData.debugMode)
328 fprintf(debugFP, "safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst,count);
334 /* Some compiler can't cast u64 to double
335 * This function do the job for us:
337 * We use the highest bit for cast, this only
338 * works if the highest bit is not
339 * in use (This should not happen)
341 * We used this for all compiler
344 u64ToDouble(u64 value)
347 u64 tmp = value & u64Const(0x7fffffffffffffff);
348 r = (double)(s64)tmp;
349 if (value & u64Const(0x8000000000000000))
350 r += 9.2233720368547758080e18; /* 2^63 */
354 /* Fake up flags for now, as we aren't keeping track of castling
355 availability yet. [HGM] Change of logic: the flag now only
356 indicates the type of castlings allowed by the rule of the game.
357 The actual rights themselves are maintained in the array
358 castlingRights, as part of the game history, and are not probed
364 int flags = F_ALL_CASTLE_OK;
365 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
366 switch (gameInfo.variant) {
368 flags &= ~F_ALL_CASTLE_OK;
369 case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
370 flags |= F_IGNORE_CHECK;
372 flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
375 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
377 case VariantKriegspiel:
378 flags |= F_KRIEGSPIEL_CAPTURE;
380 case VariantCapaRandom:
381 case VariantFischeRandom:
382 flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
383 case VariantNoCastle:
384 case VariantShatranj:
387 flags &= ~F_ALL_CASTLE_OK;
395 FILE *gameFileFP, *debugFP;
398 [AS] Note: sometimes, the sscanf() function is used to parse the input
399 into a fixed-size buffer. Because of this, we must be prepared to
400 receive strings as long as the size of the input buffer, which is currently
401 set to 4K for Windows and 8K for the rest.
402 So, we must either allocate sufficiently large buffers here, or
403 reduce the size of the input buffer in the input reading part.
406 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
407 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
408 char thinkOutput1[MSG_SIZ*10];
410 ChessProgramState first, second;
412 /* premove variables */
415 int premoveFromX = 0;
416 int premoveFromY = 0;
417 int premovePromoChar = 0;
419 Boolean alarmSounded;
420 /* end premove variables */
422 char *ics_prefix = "$";
423 int ics_type = ICS_GENERIC;
425 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
426 int pauseExamForwardMostMove = 0;
427 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
428 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
429 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
430 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
431 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
432 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
433 int whiteFlag = FALSE, blackFlag = FALSE;
434 int userOfferedDraw = FALSE;
435 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
436 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
437 int cmailMoveType[CMAIL_MAX_GAMES];
438 long ics_clock_paused = 0;
439 ProcRef icsPR = NoProc, cmailPR = NoProc;
440 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
441 GameMode gameMode = BeginningOfGame;
442 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
443 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
444 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
445 int hiddenThinkOutputState = 0; /* [AS] */
446 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
447 int adjudicateLossPlies = 6;
448 char white_holding[64], black_holding[64];
449 TimeMark lastNodeCountTime;
450 long lastNodeCount=0;
451 int shiftKey; // [HGM] set by mouse handler
453 int have_sent_ICS_logon = 0;
455 int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
456 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack;
457 long timeControl_2; /* [AS] Allow separate time controls */
458 char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC; /* [HGM] secondary TC: merge of MPS, TC and inc */
459 long timeRemaining[2][MAX_MOVES];
461 TimeMark programStartTime;
462 char ics_handle[MSG_SIZ];
463 int have_set_title = 0;
465 /* animateTraining preserves the state of appData.animate
466 * when Training mode is activated. This allows the
467 * response to be animated when appData.animate == TRUE and
468 * appData.animateDragging == TRUE.
470 Boolean animateTraining;
476 Board boards[MAX_MOVES];
477 /* [HGM] Following 7 needed for accurate legality tests: */
478 signed char castlingRank[BOARD_FILES]; // and corresponding ranks
479 signed char initialRights[BOARD_FILES];
480 int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
481 int initialRulePlies, FENrulePlies;
482 FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
485 int mute; // mute all sounds
487 // [HGM] vari: next 12 to save and restore variations
488 #define MAX_VARIATIONS 10
489 int framePtr = MAX_MOVES-1; // points to free stack entry
491 int savedFirst[MAX_VARIATIONS];
492 int savedLast[MAX_VARIATIONS];
493 int savedFramePtr[MAX_VARIATIONS];
494 char *savedDetails[MAX_VARIATIONS];
495 ChessMove savedResult[MAX_VARIATIONS];
497 void PushTail P((int firstMove, int lastMove));
498 Boolean PopTail P((Boolean annotate));
499 void CleanupTail P((void));
501 ChessSquare FIDEArray[2][BOARD_FILES] = {
502 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
503 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
504 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
505 BlackKing, BlackBishop, BlackKnight, BlackRook }
508 ChessSquare twoKingsArray[2][BOARD_FILES] = {
509 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
510 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
511 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
512 BlackKing, BlackKing, BlackKnight, BlackRook }
515 ChessSquare KnightmateArray[2][BOARD_FILES] = {
516 { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
517 WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
518 { BlackRook, BlackMan, BlackBishop, BlackQueen,
519 BlackUnicorn, BlackBishop, BlackMan, BlackRook }
522 ChessSquare SpartanArray[2][BOARD_FILES] = {
523 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
524 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
525 { BlackAlfil, BlackMarshall, BlackKing, BlackDragon,
526 BlackDragon, BlackKing, BlackAngel, BlackAlfil }
529 ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
530 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
531 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
532 { BlackCardinal, BlackAlfil, BlackMarshall, BlackAngel,
533 BlackKing, BlackMarshall, BlackAlfil, BlackCardinal }
536 ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
537 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
538 WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
539 { BlackRook, BlackKnight, BlackAlfil, BlackKing,
540 BlackFerz, BlackAlfil, BlackKnight, BlackRook }
543 ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
544 { WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
545 WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
546 { BlackRook, BlackKnight, BlackMan, BlackFerz,
547 BlackKing, BlackMan, BlackKnight, BlackRook }
551 #if (BOARD_FILES>=10)
552 ChessSquare ShogiArray[2][BOARD_FILES] = {
553 { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
554 WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
555 { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
556 BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
559 ChessSquare XiangqiArray[2][BOARD_FILES] = {
560 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
561 WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
562 { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
563 BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
566 ChessSquare CapablancaArray[2][BOARD_FILES] = {
567 { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
568 WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
569 { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
570 BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
573 ChessSquare GreatArray[2][BOARD_FILES] = {
574 { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
575 WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
576 { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
577 BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
580 ChessSquare JanusArray[2][BOARD_FILES] = {
581 { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
582 WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
583 { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
584 BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
588 ChessSquare GothicArray[2][BOARD_FILES] = {
589 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
590 WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
591 { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
592 BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
595 #define GothicArray CapablancaArray
599 ChessSquare FalconArray[2][BOARD_FILES] = {
600 { WhiteRook, WhiteKnight, WhiteBishop, WhiteLance, WhiteQueen,
601 WhiteKing, WhiteLance, WhiteBishop, WhiteKnight, WhiteRook },
602 { BlackRook, BlackKnight, BlackBishop, BlackLance, BlackQueen,
603 BlackKing, BlackLance, BlackBishop, BlackKnight, BlackRook }
606 #define FalconArray CapablancaArray
609 #else // !(BOARD_FILES>=10)
610 #define XiangqiPosition FIDEArray
611 #define CapablancaArray FIDEArray
612 #define GothicArray FIDEArray
613 #define GreatArray FIDEArray
614 #endif // !(BOARD_FILES>=10)
616 #if (BOARD_FILES>=12)
617 ChessSquare CourierArray[2][BOARD_FILES] = {
618 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
619 WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
620 { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
621 BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
623 #else // !(BOARD_FILES>=12)
624 #define CourierArray CapablancaArray
625 #endif // !(BOARD_FILES>=12)
628 Board initialPosition;
631 /* Convert str to a rating. Checks for special cases of "----",
633 "++++", etc. Also strips ()'s */
635 string_to_rating(str)
638 while(*str && !isdigit(*str)) ++str;
640 return 0; /* One of the special "no rating" cases */
648 /* Init programStats */
649 programStats.movelist[0] = 0;
650 programStats.depth = 0;
651 programStats.nr_moves = 0;
652 programStats.moves_left = 0;
653 programStats.nodes = 0;
654 programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
655 programStats.score = 0;
656 programStats.got_only_move = 0;
657 programStats.got_fail = 0;
658 programStats.line_is_book = 0;
663 { // [HGM] moved some code here from InitBackend1 that has to be done after both engines have contributed their settings
664 if (appData.firstPlaysBlack) {
665 first.twoMachinesColor = "black\n";
666 second.twoMachinesColor = "white\n";
668 first.twoMachinesColor = "white\n";
669 second.twoMachinesColor = "black\n";
672 first.other = &second;
673 second.other = &first;
676 if(appData.timeOddsMode) {
677 norm = appData.timeOdds[0];
678 if(norm > appData.timeOdds[1]) norm = appData.timeOdds[1];
680 first.timeOdds = appData.timeOdds[0]/norm;
681 second.timeOdds = appData.timeOdds[1]/norm;
684 if(programVersion) free(programVersion);
685 if (appData.noChessProgram) {
686 programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
687 sprintf(programVersion, "%s", PACKAGE_STRING);
689 /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
690 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
691 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
696 ClearOptions(ChessProgramState *cps)
699 cps->nrOptions = cps->comboCnt = 0;
700 for(i=0; i<MAX_OPTIONS; i++) {
701 cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
702 cps->option[i].textValue = 0;
706 char *engineNames[] = {
711 InitEngine(ChessProgramState *cps, int n)
712 { // [HGM] all engine initialiation put in a function that does one engine
716 cps->which = engineNames[n];
717 cps->maybeThinking = FALSE;
721 cps->sendDrawOffers = 1;
723 cps->program = appData.chessProgram[n];
724 cps->host = appData.host[n];
725 cps->dir = appData.directory[n];
726 cps->initString = appData.engInitString[n];
727 cps->computerString = appData.computerString[n];
728 cps->useSigint = TRUE;
729 cps->useSigterm = TRUE;
730 cps->reuse = appData.reuse[n];
731 cps->nps = appData.NPS[n]; // [HGM] nps: copy nodes per second
732 cps->useSetboard = FALSE;
734 cps->usePing = FALSE;
737 cps->usePlayother = FALSE;
738 cps->useColors = TRUE;
739 cps->useUsermove = FALSE;
740 cps->sendICS = FALSE;
741 cps->sendName = appData.icsActive;
742 cps->sdKludge = FALSE;
743 cps->stKludge = FALSE;
744 TidyProgramName(cps->program, cps->host, cps->tidy);
746 safeStrCpy(cps->variants, appData.variant, MSG_SIZ);
747 cps->analysisSupport = 2; /* detect */
748 cps->analyzing = FALSE;
749 cps->initDone = FALSE;
751 /* New features added by Tord: */
752 cps->useFEN960 = FALSE;
753 cps->useOOCastle = TRUE;
754 /* End of new features added by Tord. */
755 cps->fenOverride = appData.fenOverride[n];
757 /* [HGM] time odds: set factor for each machine */
758 cps->timeOdds = appData.timeOdds[n];
760 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
761 cps->accumulateTC = appData.accumulateTC[n];
762 cps->maxNrOfSessions = 1;
766 cps->supportsNPS = UNKNOWN;
769 cps->optionSettings = appData.engOptions[n];
771 cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
772 cps->isUCI = appData.isUCI[n]; /* [AS] */
773 cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
775 if (appData.protocolVersion[n] > PROTOVER
776 || appData.protocolVersion[n] < 1)
781 len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
782 appData.protocolVersion[n]);
783 if( (len > MSG_SIZ) && appData.debugMode )
784 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
786 DisplayFatalError(buf, 0, 2);
790 cps->protocolVersion = appData.protocolVersion[n];
793 InitEngineUCI( installDir, cps ); // [HGM] moved here from winboard.c, to make available in xboard
799 int matched, min, sec;
801 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
802 startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
804 GetTimeMark(&programStartTime);
805 srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
808 programStats.ok_to_send = 1;
809 programStats.seen_stat = 0;
812 * Initialize game list
818 * Internet chess server status
820 if (appData.icsActive) {
821 appData.matchMode = FALSE;
822 appData.matchGames = 0;
824 appData.noChessProgram = !appData.zippyPlay;
826 appData.zippyPlay = FALSE;
827 appData.zippyTalk = FALSE;
828 appData.noChessProgram = TRUE;
830 if (*appData.icsHelper != NULLCHAR) {
831 appData.useTelnet = TRUE;
832 appData.telnetProgram = appData.icsHelper;
835 appData.zippyTalk = appData.zippyPlay = FALSE;
838 /* [AS] Initialize pv info list [HGM] and game state */
842 for( i=0; i<=framePtr; i++ ) {
843 pvInfoList[i].depth = -1;
844 boards[i][EP_STATUS] = EP_NONE;
845 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
850 * Parse timeControl resource
852 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
853 appData.movesPerSession)) {
855 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
856 DisplayFatalError(buf, 0, 2);
860 * Parse searchTime resource
862 if (*appData.searchTime != NULLCHAR) {
863 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
865 searchTime = min * 60;
866 } else if (matched == 2) {
867 searchTime = min * 60 + sec;
870 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
871 DisplayFatalError(buf, 0, 2);
875 /* [AS] Adjudication threshold */
876 adjudicateLossThreshold = appData.adjudicateLossThreshold;
878 InitEngine(&first, 0);
879 InitEngine(&second, 1);
882 if (appData.icsActive) {
883 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
884 } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
885 appData.clockMode = FALSE;
886 first.sendTime = second.sendTime = 0;
890 /* Override some settings from environment variables, for backward
891 compatibility. Unfortunately it's not feasible to have the env
892 vars just set defaults, at least in xboard. Ugh.
894 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
899 if (!appData.icsActive) {
903 /* Check for variants that are supported only in ICS mode,
904 or not at all. Some that are accepted here nevertheless
905 have bugs; see comments below.
907 VariantClass variant = StringToVariant(appData.variant);
909 case VariantBughouse: /* need four players and two boards */
910 case VariantKriegspiel: /* need to hide pieces and move details */
911 /* case VariantFischeRandom: (Fabien: moved below) */
912 len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
913 if( (len > MSG_SIZ) && appData.debugMode )
914 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
916 DisplayFatalError(buf, 0, 2);
920 case VariantLoadable:
930 len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
931 if( (len > MSG_SIZ) && appData.debugMode )
932 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
934 DisplayFatalError(buf, 0, 2);
937 case VariantXiangqi: /* [HGM] repetition rules not implemented */
938 case VariantFairy: /* [HGM] TestLegality definitely off! */
939 case VariantGothic: /* [HGM] should work */
940 case VariantCapablanca: /* [HGM] should work */
941 case VariantCourier: /* [HGM] initial forced moves not implemented */
942 case VariantShogi: /* [HGM] could still mate with pawn drop */
943 case VariantKnightmate: /* [HGM] should work */
944 case VariantCylinder: /* [HGM] untested */
945 case VariantFalcon: /* [HGM] untested */
946 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
947 offboard interposition not understood */
948 case VariantNormal: /* definitely works! */
949 case VariantWildCastle: /* pieces not automatically shuffled */
950 case VariantNoCastle: /* pieces not automatically shuffled */
951 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
952 case VariantLosers: /* should work except for win condition,
953 and doesn't know captures are mandatory */
954 case VariantSuicide: /* should work except for win condition,
955 and doesn't know captures are mandatory */
956 case VariantGiveaway: /* should work except for win condition,
957 and doesn't know captures are mandatory */
958 case VariantTwoKings: /* should work */
959 case VariantAtomic: /* should work except for win condition */
960 case Variant3Check: /* should work except for win condition */
961 case VariantShatranj: /* should work except for all win conditions */
962 case VariantMakruk: /* should work except for daw countdown */
963 case VariantBerolina: /* might work if TestLegality is off */
964 case VariantCapaRandom: /* should work */
965 case VariantJanus: /* should work */
966 case VariantSuper: /* experimental */
967 case VariantGreat: /* experimental, requires legality testing to be off */
968 case VariantSChess: /* S-Chess, should work */
969 case VariantSpartan: /* should work */
976 int NextIntegerFromString( char ** str, long * value )
981 while( *s == ' ' || *s == '\t' ) {
987 if( *s >= '0' && *s <= '9' ) {
988 while( *s >= '0' && *s <= '9' ) {
989 *value = *value * 10 + (*s - '0');
1001 int NextTimeControlFromString( char ** str, long * value )
1004 int result = NextIntegerFromString( str, &temp );
1007 *value = temp * 60; /* Minutes */
1008 if( **str == ':' ) {
1010 result = NextIntegerFromString( str, &temp );
1011 *value += temp; /* Seconds */
1018 int NextSessionFromString( char ** str, int *moves, long * tc, long *inc, int *incType)
1019 { /* [HGM] routine added to read '+moves/time' for secondary time control. */
1020 int result = -1, type = 0; long temp, temp2;
1022 if(**str != ':') return -1; // old params remain in force!
1024 if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
1025 if( NextIntegerFromString( str, &temp ) ) return -1;
1026 if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
1029 /* time only: incremental or sudden-death time control */
1030 if(**str == '+') { /* increment follows; read it */
1032 if(**str == '!') type = *(*str)++; // Bronstein TC
1033 if(result = NextIntegerFromString( str, &temp2)) return -1;
1034 *inc = temp2 * 1000;
1035 if(**str == '.') { // read fraction of increment
1036 char *start = ++(*str);
1037 if(result = NextIntegerFromString( str, &temp2)) return -1;
1039 while(start++ < *str) temp2 /= 10;
1043 *moves = 0; *tc = temp * 1000; *incType = type;
1047 (*str)++; /* classical time control */
1048 result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
1059 int GetTimeQuota(int movenr, int lastUsed, char *tcString)
1060 { /* [HGM] get time to add from the multi-session time-control string */
1061 int incType, moves=1; /* kludge to force reading of first session */
1062 long time, increment;
1065 if(!*s) return 0; // empty TC string means we ran out of the last sudden-death version
1066 if(appData.debugMode) fprintf(debugFP, "TC string = '%s'\n", tcString);
1068 if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
1069 nextSession = s; suddenDeath = moves == 0 && increment == 0;
1070 if(appData.debugMode) fprintf(debugFP, "mps=%d tc=%d inc=%d\n", moves, (int) time, (int) increment);
1071 if(movenr == -1) return time; /* last move before new session */
1072 if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
1073 if(incType == '!' && lastUsed < increment) increment = lastUsed;
1074 if(!moves) return increment; /* current session is incremental */
1075 if(movenr >= 0) movenr -= moves; /* we already finished this session */
1076 } while(movenr >= -1); /* try again for next session */
1078 return 0; // no new time quota on this move
1082 ParseTimeControl(tc, ti, mps)
1089 char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
1092 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1093 if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
1094 sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
1098 snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
1100 snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
1103 snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
1105 snprintf(buf, MSG_SIZ, ":%s", mytc);
1107 fullTimeControlString = StrSave(buf); // this should now be in PGN format
1109 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1114 /* Parse second time control */
1117 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1125 timeControl_2 = tc2 * 1000;
1135 timeControl = tc1 * 1000;
1138 timeIncrement = ti * 1000; /* convert to ms */
1139 movesPerSession = 0;
1142 movesPerSession = mps;
1150 if (appData.debugMode) {
1151 fprintf(debugFP, "%s\n", programVersion);
1154 set_cont_sequence(appData.wrapContSeq);
1155 if (appData.matchGames > 0) {
1156 appData.matchMode = TRUE;
1157 } else if (appData.matchMode) {
1158 appData.matchGames = 1;
1160 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1161 appData.matchGames = appData.sameColorGames;
1162 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1163 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1164 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1167 if (appData.noChessProgram || first.protocolVersion == 1) {
1170 /* kludge: allow timeout for initial "feature" commands */
1172 DisplayMessage("", _("Starting chess program"));
1173 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1178 MatchEvent(int mode)
1179 { // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
1180 /* Set up machine vs. machine match */
1181 if (appData.noChessProgram) {
1182 DisplayFatalError(_("Can't have a match with no chess programs"),
1188 if (*appData.loadGameFile != NULLCHAR) {
1189 int index = appData.loadGameIndex; // [HGM] autoinc
1190 if(index<0) lastIndex = index = 1;
1191 if (!LoadGameFromFile(appData.loadGameFile,
1193 appData.loadGameFile, FALSE)) {
1194 DisplayFatalError(_("Bad game file"), 0, 1);
1197 } else if (*appData.loadPositionFile != NULLCHAR) {
1198 int index = appData.loadPositionIndex; // [HGM] autoinc
1199 if(index<0) lastIndex = index = 1;
1200 if (!LoadPositionFromFile(appData.loadPositionFile,
1202 appData.loadPositionFile)) {
1203 DisplayFatalError(_("Bad position file"), 0, 1);
1207 first.matchWins = second.matchWins = 0; // [HGM] match: needed in later matches
\r
1212 InitBackEnd3 P((void))
1214 GameMode initialMode;
1218 InitChessProgram(&first, startedFromSetupPosition);
1220 if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
1221 free(programVersion);
1222 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1223 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1226 if (appData.icsActive) {
1228 /* [DM] Make a console window if needed [HGM] merged ifs */
1234 if (*appData.icsCommPort != NULLCHAR)
1235 len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1236 appData.icsCommPort);
1238 len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1239 appData.icsHost, appData.icsPort);
1241 if( (len > MSG_SIZ) && appData.debugMode )
1242 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1244 DisplayFatalError(buf, err, 1);
1249 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1251 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1252 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1253 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1254 } else if (appData.noChessProgram) {
1260 if (*appData.cmailGameName != NULLCHAR) {
1262 OpenLoopback(&cmailPR);
1264 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1268 DisplayMessage("", "");
1269 if (StrCaseCmp(appData.initialMode, "") == 0) {
1270 initialMode = BeginningOfGame;
1271 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1272 initialMode = TwoMachinesPlay;
1273 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1274 initialMode = AnalyzeFile;
1275 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1276 initialMode = AnalyzeMode;
1277 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1278 initialMode = MachinePlaysWhite;
1279 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1280 initialMode = MachinePlaysBlack;
1281 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1282 initialMode = EditGame;
1283 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1284 initialMode = EditPosition;
1285 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1286 initialMode = Training;
1288 len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1289 if( (len > MSG_SIZ) && appData.debugMode )
1290 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1292 DisplayFatalError(buf, 0, 2);
1296 if (appData.matchMode) {
1298 } else if (*appData.cmailGameName != NULLCHAR) {
1299 /* Set up cmail mode */
1300 ReloadCmailMsgEvent(TRUE);
1302 /* Set up other modes */
1303 if (initialMode == AnalyzeFile) {
1304 if (*appData.loadGameFile == NULLCHAR) {
1305 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1309 if (*appData.loadGameFile != NULLCHAR) {
1310 (void) LoadGameFromFile(appData.loadGameFile,
1311 appData.loadGameIndex,
1312 appData.loadGameFile, TRUE);
1313 } else if (*appData.loadPositionFile != NULLCHAR) {
1314 (void) LoadPositionFromFile(appData.loadPositionFile,
1315 appData.loadPositionIndex,
1316 appData.loadPositionFile);
1317 /* [HGM] try to make self-starting even after FEN load */
1318 /* to allow automatic setup of fairy variants with wtm */
1319 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1320 gameMode = BeginningOfGame;
1321 setboardSpoiledMachineBlack = 1;
1323 /* [HGM] loadPos: make that every new game uses the setup */
1324 /* from file as long as we do not switch variant */
1325 if(!blackPlaysFirst) {
1326 startedFromPositionFile = TRUE;
1327 CopyBoard(filePosition, boards[0]);
1330 if (initialMode == AnalyzeMode) {
1331 if (appData.noChessProgram) {
1332 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1335 if (appData.icsActive) {
1336 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1340 } else if (initialMode == AnalyzeFile) {
1341 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1342 ShowThinkingEvent();
1344 AnalysisPeriodicEvent(1);
1345 } else if (initialMode == MachinePlaysWhite) {
1346 if (appData.noChessProgram) {
1347 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1351 if (appData.icsActive) {
1352 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1356 MachineWhiteEvent();
1357 } else if (initialMode == MachinePlaysBlack) {
1358 if (appData.noChessProgram) {
1359 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1363 if (appData.icsActive) {
1364 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1368 MachineBlackEvent();
1369 } else if (initialMode == TwoMachinesPlay) {
1370 if (appData.noChessProgram) {
1371 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1375 if (appData.icsActive) {
1376 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1381 } else if (initialMode == EditGame) {
1383 } else if (initialMode == EditPosition) {
1384 EditPositionEvent();
1385 } else if (initialMode == Training) {
1386 if (*appData.loadGameFile == NULLCHAR) {
1387 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1396 * Establish will establish a contact to a remote host.port.
1397 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1398 * used to talk to the host.
1399 * Returns 0 if okay, error code if not.
1406 if (*appData.icsCommPort != NULLCHAR) {
1407 /* Talk to the host through a serial comm port */
1408 return OpenCommPort(appData.icsCommPort, &icsPR);
1410 } else if (*appData.gateway != NULLCHAR) {
1411 if (*appData.remoteShell == NULLCHAR) {
1412 /* Use the rcmd protocol to run telnet program on a gateway host */
1413 snprintf(buf, sizeof(buf), "%s %s %s",
1414 appData.telnetProgram, appData.icsHost, appData.icsPort);
1415 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1418 /* Use the rsh program to run telnet program on a gateway host */
1419 if (*appData.remoteUser == NULLCHAR) {
1420 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1421 appData.gateway, appData.telnetProgram,
1422 appData.icsHost, appData.icsPort);
1424 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1425 appData.remoteShell, appData.gateway,
1426 appData.remoteUser, appData.telnetProgram,
1427 appData.icsHost, appData.icsPort);
1429 return StartChildProcess(buf, "", &icsPR);
1432 } else if (appData.useTelnet) {
1433 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1436 /* TCP socket interface differs somewhat between
1437 Unix and NT; handle details in the front end.
1439 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1443 void EscapeExpand(char *p, char *q)
1444 { // [HGM] initstring: routine to shape up string arguments
1445 while(*p++ = *q++) if(p[-1] == '\\')
1447 case 'n': p[-1] = '\n'; break;
1448 case 'r': p[-1] = '\r'; break;
1449 case 't': p[-1] = '\t'; break;
1450 case '\\': p[-1] = '\\'; break;
1451 case 0: *p = 0; return;
1452 default: p[-1] = q[-1]; break;
1457 show_bytes(fp, buf, count)
1463 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1464 fprintf(fp, "\\%03o", *buf & 0xff);
1473 /* Returns an errno value */
1475 OutputMaybeTelnet(pr, message, count, outError)
1481 char buf[8192], *p, *q, *buflim;
1482 int left, newcount, outcount;
1484 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1485 *appData.gateway != NULLCHAR) {
1486 if (appData.debugMode) {
1487 fprintf(debugFP, ">ICS: ");
1488 show_bytes(debugFP, message, count);
1489 fprintf(debugFP, "\n");
1491 return OutputToProcess(pr, message, count, outError);
1494 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1501 if (appData.debugMode) {
1502 fprintf(debugFP, ">ICS: ");
1503 show_bytes(debugFP, buf, newcount);
1504 fprintf(debugFP, "\n");
1506 outcount = OutputToProcess(pr, buf, newcount, outError);
1507 if (outcount < newcount) return -1; /* to be sure */
1514 } else if (((unsigned char) *p) == TN_IAC) {
1515 *q++ = (char) TN_IAC;
1522 if (appData.debugMode) {
1523 fprintf(debugFP, ">ICS: ");
1524 show_bytes(debugFP, buf, newcount);
1525 fprintf(debugFP, "\n");
1527 outcount = OutputToProcess(pr, buf, newcount, outError);
1528 if (outcount < newcount) return -1; /* to be sure */
1533 read_from_player(isr, closure, message, count, error)
1540 int outError, outCount;
1541 static int gotEof = 0;
1543 /* Pass data read from player on to ICS */
1546 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1547 if (outCount < count) {
1548 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1550 } else if (count < 0) {
1551 RemoveInputSource(isr);
1552 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1553 } else if (gotEof++ > 0) {
1554 RemoveInputSource(isr);
1555 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1561 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1562 if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
1563 connectionAlive = FALSE; // only sticks if no response to 'date' command.
1564 SendToICS("date\n");
1565 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1568 /* added routine for printf style output to ics */
1569 void ics_printf(char *format, ...)
1571 char buffer[MSG_SIZ];
1574 va_start(args, format);
1575 vsnprintf(buffer, sizeof(buffer), format, args);
1576 buffer[sizeof(buffer)-1] = '\0';
1585 int count, outCount, outError;
1587 if (icsPR == NULL) return;
1590 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1591 if (outCount < count) {
1592 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1596 /* This is used for sending logon scripts to the ICS. Sending
1597 without a delay causes problems when using timestamp on ICC
1598 (at least on my machine). */
1600 SendToICSDelayed(s,msdelay)
1604 int count, outCount, outError;
1606 if (icsPR == NULL) return;
1609 if (appData.debugMode) {
1610 fprintf(debugFP, ">ICS: ");
1611 show_bytes(debugFP, s, count);
1612 fprintf(debugFP, "\n");
1614 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1616 if (outCount < count) {
1617 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1622 /* Remove all highlighting escape sequences in s
1623 Also deletes any suffix starting with '('
1626 StripHighlightAndTitle(s)
1629 static char retbuf[MSG_SIZ];
1632 while (*s != NULLCHAR) {
1633 while (*s == '\033') {
1634 while (*s != NULLCHAR && !isalpha(*s)) s++;
1635 if (*s != NULLCHAR) s++;
1637 while (*s != NULLCHAR && *s != '\033') {
1638 if (*s == '(' || *s == '[') {
1649 /* Remove all highlighting escape sequences in s */
1654 static char retbuf[MSG_SIZ];
1657 while (*s != NULLCHAR) {
1658 while (*s == '\033') {
1659 while (*s != NULLCHAR && !isalpha(*s)) s++;
1660 if (*s != NULLCHAR) s++;
1662 while (*s != NULLCHAR && *s != '\033') {
1670 char *variantNames[] = VARIANT_NAMES;
1675 return variantNames[v];
1679 /* Identify a variant from the strings the chess servers use or the
1680 PGN Variant tag names we use. */
1687 VariantClass v = VariantNormal;
1688 int i, found = FALSE;
1694 /* [HGM] skip over optional board-size prefixes */
1695 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
1696 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
1697 while( *e++ != '_');
1700 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
1704 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1705 if (StrCaseStr(e, variantNames[i])) {
1706 v = (VariantClass) i;
1713 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
1714 || StrCaseStr(e, "wild/fr")
1715 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
1716 v = VariantFischeRandom;
1717 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
1718 (i = 1, p = StrCaseStr(e, "w"))) {
1720 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
1727 case 0: /* FICS only, actually */
1729 /* Castling legal even if K starts on d-file */
1730 v = VariantWildCastle;
1735 /* Castling illegal even if K & R happen to start in
1736 normal positions. */
1737 v = VariantNoCastle;
1750 /* Castling legal iff K & R start in normal positions */
1756 /* Special wilds for position setup; unclear what to do here */
1757 v = VariantLoadable;
1760 /* Bizarre ICC game */
1761 v = VariantTwoKings;
1764 v = VariantKriegspiel;
1770 v = VariantFischeRandom;
1773 v = VariantCrazyhouse;
1776 v = VariantBughouse;
1782 /* Not quite the same as FICS suicide! */
1783 v = VariantGiveaway;
1789 v = VariantShatranj;
1792 /* Temporary names for future ICC types. The name *will* change in
1793 the next xboard/WinBoard release after ICC defines it. */
1831 v = VariantCapablanca;
1834 v = VariantKnightmate;
1840 v = VariantCylinder;
1846 v = VariantCapaRandom;
1849 v = VariantBerolina;
1861 /* Found "wild" or "w" in the string but no number;
1862 must assume it's normal chess. */
1866 len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
1867 if( (len > MSG_SIZ) && appData.debugMode )
1868 fprintf(debugFP, "StringToVariant: buffer truncated.\n");
1870 DisplayError(buf, 0);
1876 if (appData.debugMode) {
1877 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
1878 e, wnum, VariantName(v));
1883 static int leftover_start = 0, leftover_len = 0;
1884 char star_match[STAR_MATCH_N][MSG_SIZ];
1886 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
1887 advance *index beyond it, and set leftover_start to the new value of
1888 *index; else return FALSE. If pattern contains the character '*', it
1889 matches any sequence of characters not containing '\r', '\n', or the
1890 character following the '*' (if any), and the matched sequence(s) are
1891 copied into star_match.
1894 looking_at(buf, index, pattern)
1899 char *bufp = &buf[*index], *patternp = pattern;
1901 char *matchp = star_match[0];
1904 if (*patternp == NULLCHAR) {
1905 *index = leftover_start = bufp - buf;
1909 if (*bufp == NULLCHAR) return FALSE;
1910 if (*patternp == '*') {
1911 if (*bufp == *(patternp + 1)) {
1913 matchp = star_match[++star_count];
1917 } else if (*bufp == '\n' || *bufp == '\r') {
1919 if (*patternp == NULLCHAR)
1924 *matchp++ = *bufp++;
1928 if (*patternp != *bufp) return FALSE;
1935 SendToPlayer(data, length)
1939 int error, outCount;
1940 outCount = OutputToProcess(NoProc, data, length, &error);
1941 if (outCount < length) {
1942 DisplayFatalError(_("Error writing to display"), error, 1);
1947 PackHolding(packed, holding)
1959 switch (runlength) {
1970 sprintf(q, "%d", runlength);
1982 /* Telnet protocol requests from the front end */
1984 TelnetRequest(ddww, option)
1985 unsigned char ddww, option;
1987 unsigned char msg[3];
1988 int outCount, outError;
1990 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
1992 if (appData.debugMode) {
1993 char buf1[8], buf2[8], *ddwwStr, *optionStr;
2009 snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2018 snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2021 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2026 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2028 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2035 if (!appData.icsActive) return;
2036 TelnetRequest(TN_DO, TN_ECHO);
2042 if (!appData.icsActive) return;
2043 TelnetRequest(TN_DONT, TN_ECHO);
2047 CopyHoldings(Board board, char *holdings, ChessSquare lowestPiece)
2049 /* put the holdings sent to us by the server on the board holdings area */
2050 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2054 if(gameInfo.holdingsWidth < 2) return;
2055 if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2056 return; // prevent overwriting by pre-board holdings
2058 if( (int)lowestPiece >= BlackPawn ) {
2061 holdingsStartRow = BOARD_HEIGHT-1;
2064 holdingsColumn = BOARD_WIDTH-1;
2065 countsColumn = BOARD_WIDTH-2;
2066 holdingsStartRow = 0;
2070 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
2071 board[i][holdingsColumn] = EmptySquare;
2072 board[i][countsColumn] = (ChessSquare) 0;
2074 while( (p=*holdings++) != NULLCHAR ) {
2075 piece = CharToPiece( ToUpper(p) );
2076 if(piece == EmptySquare) continue;
2077 /*j = (int) piece - (int) WhitePawn;*/
2078 j = PieceToNumber(piece);
2079 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2080 if(j < 0) continue; /* should not happen */
2081 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2082 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2083 board[holdingsStartRow+j*direction][countsColumn]++;
2089 VariantSwitch(Board board, VariantClass newVariant)
2091 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2092 static Board oldBoard;
2094 startedFromPositionFile = FALSE;
2095 if(gameInfo.variant == newVariant) return;
2097 /* [HGM] This routine is called each time an assignment is made to
2098 * gameInfo.variant during a game, to make sure the board sizes
2099 * are set to match the new variant. If that means adding or deleting
2100 * holdings, we shift the playing board accordingly
2101 * This kludge is needed because in ICS observe mode, we get boards
2102 * of an ongoing game without knowing the variant, and learn about the
2103 * latter only later. This can be because of the move list we requested,
2104 * in which case the game history is refilled from the beginning anyway,
2105 * but also when receiving holdings of a crazyhouse game. In the latter
2106 * case we want to add those holdings to the already received position.
2110 if (appData.debugMode) {
2111 fprintf(debugFP, "Switch board from %s to %s\n",
2112 VariantName(gameInfo.variant), VariantName(newVariant));
2113 setbuf(debugFP, NULL);
2115 shuffleOpenings = 0; /* [HGM] shuffle */
2116 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2120 newWidth = 9; newHeight = 9;
2121 gameInfo.holdingsSize = 7;
2122 case VariantBughouse:
2123 case VariantCrazyhouse:
2124 newHoldingsWidth = 2; break;
2128 newHoldingsWidth = 2;
2129 gameInfo.holdingsSize = 8;
2132 case VariantCapablanca:
2133 case VariantCapaRandom:
2136 newHoldingsWidth = gameInfo.holdingsSize = 0;
2139 if(newWidth != gameInfo.boardWidth ||
2140 newHeight != gameInfo.boardHeight ||
2141 newHoldingsWidth != gameInfo.holdingsWidth ) {
2143 /* shift position to new playing area, if needed */
2144 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2145 for(i=0; i<BOARD_HEIGHT; i++)
2146 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2147 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2149 for(i=0; i<newHeight; i++) {
2150 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2151 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2153 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2154 for(i=0; i<BOARD_HEIGHT; i++)
2155 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2156 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2159 gameInfo.boardWidth = newWidth;
2160 gameInfo.boardHeight = newHeight;
2161 gameInfo.holdingsWidth = newHoldingsWidth;
2162 gameInfo.variant = newVariant;
2163 InitDrawingSizes(-2, 0);
2164 } else gameInfo.variant = newVariant;
2165 CopyBoard(oldBoard, board); // remember correctly formatted board
2166 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2167 DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2170 static int loggedOn = FALSE;
2172 /*-- Game start info cache: --*/
2174 char gs_kind[MSG_SIZ];
2175 static char player1Name[128] = "";
2176 static char player2Name[128] = "";
2177 static char cont_seq[] = "\n\\ ";
2178 static int player1Rating = -1;
2179 static int player2Rating = -1;
2180 /*----------------------------*/
2182 ColorClass curColor = ColorNormal;
2183 int suppressKibitz = 0;
2186 Boolean soughtPending = FALSE;
2187 Boolean seekGraphUp;
2188 #define MAX_SEEK_ADS 200
2190 char *seekAdList[MAX_SEEK_ADS];
2191 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2192 float tcList[MAX_SEEK_ADS];
2193 char colorList[MAX_SEEK_ADS];
2194 int nrOfSeekAds = 0;
2195 int minRating = 1010, maxRating = 2800;
2196 int hMargin = 10, vMargin = 20, h, w;
2197 extern int squareSize, lineGap;
2202 int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2203 xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2204 if(r < minRating+100 && r >=0 ) r = minRating+100;
2205 if(r > maxRating) r = maxRating;
2206 if(tc < 1.) tc = 1.;
2207 if(tc > 95.) tc = 95.;
2208 x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2209 y = ((double)r - minRating)/(maxRating - minRating)
2210 * (h-vMargin-squareSize/8-1) + vMargin;
2211 if(ratingList[i] < 0) y = vMargin + squareSize/4;
2212 if(strstr(seekAdList[i], " u ")) color = 1;
2213 if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2214 !strstr(seekAdList[i], "bullet") &&
2215 !strstr(seekAdList[i], "blitz") &&
2216 !strstr(seekAdList[i], "standard") ) color = 2;
2217 if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2218 DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2222 AddAd(char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
2224 char buf[MSG_SIZ], *ext = "";
2225 VariantClass v = StringToVariant(type);
2226 if(strstr(type, "wild")) {
2227 ext = type + 4; // append wild number
2228 if(v == VariantFischeRandom) type = "chess960"; else
2229 if(v == VariantLoadable) type = "setup"; else
2230 type = VariantName(v);
2232 snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2233 if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2234 if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2235 ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2236 sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2237 tcList[nrOfSeekAds] = base + (2./3.)*inc;
2238 seekNrList[nrOfSeekAds] = nr;
2239 zList[nrOfSeekAds] = 0;
2240 seekAdList[nrOfSeekAds++] = StrSave(buf);
2241 if(plot) PlotSeekAd(nrOfSeekAds-1);
2248 int x = xList[i], y = yList[i], d=squareSize/4, k;
2249 DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2250 if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2251 // now replot every dot that overlapped
2252 for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2253 int xx = xList[k], yy = yList[k];
2254 if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2255 DrawSeekDot(xx, yy, colorList[k]);
2260 RemoveSeekAd(int nr)
2263 for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2265 if(seekAdList[i]) free(seekAdList[i]);
2266 seekAdList[i] = seekAdList[--nrOfSeekAds];
2267 seekNrList[i] = seekNrList[nrOfSeekAds];
2268 ratingList[i] = ratingList[nrOfSeekAds];
2269 colorList[i] = colorList[nrOfSeekAds];
2270 tcList[i] = tcList[nrOfSeekAds];
2271 xList[i] = xList[nrOfSeekAds];
2272 yList[i] = yList[nrOfSeekAds];
2273 zList[i] = zList[nrOfSeekAds];
2274 seekAdList[nrOfSeekAds] = NULL;
2280 MatchSoughtLine(char *line)
2282 char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2283 int nr, base, inc, u=0; char dummy;
2285 if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2286 sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2288 (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2289 sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
2290 // match: compact and save the line
2291 AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2301 if(!seekGraphUp) return FALSE;
2302 h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap;
2303 w = BOARD_WIDTH * (squareSize + lineGap) + lineGap;
2305 DrawSeekBackground(0, 0, w, h);
2306 DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2307 DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2308 for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2309 int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2311 DrawSeekAxis(hMargin+5*(i%500==0), yy, hMargin-5, yy); // rating ticks
2314 snprintf(buf, MSG_SIZ, "%d", i);
2315 DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2318 DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2319 for(i=1; i<100; i+=(i<10?1:5)) {
2320 int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2321 DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2322 if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2324 snprintf(buf, MSG_SIZ, "%d", i);
2325 DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2328 for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2332 int SeekGraphClick(ClickType click, int x, int y, int moving)
2334 static int lastDown = 0, displayed = 0, lastSecond;
2335 if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2336 if(click == Release || moving) return FALSE;
2338 soughtPending = TRUE;
2339 SendToICS(ics_prefix);
2340 SendToICS("sought\n"); // should this be "sought all"?
2341 } else { // issue challenge based on clicked ad
2342 int dist = 10000; int i, closest = 0, second = 0;
2343 for(i=0; i<nrOfSeekAds; i++) {
2344 int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
2345 if(d < dist) { dist = d; closest = i; }
2346 second += (d - zList[i] < 120); // count in-range ads
2347 if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2351 second = (second > 1);
2352 if(displayed != closest || second != lastSecond) {
2353 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2354 lastSecond = second; displayed = closest;
2356 if(click == Press) {
2357 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2360 } // on press 'hit', only show info
2361 if(moving == 2) return TRUE; // ignore right up-clicks on dot
2362 snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2363 SendToICS(ics_prefix);
2365 return TRUE; // let incoming board of started game pop down the graph
2366 } else if(click == Release) { // release 'miss' is ignored
2367 zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2368 if(moving == 2) { // right up-click
2369 nrOfSeekAds = 0; // refresh graph
2370 soughtPending = TRUE;
2371 SendToICS(ics_prefix);
2372 SendToICS("sought\n"); // should this be "sought all"?
2375 } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2376 // press miss or release hit 'pop down' seek graph
2377 seekGraphUp = FALSE;
2378 DrawPosition(TRUE, NULL);
2384 read_from_ics(isr, closure, data, count, error)
2391 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2392 #define STARTED_NONE 0
2393 #define STARTED_MOVES 1
2394 #define STARTED_BOARD 2
2395 #define STARTED_OBSERVE 3
2396 #define STARTED_HOLDINGS 4
2397 #define STARTED_CHATTER 5
2398 #define STARTED_COMMENT 6
2399 #define STARTED_MOVES_NOHIDE 7
2401 static int started = STARTED_NONE;
2402 static char parse[20000];
2403 static int parse_pos = 0;
2404 static char buf[BUF_SIZE + 1];
2405 static int firstTime = TRUE, intfSet = FALSE;
2406 static ColorClass prevColor = ColorNormal;
2407 static int savingComment = FALSE;
2408 static int cmatch = 0; // continuation sequence match
2415 int backup; /* [DM] For zippy color lines */
2417 char talker[MSG_SIZ]; // [HGM] chat
2420 connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2422 if (appData.debugMode) {
2424 fprintf(debugFP, "<ICS: ");
2425 show_bytes(debugFP, data, count);
2426 fprintf(debugFP, "\n");
2430 if (appData.debugMode) { int f = forwardMostMove;
2431 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2432 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2433 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2436 /* If last read ended with a partial line that we couldn't parse,
2437 prepend it to the new read and try again. */
2438 if (leftover_len > 0) {
2439 for (i=0; i<leftover_len; i++)
2440 buf[i] = buf[leftover_start + i];
2443 /* copy new characters into the buffer */
2444 bp = buf + leftover_len;
2445 buf_len=leftover_len;
2446 for (i=0; i<count; i++)
2449 if (data[i] == '\r')
2452 // join lines split by ICS?
2453 if (!appData.noJoin)
2456 Joining just consists of finding matches against the
2457 continuation sequence, and discarding that sequence
2458 if found instead of copying it. So, until a match
2459 fails, there's nothing to do since it might be the
2460 complete sequence, and thus, something we don't want
2463 if (data[i] == cont_seq[cmatch])
2466 if (cmatch == strlen(cont_seq))
2468 cmatch = 0; // complete match. just reset the counter
2471 it's possible for the ICS to not include the space
2472 at the end of the last word, making our [correct]
2473 join operation fuse two separate words. the server
2474 does this when the space occurs at the width setting.
2476 if (!buf_len || buf[buf_len-1] != ' ')
2487 match failed, so we have to copy what matched before
2488 falling through and copying this character. In reality,
2489 this will only ever be just the newline character, but
2490 it doesn't hurt to be precise.
2492 strncpy(bp, cont_seq, cmatch);
2504 buf[buf_len] = NULLCHAR;
2505 // next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2510 while (i < buf_len) {
2511 /* Deal with part of the TELNET option negotiation
2512 protocol. We refuse to do anything beyond the
2513 defaults, except that we allow the WILL ECHO option,
2514 which ICS uses to turn off password echoing when we are
2515 directly connected to it. We reject this option
2516 if localLineEditing mode is on (always on in xboard)
2517 and we are talking to port 23, which might be a real
2518 telnet server that will try to keep WILL ECHO on permanently.
2520 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2521 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2522 unsigned char option;
2524 switch ((unsigned char) buf[++i]) {
2526 if (appData.debugMode)
2527 fprintf(debugFP, "\n<WILL ");
2528 switch (option = (unsigned char) buf[++i]) {
2530 if (appData.debugMode)
2531 fprintf(debugFP, "ECHO ");
2532 /* Reply only if this is a change, according
2533 to the protocol rules. */
2534 if (remoteEchoOption) break;
2535 if (appData.localLineEditing &&
2536 atoi(appData.icsPort) == TN_PORT) {
2537 TelnetRequest(TN_DONT, TN_ECHO);
2540 TelnetRequest(TN_DO, TN_ECHO);
2541 remoteEchoOption = TRUE;
2545 if (appData.debugMode)
2546 fprintf(debugFP, "%d ", option);
2547 /* Whatever this is, we don't want it. */
2548 TelnetRequest(TN_DONT, option);
2553 if (appData.debugMode)
2554 fprintf(debugFP, "\n<WONT ");
2555 switch (option = (unsigned char) buf[++i]) {
2557 if (appData.debugMode)
2558 fprintf(debugFP, "ECHO ");
2559 /* Reply only if this is a change, according
2560 to the protocol rules. */
2561 if (!remoteEchoOption) break;
2563 TelnetRequest(TN_DONT, TN_ECHO);
2564 remoteEchoOption = FALSE;
2567 if (appData.debugMode)
2568 fprintf(debugFP, "%d ", (unsigned char) option);
2569 /* Whatever this is, it must already be turned
2570 off, because we never agree to turn on
2571 anything non-default, so according to the
2572 protocol rules, we don't reply. */
2577 if (appData.debugMode)
2578 fprintf(debugFP, "\n<DO ");
2579 switch (option = (unsigned char) buf[++i]) {
2581 /* Whatever this is, we refuse to do it. */
2582 if (appData.debugMode)
2583 fprintf(debugFP, "%d ", option);
2584 TelnetRequest(TN_WONT, option);
2589 if (appData.debugMode)
2590 fprintf(debugFP, "\n<DONT ");
2591 switch (option = (unsigned char) buf[++i]) {
2593 if (appData.debugMode)
2594 fprintf(debugFP, "%d ", option);
2595 /* Whatever this is, we are already not doing
2596 it, because we never agree to do anything
2597 non-default, so according to the protocol
2598 rules, we don't reply. */
2603 if (appData.debugMode)
2604 fprintf(debugFP, "\n<IAC ");
2605 /* Doubled IAC; pass it through */
2609 if (appData.debugMode)
2610 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2611 /* Drop all other telnet commands on the floor */
2614 if (oldi > next_out)
2615 SendToPlayer(&buf[next_out], oldi - next_out);
2621 /* OK, this at least will *usually* work */
2622 if (!loggedOn && looking_at(buf, &i, "ics%")) {
2626 if (loggedOn && !intfSet) {
2627 if (ics_type == ICS_ICC) {
2628 snprintf(str, MSG_SIZ,
2629 "/set-quietly interface %s\n/set-quietly style 12\n",
2631 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2632 strcat(str, "/set-2 51 1\n/set seek 1\n");
2633 } else if (ics_type == ICS_CHESSNET) {
2634 snprintf(str, MSG_SIZ, "/style 12\n");
2636 safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
2637 strcat(str, programVersion);
2638 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2639 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2640 strcat(str, "$iset seekremove 1\n$set seek 1\n");
2642 strcat(str, "$iset nohighlight 1\n");
2644 strcat(str, "$iset lock 1\n$style 12\n");
2647 NotifyFrontendLogin();
2651 if (started == STARTED_COMMENT) {
2652 /* Accumulate characters in comment */
2653 parse[parse_pos++] = buf[i];
2654 if (buf[i] == '\n') {
2655 parse[parse_pos] = NULLCHAR;
2656 if(chattingPartner>=0) {
2658 snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
2659 OutputChatMessage(chattingPartner, mess);
2660 chattingPartner = -1;
2661 next_out = i+1; // [HGM] suppress printing in ICS window
2663 if(!suppressKibitz) // [HGM] kibitz
2664 AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
2665 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2666 int nrDigit = 0, nrAlph = 0, j;
2667 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2668 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2669 parse[parse_pos] = NULLCHAR;
2670 // try to be smart: if it does not look like search info, it should go to
2671 // ICS interaction window after all, not to engine-output window.
2672 for(j=0; j<parse_pos; j++) { // count letters and digits
2673 nrDigit += (parse[j] >= '0' && parse[j] <= '9');
2674 nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
2675 nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
2677 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
2678 int depth=0; float score;
2679 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
2680 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
2681 pvInfoList[forwardMostMove-1].depth = depth;
2682 pvInfoList[forwardMostMove-1].score = 100*score;
2684 OutputKibitz(suppressKibitz, parse);
2687 snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
2688 SendToPlayer(tmp, strlen(tmp));
2690 next_out = i+1; // [HGM] suppress printing in ICS window
2692 started = STARTED_NONE;
2694 /* Don't match patterns against characters in comment */
2699 if (started == STARTED_CHATTER) {
2700 if (buf[i] != '\n') {
2701 /* Don't match patterns against characters in chatter */
2705 started = STARTED_NONE;
2706 if(suppressKibitz) next_out = i+1;
2709 /* Kludge to deal with rcmd protocol */
2710 if (firstTime && looking_at(buf, &i, "\001*")) {
2711 DisplayFatalError(&buf[1], 0, 1);
2717 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
2720 if (appData.debugMode)
2721 fprintf(debugFP, "ics_type %d\n", ics_type);
2724 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
2725 ics_type = ICS_FICS;
2727 if (appData.debugMode)
2728 fprintf(debugFP, "ics_type %d\n", ics_type);
2731 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
2732 ics_type = ICS_CHESSNET;
2734 if (appData.debugMode)
2735 fprintf(debugFP, "ics_type %d\n", ics_type);
2740 (looking_at(buf, &i, "\"*\" is *a registered name") ||
2741 looking_at(buf, &i, "Logging you in as \"*\"") ||
2742 looking_at(buf, &i, "will be \"*\""))) {
2743 safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
2747 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
2749 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
2750 DisplayIcsInteractionTitle(buf);
2751 have_set_title = TRUE;
2754 /* skip finger notes */
2755 if (started == STARTED_NONE &&
2756 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
2757 (buf[i] == '1' && buf[i+1] == '0')) &&
2758 buf[i+2] == ':' && buf[i+3] == ' ') {
2759 started = STARTED_CHATTER;
2765 // [HGM] seekgraph: recognize sought lines and end-of-sought message
2766 if(appData.seekGraph) {
2767 if(soughtPending && MatchSoughtLine(buf+i)) {
2768 i = strstr(buf+i, "rated") - buf;
2769 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2770 next_out = leftover_start = i;
2771 started = STARTED_CHATTER;
2772 suppressKibitz = TRUE;
2775 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
2776 && looking_at(buf, &i, "* ads displayed")) {
2777 soughtPending = FALSE;
2782 if(appData.autoRefresh) {
2783 if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
2784 int s = (ics_type == ICS_ICC); // ICC format differs
2786 AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
2787 star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
2788 looking_at(buf, &i, "*% "); // eat prompt
2789 if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
2790 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2791 next_out = i; // suppress
2794 if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
2795 char *p = star_match[0];
2797 if(seekGraphUp) RemoveSeekAd(atoi(p));
2798 while(*p && *p++ != ' '); // next
2800 looking_at(buf, &i, "*% "); // eat prompt
2801 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2808 /* skip formula vars */
2809 if (started == STARTED_NONE &&
2810 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
2811 started = STARTED_CHATTER;
2816 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
2817 if (appData.autoKibitz && started == STARTED_NONE &&
2818 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
2819 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
2820 if((looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
2821 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
2822 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
2823 suppressKibitz = TRUE;
2824 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2826 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
2827 && (gameMode == IcsPlayingWhite)) ||
2828 (StrStr(star_match[0], gameInfo.black) == star_match[0]
2829 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
2830 started = STARTED_CHATTER; // own kibitz we simply discard
2832 started = STARTED_COMMENT; // make sure it will be collected in parse[]
2833 parse_pos = 0; parse[0] = NULLCHAR;
2834 savingComment = TRUE;
2835 suppressKibitz = gameMode != IcsObserving ? 2 :
2836 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
2840 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
2841 looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
2842 && atoi(star_match[0])) {
2843 // suppress the acknowledgements of our own autoKibitz
2845 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2846 if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
2847 SendToPlayer(star_match[0], strlen(star_match[0]));
2848 if(looking_at(buf, &i, "*% ")) // eat prompt
2849 suppressKibitz = FALSE;
2853 } // [HGM] kibitz: end of patch
2855 // [HGM] chat: intercept tells by users for which we have an open chat window
2857 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
2858 looking_at(buf, &i, "* whispers:") ||
2859 looking_at(buf, &i, "* kibitzes:") ||
2860 looking_at(buf, &i, "* shouts:") ||
2861 looking_at(buf, &i, "* c-shouts:") ||
2862 looking_at(buf, &i, "--> * ") ||
2863 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
2864 looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
2865 looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
2866 looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
2868 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
2869 chattingPartner = -1;
2871 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
2872 for(p=0; p<MAX_CHAT; p++) {
2873 if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
2874 talker[0] = '['; strcat(talker, "] ");
2875 Colorize(channel == 1 ? ColorChannel1 : ColorChannel, FALSE);
2876 chattingPartner = p; break;
2879 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
2880 for(p=0; p<MAX_CHAT; p++) {
2881 if(!strcmp("kibitzes", chatPartner[p])) {
2882 talker[0] = '['; strcat(talker, "] ");
2883 chattingPartner = p; break;
2886 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
2887 for(p=0; p<MAX_CHAT; p++) {
2888 if(!strcmp("whispers", chatPartner[p])) {
2889 talker[0] = '['; strcat(talker, "] ");
2890 chattingPartner = p; break;
2893 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
2894 if(buf[i-8] == '-' && buf[i-3] == 't')
2895 for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
2896 if(!strcmp("c-shouts", chatPartner[p])) {
2897 talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
2898 chattingPartner = p; break;
2901 if(chattingPartner < 0)
2902 for(p=0; p<MAX_CHAT; p++) {
2903 if(!strcmp("shouts", chatPartner[p])) {
2904 if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
2905 else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
2906 else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
2907 chattingPartner = p; break;
2911 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
2912 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
2913 talker[0] = 0; Colorize(ColorTell, FALSE);
2914 chattingPartner = p; break;
2916 if(chattingPartner<0) i = oldi; else {
2917 Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
2918 if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
2919 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2920 started = STARTED_COMMENT;
2921 parse_pos = 0; parse[0] = NULLCHAR;
2922 savingComment = 3 + chattingPartner; // counts as TRUE
2923 suppressKibitz = TRUE;
2926 } // [HGM] chat: end of patch
2928 if (appData.zippyTalk || appData.zippyPlay) {
2929 /* [DM] Backup address for color zippy lines */
2932 if (loggedOn == TRUE)
2933 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
2934 (appData.zippyPlay && ZippyMatch(buf, &backup)));
2936 } // [DM] 'else { ' deleted
2938 /* Regular tells and says */
2939 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
2940 looking_at(buf, &i, "* (your partner) tells you: ") ||
2941 looking_at(buf, &i, "* says: ") ||
2942 /* Don't color "message" or "messages" output */
2943 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
2944 looking_at(buf, &i, "*. * at *:*: ") ||
2945 looking_at(buf, &i, "--* (*:*): ") ||
2946 /* Message notifications (same color as tells) */
2947 looking_at(buf, &i, "* has left a message ") ||
2948 looking_at(buf, &i, "* just sent you a message:\n") ||
2949 /* Whispers and kibitzes */
2950 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
2951 looking_at(buf, &i, "* kibitzes: ") ||
2953 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
2955 if (tkind == 1 && strchr(star_match[0], ':')) {
2956 /* Avoid "tells you:" spoofs in channels */
2959 if (star_match[0][0] == NULLCHAR ||
2960 strchr(star_match[0], ' ') ||
2961 (tkind == 3 && strchr(star_match[1], ' '))) {
2962 /* Reject bogus matches */
2965 if (appData.colorize) {
2966 if (oldi > next_out) {
2967 SendToPlayer(&buf[next_out], oldi - next_out);
2972 Colorize(ColorTell, FALSE);
2973 curColor = ColorTell;
2976 Colorize(ColorKibitz, FALSE);
2977 curColor = ColorKibitz;
2980 p = strrchr(star_match[1], '(');
2987 Colorize(ColorChannel1, FALSE);
2988 curColor = ColorChannel1;
2990 Colorize(ColorChannel, FALSE);
2991 curColor = ColorChannel;
2995 curColor = ColorNormal;
2999 if (started == STARTED_NONE && appData.autoComment &&
3000 (gameMode == IcsObserving ||
3001 gameMode == IcsPlayingWhite ||
3002 gameMode == IcsPlayingBlack)) {
3003 parse_pos = i - oldi;
3004 memcpy(parse, &buf[oldi], parse_pos);
3005 parse[parse_pos] = NULLCHAR;
3006 started = STARTED_COMMENT;
3007 savingComment = TRUE;
3009 started = STARTED_CHATTER;
3010 savingComment = FALSE;
3017 if (looking_at(buf, &i, "* s-shouts: ") ||
3018 looking_at(buf, &i, "* c-shouts: ")) {
3019 if (appData.colorize) {
3020 if (oldi > next_out) {
3021 SendToPlayer(&buf[next_out], oldi - next_out);
3024 Colorize(ColorSShout, FALSE);
3025 curColor = ColorSShout;
3028 started = STARTED_CHATTER;
3032 if (looking_at(buf, &i, "--->")) {
3037 if (looking_at(buf, &i, "* shouts: ") ||
3038 looking_at(buf, &i, "--> ")) {
3039 if (appData.colorize) {
3040 if (oldi > next_out) {
3041 SendToPlayer(&buf[next_out], oldi - next_out);
3044 Colorize(ColorShout, FALSE);
3045 curColor = ColorShout;
3048 started = STARTED_CHATTER;
3052 if (looking_at( buf, &i, "Challenge:")) {
3053 if (appData.colorize) {
3054 if (oldi > next_out) {
3055 SendToPlayer(&buf[next_out], oldi - next_out);
3058 Colorize(ColorChallenge, FALSE);
3059 curColor = ColorChallenge;
3065 if (looking_at(buf, &i, "* offers you") ||
3066 looking_at(buf, &i, "* offers to be") ||
3067 looking_at(buf, &i, "* would like to") ||
3068 looking_at(buf, &i, "* requests to") ||
3069 looking_at(buf, &i, "Your opponent offers") ||
3070 looking_at(buf, &i, "Your opponent requests")) {
3072 if (appData.colorize) {
3073 if (oldi > next_out) {
3074 SendToPlayer(&buf[next_out], oldi - next_out);
3077 Colorize(ColorRequest, FALSE);
3078 curColor = ColorRequest;
3083 if (looking_at(buf, &i, "* (*) seeking")) {
3084 if (appData.colorize) {
3085 if (oldi > next_out) {
3086 SendToPlayer(&buf[next_out], oldi - next_out);
3089 Colorize(ColorSeek, FALSE);
3090 curColor = ColorSeek;
3095 if (looking_at(buf, &i, "\\ ")) {
3096 if (prevColor != ColorNormal) {
3097 if (oldi > next_out) {
3098 SendToPlayer(&buf[next_out], oldi - next_out);
3101 Colorize(prevColor, TRUE);
3102 curColor = prevColor;
3104 if (savingComment) {
3105 parse_pos = i - oldi;
3106 memcpy(parse, &buf[oldi], parse_pos);
3107 parse[parse_pos] = NULLCHAR;
3108 started = STARTED_COMMENT;
3109 if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3110 chattingPartner = savingComment - 3; // kludge to remember the box
3112 started = STARTED_CHATTER;
3117 if (looking_at(buf, &i, "Black Strength :") ||
3118 looking_at(buf, &i, "<<< style 10 board >>>") ||
3119 looking_at(buf, &i, "<10>") ||
3120 looking_at(buf, &i, "#@#")) {
3121 /* Wrong board style */
3123 SendToICS(ics_prefix);
3124 SendToICS("set style 12\n");
3125 SendToICS(ics_prefix);
3126 SendToICS("refresh\n");
3130 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
3132 have_sent_ICS_logon = 1;
3136 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3137 (looking_at(buf, &i, "\n<12> ") ||
3138 looking_at(buf, &i, "<12> "))) {
3140 if (oldi > next_out) {
3141 SendToPlayer(&buf[next_out], oldi - next_out);
3144 started = STARTED_BOARD;
3149 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3150 looking_at(buf, &i, "<b1> ")) {
3151 if (oldi > next_out) {
3152 SendToPlayer(&buf[next_out], oldi - next_out);
3155 started = STARTED_HOLDINGS;
3160 if (looking_at(buf, &i, "* *vs. * *--- *")) {
3162 /* Header for a move list -- first line */
3164 switch (ics_getting_history) {
3168 case BeginningOfGame:
3169 /* User typed "moves" or "oldmoves" while we
3170 were idle. Pretend we asked for these
3171 moves and soak them up so user can step
3172 through them and/or save them.
3175 gameMode = IcsObserving;
3178 ics_getting_history = H_GOT_UNREQ_HEADER;
3180 case EditGame: /*?*/
3181 case EditPosition: /*?*/
3182 /* Should above feature work in these modes too? */
3183 /* For now it doesn't */
3184 ics_getting_history = H_GOT_UNWANTED_HEADER;
3187 ics_getting_history = H_GOT_UNWANTED_HEADER;
3192 /* Is this the right one? */
3193 if (gameInfo.white && gameInfo.black &&
3194 strcmp(gameInfo.white, star_match[0]) == 0 &&
3195 strcmp(gameInfo.black, star_match[2]) == 0) {
3197 ics_getting_history = H_GOT_REQ_HEADER;
3200 case H_GOT_REQ_HEADER:
3201 case H_GOT_UNREQ_HEADER:
3202 case H_GOT_UNWANTED_HEADER:
3203 case H_GETTING_MOVES:
3204 /* Should not happen */
3205 DisplayError(_("Error gathering move list: two headers"), 0);
3206 ics_getting_history = H_FALSE;
3210 /* Save player ratings into gameInfo if needed */
3211 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3212 ics_getting_history == H_GOT_UNREQ_HEADER) &&
3213 (gameInfo.whiteRating == -1 ||
3214 gameInfo.blackRating == -1)) {
3216 gameInfo.whiteRating = string_to_rating(star_match[1]);
3217 gameInfo.blackRating = string_to_rating(star_match[3]);
3218 if (appData.debugMode)
3219 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
3220 gameInfo.whiteRating, gameInfo.blackRating);
3225 if (looking_at(buf, &i,
3226 "* * match, initial time: * minute*, increment: * second")) {
3227 /* Header for a move list -- second line */
3228 /* Initial board will follow if this is a wild game */
3229 if (gameInfo.event != NULL) free(gameInfo.event);
3230 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3231 gameInfo.event = StrSave(str);
3232 /* [HGM] we switched variant. Translate boards if needed. */
3233 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3237 if (looking_at(buf, &i, "Move ")) {
3238 /* Beginning of a move list */
3239 switch (ics_getting_history) {
3241 /* Normally should not happen */
3242 /* Maybe user hit reset while we were parsing */
3245 /* Happens if we are ignoring a move list that is not
3246 * the one we just requested. Common if the user
3247 * tries to observe two games without turning off
3250 case H_GETTING_MOVES:
3251 /* Should not happen */
3252 DisplayError(_("Error gathering move list: nested"), 0);
3253 ics_getting_history = H_FALSE;
3255 case H_GOT_REQ_HEADER:
3256 ics_getting_history = H_GETTING_MOVES;
3257 started = STARTED_MOVES;
3259 if (oldi > next_out) {
3260 SendToPlayer(&buf[next_out], oldi - next_out);
3263 case H_GOT_UNREQ_HEADER:
3264 ics_getting_history = H_GETTING_MOVES;
3265 started = STARTED_MOVES_NOHIDE;
3268 case H_GOT_UNWANTED_HEADER:
3269 ics_getting_history = H_FALSE;
3275 if (looking_at(buf, &i, "% ") ||
3276 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3277 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3278 if(ics_type == ICS_ICC && soughtPending) { // [HGM] seekgraph: on ICC sought-list has no termination line
3279 soughtPending = FALSE;
3283 if(suppressKibitz) next_out = i;
3284 savingComment = FALSE;
3288 case STARTED_MOVES_NOHIDE:
3289 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3290 parse[parse_pos + i - oldi] = NULLCHAR;
3291 ParseGameHistory(parse);
3293 if (appData.zippyPlay && first.initDone) {
3294 FeedMovesToProgram(&first, forwardMostMove);
3295 if (gameMode == IcsPlayingWhite) {
3296 if (WhiteOnMove(forwardMostMove)) {
3297 if (first.sendTime) {
3298 if (first.useColors) {
3299 SendToProgram("black\n", &first);
3301 SendTimeRemaining(&first, TRUE);
3303 if (first.useColors) {
3304 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3306 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3307 first.maybeThinking = TRUE;
3309 if (first.usePlayother) {
3310 if (first.sendTime) {
3311 SendTimeRemaining(&first, TRUE);
3313 SendToProgram("playother\n", &first);
3319 } else if (gameMode == IcsPlayingBlack) {
3320 if (!WhiteOnMove(forwardMostMove)) {
3321 if (first.sendTime) {
3322 if (first.useColors) {
3323 SendToProgram("white\n", &first);
3325 SendTimeRemaining(&first, FALSE);
3327 if (first.useColors) {
3328 SendToProgram("black\n", &first);
3330 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3331 first.maybeThinking = TRUE;
3333 if (first.usePlayother) {
3334 if (first.sendTime) {
3335 SendTimeRemaining(&first, FALSE);
3337 SendToProgram("playother\n", &first);
3346 if (gameMode == IcsObserving && ics_gamenum == -1) {
3347 /* Moves came from oldmoves or moves command
3348 while we weren't doing anything else.
3350 currentMove = forwardMostMove;
3351 ClearHighlights();/*!!could figure this out*/
3352 flipView = appData.flipView;
3353 DrawPosition(TRUE, boards[currentMove]);
3354 DisplayBothClocks();
3355 snprintf(str, MSG_SIZ, "%s vs. %s",
3356 gameInfo.white, gameInfo.black);
3360 /* Moves were history of an active game */
3361 if (gameInfo.resultDetails != NULL) {
3362 free(gameInfo.resultDetails);
3363 gameInfo.resultDetails = NULL;
3366 HistorySet(parseList, backwardMostMove,
3367 forwardMostMove, currentMove-1);
3368 DisplayMove(currentMove - 1);
3369 if (started == STARTED_MOVES) next_out = i;
3370 started = STARTED_NONE;
3371 ics_getting_history = H_FALSE;
3374 case STARTED_OBSERVE:
3375 started = STARTED_NONE;
3376 SendToICS(ics_prefix);
3377 SendToICS("refresh\n");
3383 if(bookHit) { // [HGM] book: simulate book reply
3384 static char bookMove[MSG_SIZ]; // a bit generous?
3386 programStats.nodes = programStats.depth = programStats.time =
3387 programStats.score = programStats.got_only_move = 0;
3388 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3390 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3391 strcat(bookMove, bookHit);
3392 HandleMachineMove(bookMove, &first);
3397 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3398 started == STARTED_HOLDINGS ||
3399 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3400 /* Accumulate characters in move list or board */
3401 parse[parse_pos++] = buf[i];
3404 /* Start of game messages. Mostly we detect start of game
3405 when the first board image arrives. On some versions
3406 of the ICS, though, we need to do a "refresh" after starting
3407 to observe in order to get the current board right away. */
3408 if (looking_at(buf, &i, "Adding game * to observation list")) {
3409 started = STARTED_OBSERVE;
3413 /* Handle auto-observe */
3414 if (appData.autoObserve &&
3415 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3416 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3418 /* Choose the player that was highlighted, if any. */
3419 if (star_match[0][0] == '\033' ||
3420 star_match[1][0] != '\033') {
3421 player = star_match[0];
3423 player = star_match[2];
3425 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3426 ics_prefix, StripHighlightAndTitle(player));
3429 /* Save ratings from notify string */
3430 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3431 player1Rating = string_to_rating(star_match[1]);
3432 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3433 player2Rating = string_to_rating(star_match[3]);
3435 if (appData.debugMode)
3437 "Ratings from 'Game notification:' %s %d, %s %d\n",
3438 player1Name, player1Rating,
3439 player2Name, player2Rating);
3444 /* Deal with automatic examine mode after a game,
3445 and with IcsObserving -> IcsExamining transition */
3446 if (looking_at(buf, &i, "Entering examine mode for game *") ||
3447 looking_at(buf, &i, "has made you an examiner of game *")) {
3449 int gamenum = atoi(star_match[0]);
3450 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3451 gamenum == ics_gamenum) {
3452 /* We were already playing or observing this game;
3453 no need to refetch history */
3454 gameMode = IcsExamining;
3456 pauseExamForwardMostMove = forwardMostMove;
3457 } else if (currentMove < forwardMostMove) {
3458 ForwardInner(forwardMostMove);
3461 /* I don't think this case really can happen */
3462 SendToICS(ics_prefix);
3463 SendToICS("refresh\n");
3468 /* Error messages */
3469 // if (ics_user_moved) {
3470 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3471 if (looking_at(buf, &i, "Illegal move") ||
3472 looking_at(buf, &i, "Not a legal move") ||
3473 looking_at(buf, &i, "Your king is in check") ||
3474 looking_at(buf, &i, "It isn't your turn") ||
3475 looking_at(buf, &i, "It is not your move")) {
3477 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3478 currentMove = forwardMostMove-1;
3479 DisplayMove(currentMove - 1); /* before DMError */
3480 DrawPosition(FALSE, boards[currentMove]);
3481 SwitchClocks(forwardMostMove-1); // [HGM] race
3482 DisplayBothClocks();
3484 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3490 if (looking_at(buf, &i, "still have time") ||
3491 looking_at(buf, &i, "not out of time") ||
3492 looking_at(buf, &i, "either player is out of time") ||
3493 looking_at(buf, &i, "has timeseal; checking")) {
3494 /* We must have called his flag a little too soon */
3495 whiteFlag = blackFlag = FALSE;
3499 if (looking_at(buf, &i, "added * seconds to") ||
3500 looking_at(buf, &i, "seconds were added to")) {
3501 /* Update the clocks */
3502 SendToICS(ics_prefix);
3503 SendToICS("refresh\n");
3507 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3508 ics_clock_paused = TRUE;
3513 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3514 ics_clock_paused = FALSE;
3519 /* Grab player ratings from the Creating: message.
3520 Note we have to check for the special case when
3521 the ICS inserts things like [white] or [black]. */
3522 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3523 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3525 0 player 1 name (not necessarily white)
3527 2 empty, white, or black (IGNORED)
3528 3 player 2 name (not necessarily black)
3531 The names/ratings are sorted out when the game
3532 actually starts (below).
3534 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
3535 player1Rating = string_to_rating(star_match[1]);
3536 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
3537 player2Rating = string_to_rating(star_match[4]);
3539 if (appData.debugMode)
3541 "Ratings from 'Creating:' %s %d, %s %d\n",
3542 player1Name, player1Rating,
3543 player2Name, player2Rating);
3548 /* Improved generic start/end-of-game messages */
3549 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3550 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3551 /* If tkind == 0: */
3552 /* star_match[0] is the game number */
3553 /* [1] is the white player's name */
3554 /* [2] is the black player's name */
3555 /* For end-of-game: */
3556 /* [3] is the reason for the game end */
3557 /* [4] is a PGN end game-token, preceded by " " */
3558 /* For start-of-game: */
3559 /* [3] begins with "Creating" or "Continuing" */
3560 /* [4] is " *" or empty (don't care). */
3561 int gamenum = atoi(star_match[0]);
3562 char *whitename, *blackname, *why, *endtoken;
3563 ChessMove endtype = EndOfFile;
3566 whitename = star_match[1];
3567 blackname = star_match[2];
3568 why = star_match[3];
3569 endtoken = star_match[4];
3571 whitename = star_match[1];
3572 blackname = star_match[3];
3573 why = star_match[5];
3574 endtoken = star_match[6];
3577 /* Game start messages */
3578 if (strncmp(why, "Creating ", 9) == 0 ||
3579 strncmp(why, "Continuing ", 11) == 0) {
3580 gs_gamenum = gamenum;
3581 safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
3582 VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
3584 if (appData.zippyPlay) {
3585 ZippyGameStart(whitename, blackname);
3588 partnerBoardValid = FALSE; // [HGM] bughouse
3592 /* Game end messages */
3593 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3594 ics_gamenum != gamenum) {
3597 while (endtoken[0] == ' ') endtoken++;
3598 switch (endtoken[0]) {
3601 endtype = GameUnfinished;
3604 endtype = BlackWins;
3607 if (endtoken[1] == '/')
3608 endtype = GameIsDrawn;
3610 endtype = WhiteWins;
3613 GameEnds(endtype, why, GE_ICS);
3615 if (appData.zippyPlay && first.initDone) {
3616 ZippyGameEnd(endtype, why);
3617 if (first.pr == NULL) {
3618 /* Start the next process early so that we'll
3619 be ready for the next challenge */
3620 StartChessProgram(&first);
3622 /* Send "new" early, in case this command takes
3623 a long time to finish, so that we'll be ready
3624 for the next challenge. */
3625 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3629 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
3633 if (looking_at(buf, &i, "Removing game * from observation") ||
3634 looking_at(buf, &i, "no longer observing game *") ||
3635 looking_at(buf, &i, "Game * (*) has no examiners")) {
3636 if (gameMode == IcsObserving &&
3637 atoi(star_match[0]) == ics_gamenum)
3639 /* icsEngineAnalyze */
3640 if (appData.icsEngineAnalyze) {
3647 ics_user_moved = FALSE;
3652 if (looking_at(buf, &i, "no longer examining game *")) {
3653 if (gameMode == IcsExamining &&
3654 atoi(star_match[0]) == ics_gamenum)
3658 ics_user_moved = FALSE;
3663 /* Advance leftover_start past any newlines we find,
3664 so only partial lines can get reparsed */
3665 if (looking_at(buf, &i, "\n")) {
3666 prevColor = curColor;
3667 if (curColor != ColorNormal) {
3668 if (oldi > next_out) {
3669 SendToPlayer(&buf[next_out], oldi - next_out);
3672 Colorize(ColorNormal, FALSE);
3673 curColor = ColorNormal;
3675 if (started == STARTED_BOARD) {
3676 started = STARTED_NONE;
3677 parse[parse_pos] = NULLCHAR;
3678 ParseBoard12(parse);
3681 /* Send premove here */
3682 if (appData.premove) {
3684 if (currentMove == 0 &&
3685 gameMode == IcsPlayingWhite &&
3686 appData.premoveWhite) {
3687 snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
3688 if (appData.debugMode)
3689 fprintf(debugFP, "Sending premove:\n");
3691 } else if (currentMove == 1 &&
3692 gameMode == IcsPlayingBlack &&
3693 appData.premoveBlack) {
3694 snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
3695 if (appData.debugMode)
3696 fprintf(debugFP, "Sending premove:\n");
3698 } else if (gotPremove) {
3700 ClearPremoveHighlights();
3701 if (appData.debugMode)
3702 fprintf(debugFP, "Sending premove:\n");
3703 UserMoveEvent(premoveFromX, premoveFromY,
3704 premoveToX, premoveToY,
3709 /* Usually suppress following prompt */
3710 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
3711 while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
3712 if (looking_at(buf, &i, "*% ")) {
3713 savingComment = FALSE;
3718 } else if (started == STARTED_HOLDINGS) {
3720 char new_piece[MSG_SIZ];
3721 started = STARTED_NONE;
3722 parse[parse_pos] = NULLCHAR;
3723 if (appData.debugMode)
3724 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
3725 parse, currentMove);
3726 if (sscanf(parse, " game %d", &gamenum) == 1) {
3727 if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
3728 if (gameInfo.variant == VariantNormal) {
3729 /* [HGM] We seem to switch variant during a game!
3730 * Presumably no holdings were displayed, so we have
3731 * to move the position two files to the right to
3732 * create room for them!
3734 VariantClass newVariant;
3735 switch(gameInfo.boardWidth) { // base guess on board width
3736 case 9: newVariant = VariantShogi; break;
3737 case 10: newVariant = VariantGreat; break;
3738 default: newVariant = VariantCrazyhouse; break;
3740 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
3741 /* Get a move list just to see the header, which
3742 will tell us whether this is really bug or zh */
3743 if (ics_getting_history == H_FALSE) {
3744 ics_getting_history = H_REQUESTED;
3745 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
3749 new_piece[0] = NULLCHAR;
3750 sscanf(parse, "game %d white [%s black [%s <- %s",
3751 &gamenum, white_holding, black_holding,
3753 white_holding[strlen(white_holding)-1] = NULLCHAR;
3754 black_holding[strlen(black_holding)-1] = NULLCHAR;
3755 /* [HGM] copy holdings to board holdings area */
3756 CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
3757 CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
3758 boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
3760 if (appData.zippyPlay && first.initDone) {
3761 ZippyHoldings(white_holding, black_holding,
3765 if (tinyLayout || smallLayout) {
3766 char wh[16], bh[16];
3767 PackHolding(wh, white_holding);
3768 PackHolding(bh, black_holding);
3769 snprintf(str, MSG_SIZ,"[%s-%s] %s-%s", wh, bh,
3770 gameInfo.white, gameInfo.black);
3772 snprintf(str, MSG_SIZ, "%s [%s] vs. %s [%s]",
3773 gameInfo.white, white_holding,
3774 gameInfo.black, black_holding);
3776 if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
3777 DrawPosition(FALSE, boards[currentMove]);
3779 } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
3780 sscanf(parse, "game %d white [%s black [%s <- %s",
3781 &gamenum, white_holding, black_holding,
3783 white_holding[strlen(white_holding)-1] = NULLCHAR;
3784 black_holding[strlen(black_holding)-1] = NULLCHAR;
3785 /* [HGM] copy holdings to partner-board holdings area */
3786 CopyHoldings(partnerBoard, white_holding, WhitePawn);
3787 CopyHoldings(partnerBoard, black_holding, BlackPawn);
3788 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
3789 if(partnerUp) DrawPosition(FALSE, partnerBoard);
3790 if(twoBoards) { partnerUp = 0; flipView = !flipView; }
3793 /* Suppress following prompt */
3794 if (looking_at(buf, &i, "*% ")) {
3795 if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
3796 savingComment = FALSE;
3804 i++; /* skip unparsed character and loop back */
3807 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
3808 // started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
3809 // SendToPlayer(&buf[next_out], i - next_out);
3810 started != STARTED_HOLDINGS && leftover_start > next_out) {
3811 SendToPlayer(&buf[next_out], leftover_start - next_out);
3815 leftover_len = buf_len - leftover_start;
3816 /* if buffer ends with something we couldn't parse,
3817 reparse it after appending the next read */
3819 } else if (count == 0) {
3820 RemoveInputSource(isr);
3821 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
3823 DisplayFatalError(_("Error reading from ICS"), error, 1);
3828 /* Board style 12 looks like this:
3830 <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
3832 * The "<12> " is stripped before it gets to this routine. The two
3833 * trailing 0's (flip state and clock ticking) are later addition, and
3834 * some chess servers may not have them, or may have only the first.
3835 * Additional trailing fields may be added in the future.
3838 #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"
3840 #define RELATION_OBSERVING_PLAYED 0
3841 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
3842 #define RELATION_PLAYING_MYMOVE 1
3843 #define RELATION_PLAYING_NOTMYMOVE -1
3844 #define RELATION_EXAMINING 2
3845 #define RELATION_ISOLATED_BOARD -3
3846 #define RELATION_STARTING_POSITION -4 /* FICS only */
3849 ParseBoard12(string)
3852 GameMode newGameMode;
3853 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0, i;
3854 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time, takeback;
3855 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
3856 char to_play, board_chars[200];
3857 char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
3858 char black[32], white[32];
3860 int prevMove = currentMove;
3863 int fromX, fromY, toX, toY;
3865 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
3866 char *bookHit = NULL; // [HGM] book
3867 Boolean weird = FALSE, reqFlag = FALSE;
3869 fromX = fromY = toX = toY = -1;
3873 if (appData.debugMode)
3874 fprintf(debugFP, _("Parsing board: %s\n"), string);
3876 move_str[0] = NULLCHAR;
3877 elapsed_time[0] = NULLCHAR;
3878 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
3880 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
3881 if(string[i] == ' ') { ranks++; files = 0; }
3883 if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
3886 for(j = 0; j <i; j++) board_chars[j] = string[j];
3887 board_chars[i] = '\0';
3890 n = sscanf(string, PATTERN, &to_play, &double_push,
3891 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
3892 &gamenum, white, black, &relation, &basetime, &increment,
3893 &white_stren, &black_stren, &white_time, &black_time,
3894 &moveNum, str, elapsed_time, move_str, &ics_flip,
3898 snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
3899 DisplayError(str, 0);
3903 /* Convert the move number to internal form */
3904 moveNum = (moveNum - 1) * 2;
3905 if (to_play == 'B') moveNum++;
3906 if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
3907 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
3913 case RELATION_OBSERVING_PLAYED:
3914 case RELATION_OBSERVING_STATIC:
3915 if (gamenum == -1) {
3916 /* Old ICC buglet */
3917 relation = RELATION_OBSERVING_STATIC;
3919 newGameMode = IcsObserving;
3921 case RELATION_PLAYING_MYMOVE:
3922 case RELATION_PLAYING_NOTMYMOVE:
3924 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
3925 IcsPlayingWhite : IcsPlayingBlack;
3927 case RELATION_EXAMINING:
3928 newGameMode = IcsExamining;
3930 case RELATION_ISOLATED_BOARD:
3932 /* Just display this board. If user was doing something else,
3933 we will forget about it until the next board comes. */
3934 newGameMode = IcsIdle;
3936 case RELATION_STARTING_POSITION:
3937 newGameMode = gameMode;
3941 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
3942 && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
3943 // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
3945 for (k = 0; k < ranks; k++) {
3946 for (j = 0; j < files; j++)
3947 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
3948 if(gameInfo.holdingsWidth > 1) {
3949 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
3950 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
3953 CopyBoard(partnerBoard, board);
3954 if(toSqr = strchr(str, '/')) { // extract highlights from long move
3955 partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
3956 partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
3957 } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
3958 if(toSqr = strchr(str, '-')) {
3959 partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
3960 partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
3961 } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
3962 if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
3963 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
3964 if(partnerUp) DrawPosition(FALSE, partnerBoard);
3965 if(twoBoards) { partnerUp = 0; flipView = !flipView; } // [HGM] dual
3966 snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time/60000, (white_time%60000)/1000,
3967 (black_time/60000), (black_time%60000)/1000, white_stren, black_stren, to_play);
3968 DisplayMessage(partnerStatus, "");
3969 partnerBoardValid = TRUE;
3973 /* Modify behavior for initial board display on move listing
3976 switch (ics_getting_history) {
3980 case H_GOT_REQ_HEADER:
3981 case H_GOT_UNREQ_HEADER:
3982 /* This is the initial position of the current game */
3983 gamenum = ics_gamenum;
3984 moveNum = 0; /* old ICS bug workaround */
3985 if (to_play == 'B') {
3986 startedFromSetupPosition = TRUE;
3987 blackPlaysFirst = TRUE;
3989 if (forwardMostMove == 0) forwardMostMove = 1;
3990 if (backwardMostMove == 0) backwardMostMove = 1;
3991 if (currentMove == 0) currentMove = 1;
3993 newGameMode = gameMode;
3994 relation = RELATION_STARTING_POSITION; /* ICC needs this */
3996 case H_GOT_UNWANTED_HEADER:
3997 /* This is an initial board that we don't want */
3999 case H_GETTING_MOVES:
4000 /* Should not happen */
4001 DisplayError(_("Error gathering move list: extra board"), 0);
4002 ics_getting_history = H_FALSE;
4006 if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4007 weird && (int)gameInfo.variant < (int)VariantShogi) {
4008 /* [HGM] We seem to have switched variant unexpectedly
4009 * Try to guess new variant from board size
4011 VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4012 if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4013 if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4014 if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4015 if(ranks == 9 && files == 9) newVariant = VariantShogi; else
4016 if(!weird) newVariant = VariantNormal;
4017 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4018 /* Get a move list just to see the header, which
4019 will tell us whether this is really bug or zh */
4020 if (ics_getting_history == H_FALSE) {
4021 ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4022 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4027 /* Take action if this is the first board of a new game, or of a
4028 different game than is currently being displayed. */
4029 if (gamenum != ics_gamenum || newGameMode != gameMode ||
4030 relation == RELATION_ISOLATED_BOARD) {
4032 /* Forget the old game and get the history (if any) of the new one */
4033 if (gameMode != BeginningOfGame) {
4037 if (appData.autoRaiseBoard) BoardToTop();
4039 if (gamenum == -1) {
4040 newGameMode = IcsIdle;
4041 } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4042 appData.getMoveList && !reqFlag) {
4043 /* Need to get game history */
4044 ics_getting_history = H_REQUESTED;
4045 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4049 /* Initially flip the board to have black on the bottom if playing
4050 black or if the ICS flip flag is set, but let the user change
4051 it with the Flip View button. */
4052 flipView = appData.autoFlipView ?
4053 (newGameMode == IcsPlayingBlack) || ics_flip :
4056 /* Done with values from previous mode; copy in new ones */
4057 gameMode = newGameMode;
4059 ics_gamenum = gamenum;
4060 if (gamenum == gs_gamenum) {
4061 int klen = strlen(gs_kind);
4062 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4063 snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4064 gameInfo.event = StrSave(str);
4066 gameInfo.event = StrSave("ICS game");
4068 gameInfo.site = StrSave(appData.icsHost);
4069 gameInfo.date = PGNDate();
4070 gameInfo.round = StrSave("-");
4071 gameInfo.white = StrSave(white);
4072 gameInfo.black = StrSave(black);
4073 timeControl = basetime * 60 * 1000;
4075 timeIncrement = increment * 1000;
4076 movesPerSession = 0;
4077 gameInfo.timeControl = TimeControlTagValue();
4078 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4079 if (appData.debugMode) {
4080 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4081 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4082 setbuf(debugFP, NULL);
4085 gameInfo.outOfBook = NULL;
4087 /* Do we have the ratings? */
4088 if (strcmp(player1Name, white) == 0 &&
4089 strcmp(player2Name, black) == 0) {
4090 if (appData.debugMode)
4091 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4092 player1Rating, player2Rating);
4093 gameInfo.whiteRating = player1Rating;
4094 gameInfo.blackRating = player2Rating;
4095 } else if (strcmp(player2Name, white) == 0 &&
4096 strcmp(player1Name, black) == 0) {
4097 if (appData.debugMode)
4098 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4099 player2Rating, player1Rating);
4100 gameInfo.whiteRating = player2Rating;
4101 gameInfo.blackRating = player1Rating;
4103 player1Name[0] = player2Name[0] = NULLCHAR;
4105 /* Silence shouts if requested */
4106 if (appData.quietPlay &&
4107 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4108 SendToICS(ics_prefix);
4109 SendToICS("set shout 0\n");
4113 /* Deal with midgame name changes */
4115 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4116 if (gameInfo.white) free(gameInfo.white);
4117 gameInfo.white = StrSave(white);
4119 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4120 if (gameInfo.black) free(gameInfo.black);
4121 gameInfo.black = StrSave(black);
4125 /* Throw away game result if anything actually changes in examine mode */
4126 if (gameMode == IcsExamining && !newGame) {
4127 gameInfo.result = GameUnfinished;
4128 if (gameInfo.resultDetails != NULL) {
4129 free(gameInfo.resultDetails);
4130 gameInfo.resultDetails = NULL;
4134 /* In pausing && IcsExamining mode, we ignore boards coming
4135 in if they are in a different variation than we are. */
4136 if (pauseExamInvalid) return;
4137 if (pausing && gameMode == IcsExamining) {
4138 if (moveNum <= pauseExamForwardMostMove) {
4139 pauseExamInvalid = TRUE;
4140 forwardMostMove = pauseExamForwardMostMove;
4145 if (appData.debugMode) {
4146 fprintf(debugFP, "load %dx%d board\n", files, ranks);
4148 /* Parse the board */
4149 for (k = 0; k < ranks; k++) {
4150 for (j = 0; j < files; j++)
4151 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4152 if(gameInfo.holdingsWidth > 1) {
4153 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4154 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4157 CopyBoard(boards[moveNum], board);
4158 boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4160 startedFromSetupPosition =
4161 !CompareBoards(board, initialPosition);
4162 if(startedFromSetupPosition)
4163 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4166 /* [HGM] Set castling rights. Take the outermost Rooks,
4167 to make it also work for FRC opening positions. Note that board12
4168 is really defective for later FRC positions, as it has no way to
4169 indicate which Rook can castle if they are on the same side of King.
4170 For the initial position we grant rights to the outermost Rooks,
4171 and remember thos rights, and we then copy them on positions
4172 later in an FRC game. This means WB might not recognize castlings with
4173 Rooks that have moved back to their original position as illegal,
4174 but in ICS mode that is not its job anyway.
4176 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4177 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4179 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4180 if(board[0][i] == WhiteRook) j = i;
4181 initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4182 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4183 if(board[0][i] == WhiteRook) j = i;
4184 initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4185 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4186 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4187 initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4188 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4189 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4190 initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4192 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4193 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4194 if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4195 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4196 if(board[BOARD_HEIGHT-1][k] == bKing)
4197 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4198 if(gameInfo.variant == VariantTwoKings) {
4199 // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4200 if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4201 if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4204 r = boards[moveNum][CASTLING][0] = initialRights[0];
4205 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4206 r = boards[moveNum][CASTLING][1] = initialRights[1];
4207 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4208 r = boards[moveNum][CASTLING][3] = initialRights[3];
4209 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4210 r = boards[moveNum][CASTLING][4] = initialRights[4];
4211 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4212 /* wildcastle kludge: always assume King has rights */
4213 r = boards[moveNum][CASTLING][2] = initialRights[2];
4214 r = boards[moveNum][CASTLING][5] = initialRights[5];
4216 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4217 boards[moveNum][EP_STATUS] = double_push == -1 ? EP_NONE : double_push + BOARD_LEFT;
4220 if (ics_getting_history == H_GOT_REQ_HEADER ||
4221 ics_getting_history == H_GOT_UNREQ_HEADER) {
4222 /* This was an initial position from a move list, not
4223 the current position */
4227 /* Update currentMove and known move number limits */
4228 newMove = newGame || moveNum > forwardMostMove;
4231 forwardMostMove = backwardMostMove = currentMove = moveNum;
4232 if (gameMode == IcsExamining && moveNum == 0) {
4233 /* Workaround for ICS limitation: we are not told the wild
4234 type when starting to examine a game. But if we ask for
4235 the move list, the move list header will tell us */
4236 ics_getting_history = H_REQUESTED;
4237 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4240 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4241 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4243 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4244 /* [HGM] applied this also to an engine that is silently watching */
4245 if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4246 (gameMode == IcsObserving || gameMode == IcsExamining) &&
4247 gameInfo.variant == currentlyInitializedVariant) {
4248 takeback = forwardMostMove - moveNum;
4249 for (i = 0; i < takeback; i++) {
4250 if (appData.debugMode) fprintf(debugFP, "take back move\n");
4251 SendToProgram("undo\n", &first);
4256 forwardMostMove = moveNum;
4257 if (!pausing || currentMove > forwardMostMove)
4258 currentMove = forwardMostMove;
4260 /* New part of history that is not contiguous with old part */
4261 if (pausing && gameMode == IcsExamining) {
4262 pauseExamInvalid = TRUE;
4263 forwardMostMove = pauseExamForwardMostMove;
4266 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4268 if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4269 // [HGM] when we will receive the move list we now request, it will be
4270 // fed to the engine from the first move on. So if the engine is not
4271 // in the initial position now, bring it there.
4272 InitChessProgram(&first, 0);
4275 ics_getting_history = H_REQUESTED;
4276 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4279 forwardMostMove = backwardMostMove = currentMove = moveNum;
4282 /* Update the clocks */
4283 if (strchr(elapsed_time, '.')) {
4285 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4286 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4288 /* Time is in seconds */
4289 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4290 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4295 if (appData.zippyPlay && newGame &&
4296 gameMode != IcsObserving && gameMode != IcsIdle &&
4297 gameMode != IcsExamining)
4298 ZippyFirstBoard(moveNum, basetime, increment);
4301 /* Put the move on the move list, first converting
4302 to canonical algebraic form. */
4304 if (appData.debugMode) {
4305 if (appData.debugMode) { int f = forwardMostMove;
4306 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4307 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4308 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4310 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4311 fprintf(debugFP, "moveNum = %d\n", moveNum);
4312 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4313 setbuf(debugFP, NULL);
4315 if (moveNum <= backwardMostMove) {
4316 /* We don't know what the board looked like before
4318 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4319 strcat(parseList[moveNum - 1], " ");
4320 strcat(parseList[moveNum - 1], elapsed_time);
4321 moveList[moveNum - 1][0] = NULLCHAR;
4322 } else if (strcmp(move_str, "none") == 0) {
4323 // [HGM] long SAN: swapped order; test for 'none' before parsing move
4324 /* Again, we don't know what the board looked like;
4325 this is really the start of the game. */
4326 parseList[moveNum - 1][0] = NULLCHAR;
4327 moveList[moveNum - 1][0] = NULLCHAR;
4328 backwardMostMove = moveNum;
4329 startedFromSetupPosition = TRUE;
4330 fromX = fromY = toX = toY = -1;
4332 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4333 // So we parse the long-algebraic move string in stead of the SAN move
4334 int valid; char buf[MSG_SIZ], *prom;
4336 if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4337 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4338 // str looks something like "Q/a1-a2"; kill the slash
4340 snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4341 else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4342 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4343 strcat(buf, prom); // long move lacks promo specification!
4344 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4345 if(appData.debugMode)
4346 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4347 safeStrCpy(move_str, buf, MSG_SIZ);
4349 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4350 &fromX, &fromY, &toX, &toY, &promoChar)
4351 || ParseOneMove(buf, moveNum - 1, &moveType,
4352 &fromX, &fromY, &toX, &toY, &promoChar);
4353 // end of long SAN patch
4355 (void) CoordsToAlgebraic(boards[moveNum - 1],
4356 PosFlags(moveNum - 1),
4357 fromY, fromX, toY, toX, promoChar,
4358 parseList[moveNum-1]);
4359 switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4365 if(gameInfo.variant != VariantShogi)
4366 strcat(parseList[moveNum - 1], "+");
4369 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4370 strcat(parseList[moveNum - 1], "#");
4373 strcat(parseList[moveNum - 1], " ");
4374 strcat(parseList[moveNum - 1], elapsed_time);
4375 /* currentMoveString is set as a side-effect of ParseOneMove */
4376 if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4377 safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4378 strcat(moveList[moveNum - 1], "\n");
4380 if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper
4381 && gameInfo.variant != VariantGreat) // inherit info that ICS does not give from previous board
4382 for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4383 ChessSquare old, new = boards[moveNum][k][j];
4384 if(fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4385 old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4386 if(old == new) continue;
4387 if(old == PROMOTED new) boards[moveNum][k][j] = old; // prevent promoted pieces to revert to primordial ones
4388 else if(new == WhiteWazir || new == BlackWazir) {
4389 if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4390 boards[moveNum][k][j] = PROMOTED old; // choose correct type of Gold in promotion
4391 else boards[moveNum][k][j] = old; // preserve type of Gold
4392 } else if((old == WhitePawn || old == BlackPawn) && new != EmptySquare) // Pawn promotions (but not e.p.capture!)
4393 boards[moveNum][k][j] = PROMOTED new; // use non-primordial representation of chosen piece
4396 /* Move from ICS was illegal!? Punt. */
4397 if (appData.debugMode) {
4398 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4399 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4401 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4402 strcat(parseList[moveNum - 1], " ");
4403 strcat(parseList[moveNum - 1], elapsed_time);
4404 moveList[moveNum - 1][0] = NULLCHAR;
4405 fromX = fromY = toX = toY = -1;
4408 if (appData.debugMode) {
4409 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4410 setbuf(debugFP, NULL);
4414 /* Send move to chess program (BEFORE animating it). */
4415 if (appData.zippyPlay && !newGame && newMove &&
4416 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4418 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4419 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4420 if (moveList[moveNum - 1][0] == NULLCHAR) {
4421 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4423 DisplayError(str, 0);
4425 if (first.sendTime) {
4426 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4428 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4429 if (firstMove && !bookHit) {
4431 if (first.useColors) {
4432 SendToProgram(gameMode == IcsPlayingWhite ?
4434 "black\ngo\n", &first);
4436 SendToProgram("go\n", &first);
4438 first.maybeThinking = TRUE;
4441 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4442 if (moveList[moveNum - 1][0] == NULLCHAR) {
4443 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4444 DisplayError(str, 0);
4446 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4447 SendMoveToProgram(moveNum - 1, &first);
4454 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
4455 /* If move comes from a remote source, animate it. If it
4456 isn't remote, it will have already been animated. */
4457 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
4458 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
4460 if (!pausing && appData.highlightLastMove) {
4461 SetHighlights(fromX, fromY, toX, toY);
4465 /* Start the clocks */
4466 whiteFlag = blackFlag = FALSE;
4467 appData.clockMode = !(basetime == 0 && increment == 0);
4469 ics_clock_paused = TRUE;
4471 } else if (ticking == 1) {
4472 ics_clock_paused = FALSE;
4474 if (gameMode == IcsIdle ||
4475 relation == RELATION_OBSERVING_STATIC ||
4476 relation == RELATION_EXAMINING ||
4478 DisplayBothClocks();
4482 /* Display opponents and material strengths */
4483 if (gameInfo.variant != VariantBughouse &&
4484 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
4485 if (tinyLayout || smallLayout) {
4486 if(gameInfo.variant == VariantNormal)
4487 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
4488 gameInfo.white, white_stren, gameInfo.black, black_stren,
4489 basetime, increment);
4491 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
4492 gameInfo.white, white_stren, gameInfo.black, black_stren,
4493 basetime, increment, (int) gameInfo.variant);
4495 if(gameInfo.variant == VariantNormal)
4496 snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d}",
4497 gameInfo.white, white_stren, gameInfo.black, black_stren,
4498 basetime, increment);
4500 snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d %s}",
4501 gameInfo.white, white_stren, gameInfo.black, black_stren,
4502 basetime, increment, VariantName(gameInfo.variant));
4505 if (appData.debugMode) {
4506 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
4511 /* Display the board */
4512 if (!pausing && !appData.noGUI) {
4514 if (appData.premove)
4516 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
4517 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
4518 ClearPremoveHighlights();
4520 j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
4521 if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
4522 DrawPosition(j, boards[currentMove]);
4524 DisplayMove(moveNum - 1);
4525 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
4526 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
4527 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
4528 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
4532 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
4534 if(bookHit) { // [HGM] book: simulate book reply
4535 static char bookMove[MSG_SIZ]; // a bit generous?
4537 programStats.nodes = programStats.depth = programStats.time =
4538 programStats.score = programStats.got_only_move = 0;
4539 sprintf(programStats.movelist, "%s (xbook)", bookHit);
4541 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
4542 strcat(bookMove, bookHit);
4543 HandleMachineMove(bookMove, &first);
4552 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
4553 ics_getting_history = H_REQUESTED;
4554 snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
4560 AnalysisPeriodicEvent(force)
4563 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
4564 && !force) || !appData.periodicUpdates)
4567 /* Send . command to Crafty to collect stats */
4568 SendToProgram(".\n", &first);
4570 /* Don't send another until we get a response (this makes
4571 us stop sending to old Crafty's which don't understand
4572 the "." command (sending illegal cmds resets node count & time,
4573 which looks bad)) */
4574 programStats.ok_to_send = 0;
4577 void ics_update_width(new_width)
4580 ics_printf("set width %d\n", new_width);
4584 SendMoveToProgram(moveNum, cps)
4586 ChessProgramState *cps;
4590 if (cps->useUsermove) {
4591 SendToProgram("usermove ", cps);
4595 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
4596 int len = space - parseList[moveNum];
4597 memcpy(buf, parseList[moveNum], len);
4599 buf[len] = NULLCHAR;
4601 snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
4603 SendToProgram(buf, cps);
4605 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
4606 AlphaRank(moveList[moveNum], 4);
4607 SendToProgram(moveList[moveNum], cps);
4608 AlphaRank(moveList[moveNum], 4); // and back
4610 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
4611 * the engine. It would be nice to have a better way to identify castle
4613 if((gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom)
4614 && cps->useOOCastle) {
4615 int fromX = moveList[moveNum][0] - AAA;
4616 int fromY = moveList[moveNum][1] - ONE;
4617 int toX = moveList[moveNum][2] - AAA;
4618 int toY = moveList[moveNum][3] - ONE;
4619 if((boards[moveNum][fromY][fromX] == WhiteKing
4620 && boards[moveNum][toY][toX] == WhiteRook)
4621 || (boards[moveNum][fromY][fromX] == BlackKing
4622 && boards[moveNum][toY][toX] == BlackRook)) {
4623 if(toX > fromX) SendToProgram("O-O\n", cps);
4624 else SendToProgram("O-O-O\n", cps);
4626 else SendToProgram(moveList[moveNum], cps);
4628 else SendToProgram(moveList[moveNum], cps);
4629 /* End of additions by Tord */
4632 /* [HGM] setting up the opening has brought engine in force mode! */
4633 /* Send 'go' if we are in a mode where machine should play. */
4634 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
4635 (gameMode == TwoMachinesPlay ||
4637 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
4639 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
4640 SendToProgram("go\n", cps);
4641 if (appData.debugMode) {
4642 fprintf(debugFP, "(extra)\n");
4645 setboardSpoiledMachineBlack = 0;
4649 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar)
4651 int fromX, fromY, toX, toY;
4654 char user_move[MSG_SIZ];
4658 snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
4659 (int)moveType, fromX, fromY, toX, toY);
4660 DisplayError(user_move + strlen("say "), 0);
4662 case WhiteKingSideCastle:
4663 case BlackKingSideCastle:
4664 case WhiteQueenSideCastleWild:
4665 case BlackQueenSideCastleWild:
4667 case WhiteHSideCastleFR:
4668 case BlackHSideCastleFR:
4670 snprintf(user_move, MSG_SIZ, "o-o\n");
4672 case WhiteQueenSideCastle:
4673 case BlackQueenSideCastle:
4674 case WhiteKingSideCastleWild:
4675 case BlackKingSideCastleWild:
4677 case WhiteASideCastleFR:
4678 case BlackASideCastleFR:
4680 snprintf(user_move, MSG_SIZ, "o-o-o\n");
4682 case WhiteNonPromotion:
4683 case BlackNonPromotion:
4684 sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4686 case WhitePromotion:
4687 case BlackPromotion:
4688 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
4689 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
4690 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4691 PieceToChar(WhiteFerz));
4692 else if(gameInfo.variant == VariantGreat)
4693 snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
4694 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4695 PieceToChar(WhiteMan));
4697 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
4698 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4704 snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
4705 ToUpper(PieceToChar((ChessSquare) fromX)),
4706 AAA + toX, ONE + toY);
4708 case IllegalMove: /* could be a variant we don't quite understand */
4709 if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
4711 case WhiteCapturesEnPassant:
4712 case BlackCapturesEnPassant:
4713 snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
4714 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4717 SendToICS(user_move);
4718 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
4719 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
4724 { // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
4725 int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
4726 static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
4727 if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
4728 DisplayError("You cannot do this while you are playing or observing", 0);
4731 if(gameMode != IcsExamining) { // is this ever not the case?
4732 char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
4734 if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
4735 snprintf(command,MSG_SIZ, "match %s", ics_handle);
4736 } else { // on FICS we must first go to general examine mode
4737 safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
4739 if(gameInfo.variant != VariantNormal) {
4740 // try figure out wild number, as xboard names are not always valid on ICS
4741 for(i=1; i<=36; i++) {
4742 snprintf(buf, MSG_SIZ, "wild/%d", i);
4743 if(StringToVariant(buf) == gameInfo.variant) break;
4745 if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
4746 else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
4747 else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
4748 } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
4749 SendToICS(ics_prefix);
4751 if(startedFromSetupPosition || backwardMostMove != 0) {
4752 fen = PositionToFEN(backwardMostMove, NULL);
4753 if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
4754 snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
4756 } else { // FICS: everything has to set by separate bsetup commands
4757 p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
4758 snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
4760 if(!WhiteOnMove(backwardMostMove)) {
4761 SendToICS("bsetup tomove black\n");
4763 i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
4764 snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
4766 i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
4767 snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
4769 i = boards[backwardMostMove][EP_STATUS];
4770 if(i >= 0) { // set e.p.
4771 snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
4777 if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
4778 SendToICS("bsetup done\n"); // switch to normal examining.
4780 for(i = backwardMostMove; i<last; i++) {
4782 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
4785 SendToICS(ics_prefix);
4786 SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
4790 CoordsToComputerAlgebraic(rf, ff, rt, ft, promoChar, move)
4795 if (rf == DROP_RANK) {
4796 sprintf(move, "%c@%c%c\n",
4797 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
4799 if (promoChar == 'x' || promoChar == NULLCHAR) {
4800 sprintf(move, "%c%c%c%c\n",
4801 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
4803 sprintf(move, "%c%c%c%c%c\n",
4804 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
4810 ProcessICSInitScript(f)
4815 while (fgets(buf, MSG_SIZ, f)) {
4816 SendToICSDelayed(buf,(long)appData.msLoginDelay);
4823 static int lastX, lastY, selectFlag, dragging;
4828 ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
4829 if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
4830 if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
4831 if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
4832 if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
4833 if(fromY != BOARD_HEIGHT-2 && fromY != 1) pawn = EmptySquare;
4836 if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
4837 else if((int)promoSweep == -1) promoSweep = WhiteKing;
4838 else if(promoSweep == BlackPawn && step < 0) promoSweep = WhitePawn;
4839 else if(promoSweep == WhiteKing && step > 0) promoSweep = BlackKing;
4841 } while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' || promoSweep == pawn ||
4842 appData.testLegality && (promoSweep == king ||
4843 gameInfo.variant == VariantShogi && promoSweep != PROMOTED last && last != PROMOTED promoSweep && last != promoSweep));
4844 ChangeDragPiece(promoSweep);
4847 int PromoScroll(int x, int y)
4851 if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
4852 if(abs(x - lastX) < 15 && abs(y - lastY) < 15) return FALSE;
4853 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
4854 if(!step) return FALSE;
4855 lastX = x; lastY = y;
4856 if((promoSweep < BlackPawn) == flipView) step = -step;
4857 if(step > 0) selectFlag = 1;
4858 if(!selectFlag) Sweep(step);
4865 ChessSquare piece = boards[currentMove][toY][toX];
4868 if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
4869 if((int)pieceSweep == -1) pieceSweep = BlackKing;
4870 if(!step) step = -1;
4871 } while(PieceToChar(pieceSweep) == '.');
4872 boards[currentMove][toY][toX] = pieceSweep;
4873 DrawPosition(FALSE, boards[currentMove]);
4874 boards[currentMove][toY][toX] = piece;
4876 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
4878 AlphaRank(char *move, int n)
4880 // char *p = move, c; int x, y;
4882 if (appData.debugMode) {
4883 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
4887 move[2]>='0' && move[2]<='9' &&
4888 move[3]>='a' && move[3]<='x' ) {
4890 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4891 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4893 if(move[0]>='0' && move[0]<='9' &&
4894 move[1]>='a' && move[1]<='x' &&
4895 move[2]>='0' && move[2]<='9' &&
4896 move[3]>='a' && move[3]<='x' ) {
4897 /* input move, Shogi -> normal */
4898 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
4899 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
4900 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4901 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4904 move[3]>='0' && move[3]<='9' &&
4905 move[2]>='a' && move[2]<='x' ) {
4907 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4908 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4911 move[0]>='a' && move[0]<='x' &&
4912 move[3]>='0' && move[3]<='9' &&
4913 move[2]>='a' && move[2]<='x' ) {
4914 /* output move, normal -> Shogi */
4915 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
4916 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
4917 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4918 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4919 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
4921 if (appData.debugMode) {
4922 fprintf(debugFP, " out = '%s'\n", move);
4926 char yy_textstr[8000];
4928 /* Parser for moves from gnuchess, ICS, or user typein box */
4930 ParseOneMove(move, moveNum, moveType, fromX, fromY, toX, toY, promoChar)
4933 ChessMove *moveType;
4934 int *fromX, *fromY, *toX, *toY;
4937 *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
4939 switch (*moveType) {
4940 case WhitePromotion:
4941 case BlackPromotion:
4942 case WhiteNonPromotion:
4943 case BlackNonPromotion:
4945 case WhiteCapturesEnPassant:
4946 case BlackCapturesEnPassant:
4947 case WhiteKingSideCastle:
4948 case WhiteQueenSideCastle:
4949 case BlackKingSideCastle:
4950 case BlackQueenSideCastle:
4951 case WhiteKingSideCastleWild:
4952 case WhiteQueenSideCastleWild:
4953 case BlackKingSideCastleWild:
4954 case BlackQueenSideCastleWild:
4955 /* Code added by Tord: */
4956 case WhiteHSideCastleFR:
4957 case WhiteASideCastleFR:
4958 case BlackHSideCastleFR:
4959 case BlackASideCastleFR:
4960 /* End of code added by Tord */
4961 case IllegalMove: /* bug or odd chess variant */
4962 *fromX = currentMoveString[0] - AAA;
4963 *fromY = currentMoveString[1] - ONE;
4964 *toX = currentMoveString[2] - AAA;
4965 *toY = currentMoveString[3] - ONE;
4966 *promoChar = currentMoveString[4];
4967 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
4968 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
4969 if (appData.debugMode) {
4970 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
4972 *fromX = *fromY = *toX = *toY = 0;
4975 if (appData.testLegality) {
4976 return (*moveType != IllegalMove);
4978 return !(*fromX == *toX && *fromY == *toY) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
4979 WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
4984 *fromX = *moveType == WhiteDrop ?
4985 (int) CharToPiece(ToUpper(currentMoveString[0])) :
4986 (int) CharToPiece(ToLower(currentMoveString[0]));
4988 *toX = currentMoveString[2] - AAA;
4989 *toY = currentMoveString[3] - ONE;
4990 *promoChar = NULLCHAR;
4994 case ImpossibleMove:
5004 if (appData.debugMode) {
5005 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
5008 *fromX = *fromY = *toX = *toY = 0;
5009 *promoChar = NULLCHAR;
5016 ParsePV(char *pv, Boolean storeComments)
5017 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
5018 int fromX, fromY, toX, toY; char promoChar;
5023 endPV = forwardMostMove;
5025 while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
5026 if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
5027 valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
5028 if(appData.debugMode){
5029 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);
5031 if(!valid && nr == 0 &&
5032 ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
5033 nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
5034 // Hande case where played move is different from leading PV move
5035 CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
5036 CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
5037 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
5038 if(!CompareBoards(boards[endPV], boards[endPV+2])) {
5039 endPV += 2; // if position different, keep this
5040 moveList[endPV-1][0] = fromX + AAA;
5041 moveList[endPV-1][1] = fromY + ONE;
5042 moveList[endPV-1][2] = toX + AAA;
5043 moveList[endPV-1][3] = toY + ONE;
5044 parseList[endPV-1][0] = NULLCHAR;
5045 safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
5048 pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
5049 if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5050 if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5051 if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5052 valid++; // allow comments in PV
5056 if(endPV+1 > framePtr) break; // no space, truncate
5059 CopyBoard(boards[endPV], boards[endPV-1]);
5060 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5061 moveList[endPV-1][0] = fromX + AAA;
5062 moveList[endPV-1][1] = fromY + ONE;
5063 moveList[endPV-1][2] = toX + AAA;
5064 moveList[endPV-1][3] = toY + ONE;
5065 moveList[endPV-1][4] = promoChar;
5066 moveList[endPV-1][5] = NULLCHAR;
5067 strncat(moveList[endPV-1], "\n", MOVE_LEN);
5069 CoordsToAlgebraic(boards[endPV - 1],
5070 PosFlags(endPV - 1),
5071 fromY, fromX, toY, toX, promoChar,
5072 parseList[endPV - 1]);
5074 parseList[endPV-1][0] = NULLCHAR;
5076 currentMove = endPV;
5077 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5078 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5079 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5080 DrawPosition(TRUE, boards[currentMove]);
5084 LoadMultiPV(int x, int y, char *buf, int index, int *start, int *end)
5089 if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5090 lastX = x; lastY = y;
5091 while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5093 while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5094 if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5096 do{ while(buf[index] && buf[index] != '\n') index++;
5097 } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5099 ParsePV(buf+startPV, FALSE);
5100 *start = startPV; *end = index-1;
5105 LoadPV(int x, int y)
5106 { // called on right mouse click to load PV
5107 int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5108 lastX = x; lastY = y;
5109 ParsePV(lastPV[which], FALSE); // load the PV of the thinking engine in the boards array.
5116 if(endPV < 0) return;
5118 currentMove = forwardMostMove;
5119 ClearPremoveHighlights();
5120 DrawPosition(TRUE, boards[currentMove]);
5124 MovePV(int x, int y, int h)
5125 { // step through PV based on mouse coordinates (called on mouse move)
5126 int margin = h>>3, step = 0;
5128 // we must somehow check if right button is still down (might be released off board!)
5129 if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
5130 if(abs(x - lastX) < 7 && abs(y - lastY) < 7) return;
5131 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5133 lastX = x; lastY = y;
5135 if(pieceSweep != EmptySquare) { NextPiece(step); return; }
5136 if(endPV < 0) return;
5137 if(y < margin) step = 1; else
5138 if(y > h - margin) step = -1;
5139 if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5140 currentMove += step;
5141 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5142 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5143 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5144 DrawPosition(FALSE, boards[currentMove]);
5148 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5149 // All positions will have equal probability, but the current method will not provide a unique
5150 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5156 int piecesLeft[(int)BlackPawn];
5157 int seed, nrOfShuffles;
5159 void GetPositionNumber()
5160 { // sets global variable seed
5163 seed = appData.defaultFrcPosition;
5164 if(seed < 0) { // randomize based on time for negative FRC position numbers
5165 for(i=0; i<50; i++) seed += random();
5166 seed = random() ^ random() >> 8 ^ random() << 8;
5167 if(seed<0) seed = -seed;
5171 int put(Board board, int pieceType, int rank, int n, int shade)
5172 // put the piece on the (n-1)-th empty squares of the given shade
5176 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5177 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5178 board[rank][i] = (ChessSquare) pieceType;
5179 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5181 piecesLeft[pieceType]--;
5189 void AddOnePiece(Board board, int pieceType, int rank, int shade)
5190 // calculate where the next piece goes, (any empty square), and put it there
5194 i = seed % squaresLeft[shade];
5195 nrOfShuffles *= squaresLeft[shade];
5196 seed /= squaresLeft[shade];
5197 put(board, pieceType, rank, i, shade);
5200 void AddTwoPieces(Board board, int pieceType, int rank)
5201 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5203 int i, n=squaresLeft[ANY], j=n-1, k;
5205 k = n*(n-1)/2; // nr of possibilities, not counting permutations
5206 i = seed % k; // pick one
5209 while(i >= j) i -= j--;
5210 j = n - 1 - j; i += j;
5211 put(board, pieceType, rank, j, ANY);
5212 put(board, pieceType, rank, i, ANY);
5215 void SetUpShuffle(Board board, int number)
5219 GetPositionNumber(); nrOfShuffles = 1;
5221 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5222 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
5223 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5225 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5227 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5228 p = (int) board[0][i];
5229 if(p < (int) BlackPawn) piecesLeft[p] ++;
5230 board[0][i] = EmptySquare;
5233 if(PosFlags(0) & F_ALL_CASTLE_OK) {
5234 // shuffles restricted to allow normal castling put KRR first
5235 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5236 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5237 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5238 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5239 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5240 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5241 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
5242 put(board, WhiteRook, 0, 0, ANY);
5243 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
5246 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
5247 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
5248 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
5249 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
5250 while(piecesLeft[p] >= 2) {
5251 AddOnePiece(board, p, 0, LITE);
5252 AddOnePiece(board, p, 0, DARK);
5254 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
5257 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
5258 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
5259 // but we leave King and Rooks for last, to possibly obey FRC restriction
5260 if(p == (int)WhiteRook) continue;
5261 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
5262 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
5265 // now everything is placed, except perhaps King (Unicorn) and Rooks
5267 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
5268 // Last King gets castling rights
5269 while(piecesLeft[(int)WhiteUnicorn]) {
5270 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5271 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5274 while(piecesLeft[(int)WhiteKing]) {
5275 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5276 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5281 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
5282 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
5285 // Only Rooks can be left; simply place them all
5286 while(piecesLeft[(int)WhiteRook]) {
5287 i = put(board, WhiteRook, 0, 0, ANY);
5288 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
5291 initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
5293 initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
5296 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
5297 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
5300 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
5303 int SetCharTable( char *table, const char * map )
5304 /* [HGM] moved here from winboard.c because of its general usefulness */
5305 /* Basically a safe strcpy that uses the last character as King */
5307 int result = FALSE; int NrPieces;
5309 if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
5310 && NrPieces >= 12 && !(NrPieces&1)) {
5311 int i; /* [HGM] Accept even length from 12 to 34 */
5313 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
5314 for( i=0; i<NrPieces/2-1; i++ ) {
5316 table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
5318 table[(int) WhiteKing] = map[NrPieces/2-1];
5319 table[(int) BlackKing] = map[NrPieces-1];
5327 void Prelude(Board board)
5328 { // [HGM] superchess: random selection of exo-pieces
5329 int i, j, k; ChessSquare p;
5330 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
5332 GetPositionNumber(); // use FRC position number
5334 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
5335 SetCharTable(pieceToChar, appData.pieceToCharTable);
5336 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
5337 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
5340 j = seed%4; seed /= 4;
5341 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5342 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5343 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5344 j = seed%3 + (seed%3 >= j); seed /= 3;
5345 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5346 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5347 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5348 j = seed%3; seed /= 3;
5349 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5350 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5351 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5352 j = seed%2 + (seed%2 >= j); seed /= 2;
5353 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5354 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5355 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5356 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
5357 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
5358 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
5359 put(board, exoPieces[0], 0, 0, ANY);
5360 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
5364 InitPosition(redraw)
5367 ChessSquare (* pieces)[BOARD_FILES];
5368 int i, j, pawnRow, overrule,
5369 oldx = gameInfo.boardWidth,
5370 oldy = gameInfo.boardHeight,
5371 oldh = gameInfo.holdingsWidth;
5374 if(appData.icsActive) shuffleOpenings = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
5376 /* [AS] Initialize pv info list [HGM] and game status */
5378 for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
5379 pvInfoList[i].depth = 0;
5380 boards[i][EP_STATUS] = EP_NONE;
5381 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
5384 initialRulePlies = 0; /* 50-move counter start */
5386 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
5387 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
5391 /* [HGM] logic here is completely changed. In stead of full positions */
5392 /* the initialized data only consist of the two backranks. The switch */
5393 /* selects which one we will use, which is than copied to the Board */
5394 /* initialPosition, which for the rest is initialized by Pawns and */
5395 /* empty squares. This initial position is then copied to boards[0], */
5396 /* possibly after shuffling, so that it remains available. */
5398 gameInfo.holdingsWidth = 0; /* default board sizes */
5399 gameInfo.boardWidth = 8;
5400 gameInfo.boardHeight = 8;
5401 gameInfo.holdingsSize = 0;
5402 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
5403 for(i=0; i<BOARD_FILES-2; i++)
5404 initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
5405 initialPosition[EP_STATUS] = EP_NONE;
5406 SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
5407 if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
5408 SetCharTable(pieceNickName, appData.pieceNickNames);
5409 else SetCharTable(pieceNickName, "............");
5412 switch (gameInfo.variant) {
5413 case VariantFischeRandom:
5414 shuffleOpenings = TRUE;
5417 case VariantShatranj:
5418 pieces = ShatranjArray;
5419 nrCastlingRights = 0;
5420 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
5423 pieces = makrukArray;
5424 nrCastlingRights = 0;
5425 startedFromSetupPosition = TRUE;
5426 SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
5428 case VariantTwoKings:
5429 pieces = twoKingsArray;
5431 case VariantCapaRandom:
5432 shuffleOpenings = TRUE;
5433 case VariantCapablanca:
5434 pieces = CapablancaArray;
5435 gameInfo.boardWidth = 10;
5436 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5439 pieces = GothicArray;
5440 gameInfo.boardWidth = 10;
5441 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5444 SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
5445 gameInfo.holdingsSize = 7;
5448 pieces = JanusArray;
5449 gameInfo.boardWidth = 10;
5450 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
5451 nrCastlingRights = 6;
5452 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5453 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5454 initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
5455 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5456 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5457 initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
5460 pieces = FalconArray;
5461 gameInfo.boardWidth = 10;
5462 SetCharTable(pieceToChar, "PNBRQ.............FKpnbrq.............fk");
5464 case VariantXiangqi:
5465 pieces = XiangqiArray;
5466 gameInfo.boardWidth = 9;
5467 gameInfo.boardHeight = 10;
5468 nrCastlingRights = 0;
5469 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
5472 pieces = ShogiArray;
5473 gameInfo.boardWidth = 9;
5474 gameInfo.boardHeight = 9;
5475 gameInfo.holdingsSize = 7;
5476 nrCastlingRights = 0;
5477 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
5479 case VariantCourier:
5480 pieces = CourierArray;
5481 gameInfo.boardWidth = 12;
5482 nrCastlingRights = 0;
5483 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
5485 case VariantKnightmate:
5486 pieces = KnightmateArray;
5487 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
5489 case VariantSpartan:
5490 pieces = SpartanArray;
5491 SetCharTable(pieceToChar, "PNBRQ................K......lwg.....c...h..k");
5494 pieces = fairyArray;
5495 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
5498 pieces = GreatArray;
5499 gameInfo.boardWidth = 10;
5500 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
5501 gameInfo.holdingsSize = 8;
5505 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
5506 gameInfo.holdingsSize = 8;
5507 startedFromSetupPosition = TRUE;
5509 case VariantCrazyhouse:
5510 case VariantBughouse:
5512 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
5513 gameInfo.holdingsSize = 5;
5515 case VariantWildCastle:
5517 /* !!?shuffle with kings guaranteed to be on d or e file */
5518 shuffleOpenings = 1;
5520 case VariantNoCastle:
5522 nrCastlingRights = 0;
5523 /* !!?unconstrained back-rank shuffle */
5524 shuffleOpenings = 1;
5529 if(appData.NrFiles >= 0) {
5530 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
5531 gameInfo.boardWidth = appData.NrFiles;
5533 if(appData.NrRanks >= 0) {
5534 gameInfo.boardHeight = appData.NrRanks;
5536 if(appData.holdingsSize >= 0) {
5537 i = appData.holdingsSize;
5538 if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
5539 gameInfo.holdingsSize = i;
5541 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
5542 if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
5543 DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
5545 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
5546 if(pawnRow < 1) pawnRow = 1;
5547 if(gameInfo.variant == VariantMakruk) pawnRow = 2;
5549 /* User pieceToChar list overrules defaults */
5550 if(appData.pieceToCharTable != NULL)
5551 SetCharTable(pieceToChar, appData.pieceToCharTable);
5553 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
5555 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
5556 s = (ChessSquare) 0; /* account holding counts in guard band */
5557 for( i=0; i<BOARD_HEIGHT; i++ )
5558 initialPosition[i][j] = s;
5560 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
5561 initialPosition[0][j] = pieces[0][j-gameInfo.holdingsWidth];
5562 initialPosition[pawnRow][j] = WhitePawn;
5563 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
5564 if(gameInfo.variant == VariantXiangqi) {
5566 initialPosition[pawnRow][j] =
5567 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
5568 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
5569 initialPosition[2][j] = WhiteCannon;
5570 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
5574 initialPosition[BOARD_HEIGHT-1][j] = pieces[1][j-gameInfo.holdingsWidth];
5576 if( (gameInfo.variant == VariantShogi) && !overrule ) {
5579 initialPosition[1][j] = WhiteBishop;
5580 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
5582 initialPosition[1][j] = WhiteRook;
5583 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
5586 if( nrCastlingRights == -1) {
5587 /* [HGM] Build normal castling rights (must be done after board sizing!) */
5588 /* This sets default castling rights from none to normal corners */
5589 /* Variants with other castling rights must set them themselves above */
5590 nrCastlingRights = 6;
5592 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5593 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5594 initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
5595 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5596 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5597 initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
5600 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
5601 if(gameInfo.variant == VariantGreat) { // promotion commoners
5602 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
5603 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
5604 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
5605 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
5607 if( gameInfo.variant == VariantSChess ) {
5608 initialPosition[1][0] = BlackMarshall;
5609 initialPosition[2][0] = BlackAngel;
5610 initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
5611 initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
5612 initialPosition[1][1] = initialPosition[2][1] =
5613 initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
5615 if (appData.debugMode) {
5616 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
5618 if(shuffleOpenings) {
5619 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
5620 startedFromSetupPosition = TRUE;
5622 if(startedFromPositionFile) {
5623 /* [HGM] loadPos: use PositionFile for every new game */
5624 CopyBoard(initialPosition, filePosition);
5625 for(i=0; i<nrCastlingRights; i++)
5626 initialRights[i] = filePosition[CASTLING][i];
5627 startedFromSetupPosition = TRUE;
5630 CopyBoard(boards[0], initialPosition);
5632 if(oldx != gameInfo.boardWidth ||
5633 oldy != gameInfo.boardHeight ||
5634 oldv != gameInfo.variant ||
5635 oldh != gameInfo.holdingsWidth
5637 InitDrawingSizes(-2 ,0);
5639 oldv = gameInfo.variant;
5641 DrawPosition(TRUE, boards[currentMove]);
5645 SendBoard(cps, moveNum)
5646 ChessProgramState *cps;
5649 char message[MSG_SIZ];
5651 if (cps->useSetboard) {
5652 char* fen = PositionToFEN(moveNum, cps->fenOverride);
5653 snprintf(message, MSG_SIZ,"setboard %s\n", fen);
5654 SendToProgram(message, cps);
5660 /* Kludge to set black to move, avoiding the troublesome and now
5661 * deprecated "black" command.
5663 if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
5664 SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn ? "a2a3\n" : "black\n", cps);
5666 SendToProgram("edit\n", cps);
5667 SendToProgram("#\n", cps);
5668 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
5669 bp = &boards[moveNum][i][BOARD_LEFT];
5670 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
5671 if ((int) *bp < (int) BlackPawn) {
5672 snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp),
5674 if(message[0] == '+' || message[0] == '~') {
5675 snprintf(message, MSG_SIZ,"%c%c%c+\n",
5676 PieceToChar((ChessSquare)(DEMOTED *bp)),
5679 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
5680 message[1] = BOARD_RGHT - 1 - j + '1';
5681 message[2] = BOARD_HEIGHT - 1 - i + 'a';
5683 SendToProgram(message, cps);
5688 SendToProgram("c\n", cps);
5689 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
5690 bp = &boards[moveNum][i][BOARD_LEFT];
5691 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
5692 if (((int) *bp != (int) EmptySquare)
5693 && ((int) *bp >= (int) BlackPawn)) {
5694 snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
5696 if(message[0] == '+' || message[0] == '~') {
5697 snprintf(message, MSG_SIZ,"%c%c%c+\n",
5698 PieceToChar((ChessSquare)(DEMOTED *bp)),
5701 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
5702 message[1] = BOARD_RGHT - 1 - j + '1';
5703 message[2] = BOARD_HEIGHT - 1 - i + 'a';
5705 SendToProgram(message, cps);
5710 SendToProgram(".\n", cps);
5712 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
5716 DefaultPromoChoice(int white)
5719 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
5720 result = WhiteFerz; // no choice
5721 else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
5722 result= WhiteKing; // in Suicide Q is the last thing we want
5723 else if(gameInfo.variant == VariantSpartan)
5724 result = white ? WhiteQueen : WhiteAngel;
5725 else result = WhiteQueen;
5726 if(!white) result = WHITE_TO_BLACK result;
5730 static int autoQueen; // [HGM] oneclick
5733 HasPromotionChoice(int fromX, int fromY, int toX, int toY, char *promoChoice)
5735 /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
5736 /* [HGM] add Shogi promotions */
5737 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
5742 if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
5743 if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
5745 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
5746 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
5749 piece = boards[currentMove][fromY][fromX];
5750 if(gameInfo.variant == VariantShogi) {
5751 promotionZoneSize = BOARD_HEIGHT/3;
5752 highestPromotingPiece = (int)WhiteFerz;
5753 } else if(gameInfo.variant == VariantMakruk) {
5754 promotionZoneSize = 3;
5757 // Treat Lance as Pawn when it is not representing Amazon
5758 if(gameInfo.variant != VariantSuper) {
5759 if(piece == WhiteLance) piece = WhitePawn; else
5760 if(piece == BlackLance) piece = BlackPawn;
5763 // next weed out all moves that do not touch the promotion zone at all
5764 if((int)piece >= BlackPawn) {
5765 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
5767 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
5769 if( toY < BOARD_HEIGHT - promotionZoneSize &&
5770 fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
5773 if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
5775 // weed out mandatory Shogi promotions
5776 if(gameInfo.variant == VariantShogi) {
5777 if(piece >= BlackPawn) {
5778 if(toY == 0 && piece == BlackPawn ||
5779 toY == 0 && piece == BlackQueen ||
5780 toY <= 1 && piece == BlackKnight) {
5785 if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
5786 toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
5787 toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
5794 // weed out obviously illegal Pawn moves
5795 if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
5796 if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
5797 if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
5798 if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
5799 if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
5800 // note we are not allowed to test for valid (non-)capture, due to premove
5803 // we either have a choice what to promote to, or (in Shogi) whether to promote
5804 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk) {
5805 *promoChoice = PieceToChar(BlackFerz); // no choice
5808 // no sense asking what we must promote to if it is going to explode...
5809 if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
5810 *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
5813 // give caller the default choice even if we will not make it
5814 *promoChoice = ToLower(PieceToChar(defaultPromoChoice));
5815 if(gameInfo.variant == VariantShogi) *promoChoice = '+';
5816 if(appData.sweepSelect && gameInfo.variant != VariantGreat
5817 && gameInfo.variant != VariantShogi
5818 && gameInfo.variant != VariantSuper) return FALSE;
5819 if(autoQueen) return FALSE; // predetermined
5821 // suppress promotion popup on illegal moves that are not premoves
5822 premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
5823 gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
5824 if(appData.testLegality && !premove) {
5825 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
5826 fromY, fromX, toY, toX, gameInfo.variant == VariantShogi ? '+' : NULLCHAR);
5827 if(moveType != WhitePromotion && moveType != BlackPromotion)
5835 InPalace(row, column)
5837 { /* [HGM] for Xiangqi */
5838 if( (row < 3 || row > BOARD_HEIGHT-4) &&
5839 column < (BOARD_WIDTH + 4)/2 &&
5840 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
5845 PieceForSquare (x, y)
5849 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
5852 return boards[currentMove][y][x];
5856 OKToStartUserMove(x, y)
5859 ChessSquare from_piece;
5862 if (matchMode) return FALSE;
5863 if (gameMode == EditPosition) return TRUE;
5865 if (x >= 0 && y >= 0)
5866 from_piece = boards[currentMove][y][x];
5868 from_piece = EmptySquare;
5870 if (from_piece == EmptySquare) return FALSE;
5872 white_piece = (int)from_piece >= (int)WhitePawn &&
5873 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
5876 case PlayFromGameFile:
5878 case TwoMachinesPlay:
5886 case MachinePlaysWhite:
5887 case IcsPlayingBlack:
5888 if (appData.zippyPlay) return FALSE;
5890 DisplayMoveError(_("You are playing Black"));
5895 case MachinePlaysBlack:
5896 case IcsPlayingWhite:
5897 if (appData.zippyPlay) return FALSE;
5899 DisplayMoveError(_("You are playing White"));
5905 if (!white_piece && WhiteOnMove(currentMove)) {
5906 DisplayMoveError(_("It is White's turn"));
5909 if (white_piece && !WhiteOnMove(currentMove)) {
5910 DisplayMoveError(_("It is Black's turn"));
5913 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
5914 /* Editing correspondence game history */
5915 /* Could disallow this or prompt for confirmation */
5920 case BeginningOfGame:
5921 if (appData.icsActive) return FALSE;
5922 if (!appData.noChessProgram) {
5924 DisplayMoveError(_("You are playing White"));
5931 if (!white_piece && WhiteOnMove(currentMove)) {
5932 DisplayMoveError(_("It is White's turn"));
5935 if (white_piece && !WhiteOnMove(currentMove)) {
5936 DisplayMoveError(_("It is Black's turn"));
5945 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
5946 && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
5947 && gameMode != AnalyzeFile && gameMode != Training) {
5948 DisplayMoveError(_("Displayed position is not current"));
5955 OnlyMove(int *x, int *y, Boolean captures) {
5956 DisambiguateClosure cl;
5957 if (appData.zippyPlay) return FALSE;
5959 case MachinePlaysBlack:
5960 case IcsPlayingWhite:
5961 case BeginningOfGame:
5962 if(!WhiteOnMove(currentMove)) return FALSE;
5964 case MachinePlaysWhite:
5965 case IcsPlayingBlack:
5966 if(WhiteOnMove(currentMove)) return FALSE;
5973 cl.pieceIn = EmptySquare;
5978 cl.promoCharIn = NULLCHAR;
5979 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
5980 if( cl.kind == NormalMove ||
5981 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
5982 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
5983 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
5990 if(cl.kind != ImpossibleMove) return FALSE;
5991 cl.pieceIn = EmptySquare;
5996 cl.promoCharIn = NULLCHAR;
5997 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
5998 if( cl.kind == NormalMove ||
5999 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6000 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6001 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6006 autoQueen = TRUE; // act as if autoQueen on when we click to-square
6012 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
6013 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
6014 int lastLoadGameUseList = FALSE;
6015 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
6016 ChessMove lastLoadGameStart = EndOfFile;
6019 UserMoveEvent(fromX, fromY, toX, toY, promoChar)
6020 int fromX, fromY, toX, toY;
6024 ChessSquare pdown, pup;
6026 /* Check if the user is playing in turn. This is complicated because we
6027 let the user "pick up" a piece before it is his turn. So the piece he
6028 tried to pick up may have been captured by the time he puts it down!
6029 Therefore we use the color the user is supposed to be playing in this
6030 test, not the color of the piece that is currently on the starting
6031 square---except in EditGame mode, where the user is playing both
6032 sides; fortunately there the capture race can't happen. (It can
6033 now happen in IcsExamining mode, but that's just too bad. The user
6034 will get a somewhat confusing message in that case.)
6038 case PlayFromGameFile:
6040 case TwoMachinesPlay:
6044 /* We switched into a game mode where moves are not accepted,
6045 perhaps while the mouse button was down. */
6048 case MachinePlaysWhite:
6049 /* User is moving for Black */
6050 if (WhiteOnMove(currentMove)) {
6051 DisplayMoveError(_("It is White's turn"));
6056 case MachinePlaysBlack:
6057 /* User is moving for White */
6058 if (!WhiteOnMove(currentMove)) {
6059 DisplayMoveError(_("It is Black's turn"));
6066 case BeginningOfGame:
6069 if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
6070 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
6071 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
6072 /* User is moving for Black */
6073 if (WhiteOnMove(currentMove)) {
6074 DisplayMoveError(_("It is White's turn"));
6078 /* User is moving for White */
6079 if (!WhiteOnMove(currentMove)) {
6080 DisplayMoveError(_("It is Black's turn"));
6086 case IcsPlayingBlack:
6087 /* User is moving for Black */
6088 if (WhiteOnMove(currentMove)) {
6089 if (!appData.premove) {
6090 DisplayMoveError(_("It is White's turn"));
6091 } else if (toX >= 0 && toY >= 0) {
6094 premoveFromX = fromX;
6095 premoveFromY = fromY;
6096 premovePromoChar = promoChar;
6098 if (appData.debugMode)
6099 fprintf(debugFP, "Got premove: fromX %d,"
6100 "fromY %d, toX %d, toY %d\n",
6101 fromX, fromY, toX, toY);
6107 case IcsPlayingWhite:
6108 /* User is moving for White */
6109 if (!WhiteOnMove(currentMove)) {
6110 if (!appData.premove) {
6111 DisplayMoveError(_("It is Black's turn"));
6112 } else if (toX >= 0 && toY >= 0) {
6115 premoveFromX = fromX;
6116 premoveFromY = fromY;
6117 premovePromoChar = promoChar;
6119 if (appData.debugMode)
6120 fprintf(debugFP, "Got premove: fromX %d,"
6121 "fromY %d, toX %d, toY %d\n",
6122 fromX, fromY, toX, toY);
6132 /* EditPosition, empty square, or different color piece;
6133 click-click move is possible */
6134 if (toX == -2 || toY == -2) {
6135 boards[0][fromY][fromX] = EmptySquare;
6136 DrawPosition(FALSE, boards[currentMove]);
6138 } else if (toX >= 0 && toY >= 0) {
6139 boards[0][toY][toX] = boards[0][fromY][fromX];
6140 if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
6141 if(boards[0][fromY][0] != EmptySquare) {
6142 if(boards[0][fromY][1]) boards[0][fromY][1]--;
6143 if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
6146 if(fromX == BOARD_RGHT+1) {
6147 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
6148 if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
6149 if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
6152 boards[0][fromY][fromX] = EmptySquare;
6153 DrawPosition(FALSE, boards[currentMove]);
6159 if(toX < 0 || toY < 0) return;
6160 pdown = boards[currentMove][fromY][fromX];
6161 pup = boards[currentMove][toY][toX];
6163 /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
6164 if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
6165 if( pup != EmptySquare ) return;
6166 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
6167 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
6168 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
6169 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
6170 if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
6171 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
6172 while(PieceToChar(fromX) == '.' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
6176 /* [HGM] always test for legality, to get promotion info */
6177 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6178 fromY, fromX, toY, toX, promoChar);
6179 /* [HGM] but possibly ignore an IllegalMove result */
6180 if (appData.testLegality) {
6181 if (moveType == IllegalMove || moveType == ImpossibleMove) {
6182 DisplayMoveError(_("Illegal move"));
6187 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
6190 /* Common tail of UserMoveEvent and DropMenuEvent */
6192 FinishMove(moveType, fromX, fromY, toX, toY, promoChar)
6194 int fromX, fromY, toX, toY;
6195 /*char*/int promoChar;
6199 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) && promoChar != NULLCHAR) {
6200 // [HGM] superchess: suppress promotions to non-available piece
6201 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
6202 if(WhiteOnMove(currentMove)) {
6203 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
6205 if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
6209 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
6210 move type in caller when we know the move is a legal promotion */
6211 if(moveType == NormalMove && promoChar)
6212 moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
6214 /* [HGM] <popupFix> The following if has been moved here from
6215 UserMoveEvent(). Because it seemed to belong here (why not allow
6216 piece drops in training games?), and because it can only be
6217 performed after it is known to what we promote. */
6218 if (gameMode == Training) {
6219 /* compare the move played on the board to the next move in the
6220 * game. If they match, display the move and the opponent's response.
6221 * If they don't match, display an error message.
6225 CopyBoard(testBoard, boards[currentMove]);
6226 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
6228 if (CompareBoards(testBoard, boards[currentMove+1])) {
6229 ForwardInner(currentMove+1);
6231 /* Autoplay the opponent's response.
6232 * if appData.animate was TRUE when Training mode was entered,
6233 * the response will be animated.
6235 saveAnimate = appData.animate;
6236 appData.animate = animateTraining;
6237 ForwardInner(currentMove+1);
6238 appData.animate = saveAnimate;
6240 /* check for the end of the game */
6241 if (currentMove >= forwardMostMove) {
6242 gameMode = PlayFromGameFile;
6244 SetTrainingModeOff();
6245 DisplayInformation(_("End of game"));
6248 DisplayError(_("Incorrect move"), 0);
6253 /* Ok, now we know that the move is good, so we can kill
6254 the previous line in Analysis Mode */
6255 if ((gameMode == AnalyzeMode || gameMode == EditGame)
6256 && currentMove < forwardMostMove) {
6257 if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
6258 else forwardMostMove = currentMove;
6261 /* If we need the chess program but it's dead, restart it */
6262 ResurrectChessProgram();
6264 /* A user move restarts a paused game*/
6268 thinkOutput[0] = NULLCHAR;
6270 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
6272 if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
6273 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6277 if (gameMode == BeginningOfGame) {
6278 if (appData.noChessProgram) {
6279 gameMode = EditGame;
6283 gameMode = MachinePlaysBlack;
6286 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
6288 if (first.sendName) {
6289 snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
6290 SendToProgram(buf, &first);
6297 /* Relay move to ICS or chess engine */
6298 if (appData.icsActive) {
6299 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
6300 gameMode == IcsExamining) {
6301 if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
6302 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
6304 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6306 // also send plain move, in case ICS does not understand atomic claims
6307 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6311 if (first.sendTime && (gameMode == BeginningOfGame ||
6312 gameMode == MachinePlaysWhite ||
6313 gameMode == MachinePlaysBlack)) {
6314 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
6316 if (gameMode != EditGame && gameMode != PlayFromGameFile) {
6317 // [HGM] book: if program might be playing, let it use book
6318 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
6319 first.maybeThinking = TRUE;
6320 } else SendMoveToProgram(forwardMostMove-1, &first);
6321 if (currentMove == cmailOldMove + 1) {
6322 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
6326 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6330 if(appData.testLegality)
6331 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
6337 if (WhiteOnMove(currentMove)) {
6338 GameEnds(BlackWins, "Black mates", GE_PLAYER);
6340 GameEnds(WhiteWins, "White mates", GE_PLAYER);
6344 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
6349 case MachinePlaysBlack:
6350 case MachinePlaysWhite:
6351 /* disable certain menu options while machine is thinking */
6352 SetMachineThinkingEnables();
6359 userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
6360 promoDefaultAltered = FALSE; // [HGM] fall back on default choice
6362 if(bookHit) { // [HGM] book: simulate book reply
6363 static char bookMove[MSG_SIZ]; // a bit generous?
6365 programStats.nodes = programStats.depth = programStats.time =
6366 programStats.score = programStats.got_only_move = 0;
6367 sprintf(programStats.movelist, "%s (xbook)", bookHit);
6369 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
6370 strcat(bookMove, bookHit);
6371 HandleMachineMove(bookMove, &first);
6377 Mark(board, flags, kind, rf, ff, rt, ft, closure)
6384 typedef char Markers[BOARD_RANKS][BOARD_FILES];
6385 Markers *m = (Markers *) closure;
6386 if(rf == fromY && ff == fromX)
6387 (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
6388 || kind == WhiteCapturesEnPassant
6389 || kind == BlackCapturesEnPassant);
6390 else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3;
6394 MarkTargetSquares(int clear)
6397 if(!appData.markers || !appData.highlightDragging ||
6398 !appData.testLegality || gameMode == EditPosition) return;
6400 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) marker[y][x] = 0;
6403 GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker);
6404 if(PosFlags(0) & F_MANDATORY_CAPTURE) {
6405 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
6407 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
6410 DrawPosition(TRUE, NULL);
6414 Explode(Board board, int fromX, int fromY, int toX, int toY)
6416 if(gameInfo.variant == VariantAtomic &&
6417 (board[toY][toX] != EmptySquare || // capture?
6418 toX != fromX && (board[fromY][fromX] == WhitePawn || // e.p. ?
6419 board[fromY][fromX] == BlackPawn )
6421 AnimateAtomicCapture(board, fromX, fromY, toX, toY);
6427 ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
6429 int CanPromote(ChessSquare piece, int y)
6431 if(gameMode == EditPosition) return FALSE; // no promotions when editing position
6432 // some variants have fixed promotion piece, no promotion at all, or another selection mechanism
6433 if(gameInfo.variant == VariantShogi || gameInfo.variant == VariantXiangqi ||
6434 gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat ||
6435 gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6436 gameInfo.variant == VariantMakruk) return FALSE;
6437 return (piece == BlackPawn && y == 1 ||
6438 piece == WhitePawn && y == BOARD_HEIGHT-2 ||
6439 piece == BlackLance && y == 1 ||
6440 piece == WhiteLance && y == BOARD_HEIGHT-2 );
6443 void LeftClick(ClickType clickType, int xPix, int yPix)
6446 Boolean saveAnimate;
6447 static int second = 0, promotionChoice = 0, clearFlag = 0;
6448 char promoChoice = NULLCHAR;
6451 if(appData.seekGraph && appData.icsActive && loggedOn &&
6452 (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
6453 SeekGraphClick(clickType, xPix, yPix, 0);
6457 if (clickType == Press) ErrorPopDown();
6458 MarkTargetSquares(1);
6460 x = EventToSquare(xPix, BOARD_WIDTH);
6461 y = EventToSquare(yPix, BOARD_HEIGHT);
6462 if (!flipView && y >= 0) {
6463 y = BOARD_HEIGHT - 1 - y;
6465 if (flipView && x >= 0) {
6466 x = BOARD_WIDTH - 1 - x;
6469 if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
6470 defaultPromoChoice = promoSweep;
6471 promoSweep = EmptySquare; // terminate sweep
6472 promoDefaultAltered = TRUE;
6473 if(!selectFlag) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
6476 if(promotionChoice) { // we are waiting for a click to indicate promotion piece
6477 if(clickType == Release) return; // ignore upclick of click-click destination
6478 promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
6479 if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
6480 if(gameInfo.holdingsWidth &&
6481 (WhiteOnMove(currentMove)
6482 ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y > 0
6483 : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT-1) ) {
6484 // click in right holdings, for determining promotion piece
6485 ChessSquare p = boards[currentMove][y][x];
6486 if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
6487 if(p != EmptySquare) {
6488 FinishMove(NormalMove, fromX, fromY, toX, toY, ToLower(PieceToChar(p)));
6493 DrawPosition(FALSE, boards[currentMove]);
6497 /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
6498 if(clickType == Press
6499 && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
6500 || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
6501 || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
6504 if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered)
6505 fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
6507 if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
6508 int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
6509 gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
6510 defaultPromoChoice = DefaultPromoChoice(side);
6513 autoQueen = appData.alwaysPromoteToQueen;
6517 gatingPiece = EmptySquare;
6518 if (clickType != Press) {
6519 if(dragging) { // [HGM] from-square must have been reset due to game end since last press
6520 DragPieceEnd(xPix, yPix); dragging = 0;
6521 DrawPosition(FALSE, NULL);
6525 fromX = x; fromY = y;
6526 if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
6527 // even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
6528 appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
6530 if (OKToStartUserMove(fromX, fromY)) {
6532 MarkTargetSquares(0);
6533 DragPieceBegin(xPix, yPix); dragging = 1;
6534 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
6535 promoSweep = defaultPromoChoice;
6536 selectFlag = 0; lastX = xPix; lastY = yPix;
6537 Sweep(0); // Pawn that is going to promote: preview promotion piece
6538 DisplayMessage("", _("Pull pawn backwards to under-promote"));
6540 if (appData.highlightDragging) {
6541 SetHighlights(fromX, fromY, -1, -1);
6543 } else fromX = fromY = -1;
6549 if (clickType == Press && gameMode != EditPosition) {
6554 // ignore off-board to clicks
6555 if(y < 0 || x < 0) return;
6557 /* Check if clicking again on the same color piece */
6558 fromP = boards[currentMove][fromY][fromX];
6559 toP = boards[currentMove][y][x];
6560 frc = gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom || gameInfo.variant == VariantSChess;
6561 if ((WhitePawn <= fromP && fromP <= WhiteKing &&
6562 WhitePawn <= toP && toP <= WhiteKing &&
6563 !(fromP == WhiteKing && toP == WhiteRook && frc) &&
6564 !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
6565 (BlackPawn <= fromP && fromP <= BlackKing &&
6566 BlackPawn <= toP && toP <= BlackKing &&
6567 !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
6568 !(fromP == BlackKing && toP == BlackRook && frc))) {
6569 /* Clicked again on same color piece -- changed his mind */
6570 second = (x == fromX && y == fromY);
6571 promoDefaultAltered = FALSE;
6572 if(!second || appData.oneClick && !OnlyMove(&x, &y, TRUE)) {
6573 if (appData.highlightDragging) {
6574 SetHighlights(x, y, -1, -1);
6578 if (OKToStartUserMove(x, y)) {
6579 if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
6580 (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
6581 y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
6582 gatingPiece = boards[currentMove][fromY][fromX];
6583 else gatingPiece = EmptySquare;
6585 fromY = y; dragging = 1;
6586 MarkTargetSquares(0);
6587 DragPieceBegin(xPix, yPix);
6588 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
6589 promoSweep = defaultPromoChoice;
6590 selectFlag = 0; lastX = xPix; lastY = yPix;
6591 Sweep(0); // Pawn that is going to promote: preview promotion piece
6595 if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
6598 // ignore clicks on holdings
6599 if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
6602 if (clickType == Release && x == fromX && y == fromY) {
6603 DragPieceEnd(xPix, yPix); dragging = 0;
6605 // a deferred attempt to click-click move an empty square on top of a piece
6606 boards[currentMove][y][x] = EmptySquare;
6608 DrawPosition(FALSE, boards[currentMove]);
6609 fromX = fromY = -1; clearFlag = 0;
6612 if (appData.animateDragging) {
6613 /* Undo animation damage if any */
6614 DrawPosition(FALSE, NULL);
6617 /* Second up/down in same square; just abort move */
6620 gatingPiece = EmptySquare;
6623 ClearPremoveHighlights();
6625 /* First upclick in same square; start click-click mode */
6626 SetHighlights(x, y, -1, -1);
6633 /* we now have a different from- and (possibly off-board) to-square */
6634 /* Completed move */
6637 saveAnimate = appData.animate;
6638 if (clickType == Press) {
6639 if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
6640 // must be Edit Position mode with empty-square selected
6641 fromX = x; fromY = y; DragPieceBegin(xPix, yPix); dragging = 1; // consider this a new attempt to drag
6642 if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
6645 /* Finish clickclick move */
6646 if (appData.animate || appData.highlightLastMove) {
6647 SetHighlights(fromX, fromY, toX, toY);
6652 /* Finish drag move */
6653 if (appData.highlightLastMove) {
6654 SetHighlights(fromX, fromY, toX, toY);
6658 DragPieceEnd(xPix, yPix); dragging = 0;
6659 /* Don't animate move and drag both */
6660 appData.animate = FALSE;
6663 // moves into holding are invalid for now (except in EditPosition, adapting to-square)
6664 if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
6665 ChessSquare piece = boards[currentMove][fromY][fromX];
6666 if(gameMode == EditPosition && piece != EmptySquare &&
6667 fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
6670 if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
6671 n = PieceToNumber(piece - (int)BlackPawn);
6672 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
6673 boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
6674 boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
6676 if(x == BOARD_RGHT+1 && piece < BlackPawn) {
6677 n = PieceToNumber(piece);
6678 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
6679 boards[currentMove][n][BOARD_WIDTH-1] = piece;
6680 boards[currentMove][n][BOARD_WIDTH-2]++;
6682 boards[currentMove][fromY][fromX] = EmptySquare;
6686 DrawPosition(TRUE, boards[currentMove]);
6690 // off-board moves should not be highlighted
6691 if(x < 0 || y < 0) ClearHighlights();
6693 if(gatingPiece != EmptySquare) promoChoice = ToLower(PieceToChar(gatingPiece));
6695 if (HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice)) {
6696 SetHighlights(fromX, fromY, toX, toY);
6697 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
6698 // [HGM] super: promotion to captured piece selected from holdings
6699 ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
6700 promotionChoice = TRUE;
6701 // kludge follows to temporarily execute move on display, without promoting yet
6702 boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
6703 boards[currentMove][toY][toX] = p;
6704 DrawPosition(FALSE, boards[currentMove]);
6705 boards[currentMove][fromY][fromX] = p; // take back, but display stays
6706 boards[currentMove][toY][toX] = q;
6707 DisplayMessage("Click in holdings to choose piece", "");
6712 int oldMove = currentMove;
6713 UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
6714 if (!appData.highlightLastMove || gotPremove) ClearHighlights();
6715 if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
6716 if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
6717 Explode(boards[currentMove-1], fromX, fromY, toX, toY))
6718 DrawPosition(TRUE, boards[currentMove]);
6721 appData.animate = saveAnimate;
6722 if (appData.animate || appData.animateDragging) {
6723 /* Undo animation damage if needed */
6724 DrawPosition(FALSE, NULL);
6728 int RightClick(ClickType action, int x, int y, int *fromX, int *fromY)
6729 { // front-end-free part taken out of PieceMenuPopup
6730 int whichMenu; int xSqr, ySqr;
6732 if(seekGraphUp) { // [HGM] seekgraph
6733 if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
6734 if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
6738 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
6739 && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
6740 if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
6741 if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
6742 if(action == Press) {
6743 originalFlip = flipView;
6744 flipView = !flipView; // temporarily flip board to see game from partners perspective
6745 DrawPosition(TRUE, partnerBoard);
6746 DisplayMessage(partnerStatus, "");
6748 } else if(action == Release) {
6749 flipView = originalFlip;
6750 DrawPosition(TRUE, boards[currentMove]);
6756 xSqr = EventToSquare(x, BOARD_WIDTH);
6757 ySqr = EventToSquare(y, BOARD_HEIGHT);
6758 if (action == Release) {
6759 if(pieceSweep != EmptySquare) {
6760 EditPositionMenuEvent(pieceSweep, toX, toY);
6761 pieceSweep = EmptySquare;
6762 } else UnLoadPV(); // [HGM] pv
6764 if (action != Press) return -2; // return code to be ignored
6767 if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
\r
6769 if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
\r
6770 if (xSqr < 0 || ySqr < 0) return -1;
6771 if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
6772 pieceSweep = shiftKey ? BlackPawn : WhitePawn; // [HGM] sweep: prepare selecting piece by mouse sweep
6773 toX = xSqr; toY = ySqr; lastX = x, lastY = y;
6774 if(flipView) toX = BOARD_WIDTH - 1 - toX; else toY = BOARD_HEIGHT - 1 - toY;
6778 if(!appData.icsEngineAnalyze) return -1;
6779 case IcsPlayingWhite:
6780 case IcsPlayingBlack:
6781 if(!appData.zippyPlay) goto noZip;
6784 case MachinePlaysWhite:
6785 case MachinePlaysBlack:
6786 case TwoMachinesPlay: // [HGM] pv: use for showing PV
6787 if (!appData.dropMenu) {
6789 return 2; // flag front-end to grab mouse events
6791 if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
6792 gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
6795 if (xSqr < 0 || ySqr < 0) return -1;
6796 if (!appData.dropMenu || appData.testLegality &&
6797 gameInfo.variant != VariantBughouse &&
6798 gameInfo.variant != VariantCrazyhouse) return -1;
6799 whichMenu = 1; // drop menu
6805 if (((*fromX = xSqr) < 0) ||
6806 ((*fromY = ySqr) < 0)) {
6807 *fromX = *fromY = -1;
6811 *fromX = BOARD_WIDTH - 1 - *fromX;
6813 *fromY = BOARD_HEIGHT - 1 - *fromY;
6818 void SendProgramStatsToFrontend( ChessProgramState * cps, ChessProgramStats * cpstats )
6820 // char * hint = lastHint;
6821 FrontEndProgramStats stats;
6823 stats.which = cps == &first ? 0 : 1;
6824 stats.depth = cpstats->depth;
6825 stats.nodes = cpstats->nodes;
6826 stats.score = cpstats->score;
6827 stats.time = cpstats->time;
6828 stats.pv = cpstats->movelist;
6829 stats.hint = lastHint;
6830 stats.an_move_index = 0;
6831 stats.an_move_count = 0;
6833 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
6834 stats.hint = cpstats->move_name;
6835 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
6836 stats.an_move_count = cpstats->nr_moves;
6839 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
6841 SetProgramStats( &stats );
6845 Count(Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
6846 { // count all piece types
6848 *nB = *nW = *wStale = *bStale = *bishopColor = 0;
6849 for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
6850 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
6853 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
6854 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
6855 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
6856 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
6857 p == BlackBishop || p == BlackFerz || p == BlackAlfil )
6858 *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
6863 SufficientDefence(int pCnt[], int side, int nMine, int nHis)
6865 int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
6866 int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
6868 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
6869 if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
6870 if(myPawns == 2 && nMine == 3) // KPP
6871 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
6872 if(myPawns == 1 && nMine == 2) // KP
6873 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
6874 if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
6875 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
6876 if(myPawns) return FALSE;
6877 if(pCnt[WhiteRook+side])
6878 return pCnt[BlackRook-side] ||
6879 pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
6880 pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
6881 pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
6882 if(pCnt[WhiteCannon+side]) {
6883 if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
6884 return majorDefense || pCnt[BlackAlfil-side] >= 2;
6886 if(pCnt[WhiteKnight+side])
6887 return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
6892 MatingPotential(int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
6894 VariantClass v = gameInfo.variant;
6896 if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
6897 if(v == VariantShatranj) return TRUE; // always winnable through baring
6898 if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
6899 if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
6901 if(v == VariantXiangqi) {
6902 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
6904 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
6905 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
6906 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
6907 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
6908 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
6909 if(stale) // we have at least one last-rank P plus perhaps C
6910 return majors // KPKX
6911 || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
6913 return pCnt[WhiteFerz+side] // KCAK
6914 || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
6915 || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
6916 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
6918 } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
6919 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
6921 if(nMine == 1) return FALSE; // bare King
6922 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
6923 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
6924 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
6925 // by now we have King + 1 piece (or multiple Bishops on the same color)
6926 if(pCnt[WhiteKnight+side])
6927 return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
6928 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
6929 || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
6931 return (pCnt[BlackKnight-side]); // KBKN, KFKN
6932 if(pCnt[WhiteAlfil+side])
6933 return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
6934 if(pCnt[WhiteWazir+side])
6935 return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
6942 Adjudicate(ChessProgramState *cps)
6943 { // [HGM] some adjudications useful with buggy engines
6944 // [HGM] adjudicate: made into separate routine, which now can be called after every move
6945 // In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
6946 // Actually ending the game is now based on the additional internal condition canAdjudicate.
6947 // Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
6948 int k, count = 0; static int bare = 1;
6949 ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
6950 Boolean canAdjudicate = !appData.icsActive;
6952 // most tests only when we understand the game, i.e. legality-checking on
6953 if( appData.testLegality )
6954 { /* [HGM] Some more adjudications for obstinate engines */
6955 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+1], i;
6956 static int moveCount = 6;
6958 char *reason = NULL;
6960 /* Count what is on board. */
6961 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
6963 /* Some material-based adjudications that have to be made before stalemate test */
6964 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
6965 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
6966 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
6967 if(canAdjudicate && appData.checkMates) {
6969 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
6970 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
6971 "Xboard adjudication: King destroyed", GE_XBOARD );
6976 /* Bare King in Shatranj (loses) or Losers (wins) */
6977 if( nrW == 1 || nrB == 1) {
6978 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
6979 boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
6980 if(canAdjudicate && appData.checkMates) {
6982 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
6983 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
6984 "Xboard adjudication: Bare king", GE_XBOARD );
6988 if( gameInfo.variant == VariantShatranj && --bare < 0)
6990 boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
6991 if(canAdjudicate && appData.checkMates) {
6992 /* but only adjudicate if adjudication enabled */
6994 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
6995 GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
6996 "Xboard adjudication: Bare king", GE_XBOARD );
7003 // don't wait for engine to announce game end if we can judge ourselves
7004 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
7006 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
7007 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
7008 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
7009 if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
7012 reason = "Xboard adjudication: 3rd check";
7013 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
7023 reason = "Xboard adjudication: Stalemate";
7024 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
7025 boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
7026 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
7027 boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
7028 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
7029 boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
7030 ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
7031 EP_CHECKMATE : EP_WINS);
7032 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi)
7033 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
7037 reason = "Xboard adjudication: Checkmate";
7038 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
7042 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
7044 result = GameIsDrawn; break;
7046 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
7048 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
7052 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
7054 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7055 GameEnds( result, reason, GE_XBOARD );
7059 /* Next absolutely insufficient mating material. */
7060 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
7061 !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
7062 { /* includes KBK, KNK, KK of KBKB with like Bishops */
7064 /* always flag draws, for judging claims */
7065 boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
7067 if(canAdjudicate && appData.materialDraws) {
7068 /* but only adjudicate them if adjudication enabled */
7069 if(engineOpponent) {
7070 SendToProgram("force\n", engineOpponent); // suppress reply
7071 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
7073 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
7078 /* Then some trivial draws (only adjudicate, cannot be claimed) */
7079 if(gameInfo.variant == VariantXiangqi ?
7080 SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
7082 ( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
7083 || nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
7084 || nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
7085 || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
7087 if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
7088 { /* if the first 3 moves do not show a tactical win, declare draw */
7089 if(engineOpponent) {
7090 SendToProgram("force\n", engineOpponent); // suppress reply
7091 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7093 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
7096 } else moveCount = 6;
7098 if (appData.debugMode) { int i;
7099 fprintf(debugFP, "repeat test fmm=%d bmm=%d ep=%d, reps=%d\n",
7100 forwardMostMove, backwardMostMove, boards[backwardMostMove][EP_STATUS],
7101 appData.drawRepeats);
7102 for( i=forwardMostMove; i>=backwardMostMove; i-- )
7103 fprintf(debugFP, "%d ep=%d\n", i, (signed char)boards[i][EP_STATUS]);
7107 // Repetition draws and 50-move rule can be applied independently of legality testing
7109 /* Check for rep-draws */
7111 for(k = forwardMostMove-2;
7112 k>=backwardMostMove && k>=forwardMostMove-100 &&
7113 (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
7114 (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE;
7117 if(CompareBoards(boards[k], boards[forwardMostMove])) {
7118 /* compare castling rights */
7119 if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
7120 (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
7121 rights++; /* King lost rights, while rook still had them */
7122 if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
7123 if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
7124 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
7125 rights++; /* but at least one rook lost them */
7127 if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
7128 (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
7130 if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
7131 if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
7132 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
7135 if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
7136 && appData.drawRepeats > 1) {
7137 /* adjudicate after user-specified nr of repeats */
7138 int result = GameIsDrawn;
7139 char *details = "XBoard adjudication: repetition draw";
7140 if(gameInfo.variant == VariantXiangqi && appData.testLegality) {
7141 // [HGM] xiangqi: check for forbidden perpetuals
7142 int m, ourPerpetual = 1, hisPerpetual = 1;
7143 for(m=forwardMostMove; m>k; m-=2) {
7144 if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
7145 ourPerpetual = 0; // the current mover did not always check
7146 if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
7147 hisPerpetual = 0; // the opponent did not always check
7149 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
7150 ourPerpetual, hisPerpetual);
7151 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
7152 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7153 details = "Xboard adjudication: perpetual checking";
7155 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
7156 break; // (or we would have caught him before). Abort repetition-checking loop.
7158 // Now check for perpetual chases
7159 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
7160 hisPerpetual = PerpetualChase(k, forwardMostMove);
7161 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
7162 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
7163 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7164 details = "Xboard adjudication: perpetual chasing";
7166 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
7167 break; // Abort repetition-checking loop.
7169 // if neither of us is checking or chasing all the time, or both are, it is draw
7171 if(engineOpponent) {
7172 SendToProgram("force\n", engineOpponent); // suppress reply
7173 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7175 GameEnds( result, details, GE_XBOARD );
7178 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
7179 boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
7183 /* Now we test for 50-move draws. Determine ply count */
7184 count = forwardMostMove;
7185 /* look for last irreversble move */
7186 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
7188 /* if we hit starting position, add initial plies */
7189 if( count == backwardMostMove )
7190 count -= initialRulePlies;
7191 count = forwardMostMove - count;
7192 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
7193 // adjust reversible move counter for checks in Xiangqi
7194 int i = forwardMostMove - count, inCheck = 0, lastCheck;
7195 if(i < backwardMostMove) i = backwardMostMove;
7196 while(i <= forwardMostMove) {
7197 lastCheck = inCheck; // check evasion does not count
7198 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
7199 if(inCheck || lastCheck) count--; // check does not count
7204 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
7205 /* this is used to judge if draw claims are legal */
7206 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
7207 if(engineOpponent) {
7208 SendToProgram("force\n", engineOpponent); // suppress reply
7209 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7211 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
7215 /* if draw offer is pending, treat it as a draw claim
7216 * when draw condition present, to allow engines a way to
7217 * claim draws before making their move to avoid a race
7218 * condition occurring after their move
7220 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
7222 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
7223 p = "Draw claim: 50-move rule";
7224 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
7225 p = "Draw claim: 3-fold repetition";
7226 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
7227 p = "Draw claim: insufficient mating material";
7228 if( p != NULL && canAdjudicate) {
7229 if(engineOpponent) {
7230 SendToProgram("force\n", engineOpponent); // suppress reply
7231 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7233 GameEnds( GameIsDrawn, p, GE_XBOARD );
7238 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
7239 if(engineOpponent) {
7240 SendToProgram("force\n", engineOpponent); // suppress reply
7241 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7243 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
7249 char *SendMoveToBookUser(int moveNr, ChessProgramState *cps, int initial)
7250 { // [HGM] book: this routine intercepts moves to simulate book replies
7251 char *bookHit = NULL;
7253 //first determine if the incoming move brings opponent into his book
7254 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
7255 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
7256 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
7257 if(bookHit != NULL && !cps->bookSuspend) {
7258 // make sure opponent is not going to reply after receiving move to book position
7259 SendToProgram("force\n", cps);
7260 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
7262 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
7263 // now arrange restart after book miss
7265 // after a book hit we never send 'go', and the code after the call to this routine
7266 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
7268 snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), bookHit); // force book move into program supposed to play it
7269 SendToProgram(buf, cps);
7270 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
7271 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
7272 SendToProgram("go\n", cps);
7273 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
7274 } else { // 'go' might be sent based on 'firstMove' after this routine returns
7275 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
7276 SendToProgram("go\n", cps);
7277 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
7279 return bookHit; // notify caller of hit, so it can take action to send move to opponent
7283 ChessProgramState *savedState;
7284 void DeferredBookMove(void)
7286 if(savedState->lastPing != savedState->lastPong)
7287 ScheduleDelayedEvent(DeferredBookMove, 10);
7289 HandleMachineMove(savedMessage, savedState);
7293 HandleMachineMove(message, cps)
7295 ChessProgramState *cps;
7297 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
7298 char realname[MSG_SIZ];
7299 int fromX, fromY, toX, toY;
7308 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
7310 * Kludge to ignore BEL characters
7312 while (*message == '\007') message++;
7315 * [HGM] engine debug message: ignore lines starting with '#' character
7317 if(cps->debug && *message == '#') return;
7320 * Look for book output
7322 if (cps == &first && bookRequested) {
7323 if (message[0] == '\t' || message[0] == ' ') {
7324 /* Part of the book output is here; append it */
7325 strcat(bookOutput, message);
7326 strcat(bookOutput, " \n");
7328 } else if (bookOutput[0] != NULLCHAR) {
7329 /* All of book output has arrived; display it */
7330 char *p = bookOutput;
7331 while (*p != NULLCHAR) {
7332 if (*p == '\t') *p = ' ';
7335 DisplayInformation(bookOutput);
7336 bookRequested = FALSE;
7337 /* Fall through to parse the current output */
7342 * Look for machine move.
7344 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
7345 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
7347 /* This method is only useful on engines that support ping */
7348 if (cps->lastPing != cps->lastPong) {
7349 if (gameMode == BeginningOfGame) {
7350 /* Extra move from before last new; ignore */
7351 if (appData.debugMode) {
7352 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7355 if (appData.debugMode) {
7356 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7357 cps->which, gameMode);
7360 SendToProgram("undo\n", cps);
7366 case BeginningOfGame:
7367 /* Extra move from before last reset; ignore */
7368 if (appData.debugMode) {
7369 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7376 /* Extra move after we tried to stop. The mode test is
7377 not a reliable way of detecting this problem, but it's
7378 the best we can do on engines that don't support ping.
7380 if (appData.debugMode) {
7381 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7382 cps->which, gameMode);
7384 SendToProgram("undo\n", cps);
7387 case MachinePlaysWhite:
7388 case IcsPlayingWhite:
7389 machineWhite = TRUE;
7392 case MachinePlaysBlack:
7393 case IcsPlayingBlack:
7394 machineWhite = FALSE;
7397 case TwoMachinesPlay:
7398 machineWhite = (cps->twoMachinesColor[0] == 'w');
7401 if (WhiteOnMove(forwardMostMove) != machineWhite) {
7402 if (appData.debugMode) {
7404 "Ignoring move out of turn by %s, gameMode %d"
7405 ", forwardMost %d\n",
7406 cps->which, gameMode, forwardMostMove);
7411 if (appData.debugMode) { int f = forwardMostMove;
7412 fprintf(debugFP, "machine move %d, castling = %d %d %d %d %d %d\n", f,
7413 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
7414 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
7416 if(cps->alphaRank) AlphaRank(machineMove, 4);
7417 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
7418 &fromX, &fromY, &toX, &toY, &promoChar)) {
7419 /* Machine move could not be parsed; ignore it. */
7420 snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
7421 machineMove, _(cps->which));
7422 DisplayError(buf1, 0);
7423 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
7424 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType);
7425 if (gameMode == TwoMachinesPlay) {
7426 GameEnds(machineWhite ? BlackWins : WhiteWins,
7432 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
7433 /* So we have to redo legality test with true e.p. status here, */
7434 /* to make sure an illegal e.p. capture does not slip through, */
7435 /* to cause a forfeit on a justified illegal-move complaint */
7436 /* of the opponent. */
7437 if( gameMode==TwoMachinesPlay && appData.testLegality ) {
7439 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
7440 fromY, fromX, toY, toX, promoChar);
7441 if (appData.debugMode) {
7443 for(i=0; i< nrCastlingRights; i++) fprintf(debugFP, "(%d,%d) ",
7444 boards[forwardMostMove][CASTLING][i], castlingRank[i]);
7445 fprintf(debugFP, "castling rights\n");
7447 if(moveType == IllegalMove) {
7448 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
7449 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
7450 GameEnds(machineWhite ? BlackWins : WhiteWins,
7453 } else if(gameInfo.variant != VariantFischeRandom && gameInfo.variant != VariantCapaRandom)
7454 /* [HGM] Kludge to handle engines that send FRC-style castling
7455 when they shouldn't (like TSCP-Gothic) */
7457 case WhiteASideCastleFR:
7458 case BlackASideCastleFR:
7460 currentMoveString[2]++;
7462 case WhiteHSideCastleFR:
7463 case BlackHSideCastleFR:
7465 currentMoveString[2]--;
7467 default: ; // nothing to do, but suppresses warning of pedantic compilers
7470 hintRequested = FALSE;
7471 lastHint[0] = NULLCHAR;
7472 bookRequested = FALSE;
7473 /* Program may be pondering now */
7474 cps->maybeThinking = TRUE;
7475 if (cps->sendTime == 2) cps->sendTime = 1;
7476 if (cps->offeredDraw) cps->offeredDraw--;
7478 /* [AS] Save move info*/
7479 pvInfoList[ forwardMostMove ].score = programStats.score;
7480 pvInfoList[ forwardMostMove ].depth = programStats.depth;
7481 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
7483 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
7485 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
7486 if( gameMode == TwoMachinesPlay && adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
7489 while( count < adjudicateLossPlies ) {
7490 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
7493 score = -score; /* Flip score for winning side */
7496 if( score > adjudicateLossThreshold ) {
7503 if( count >= adjudicateLossPlies ) {
7504 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7506 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7507 "Xboard adjudication",
7514 if(Adjudicate(cps)) {
7515 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7516 return; // [HGM] adjudicate: for all automatic game ends
7520 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
7522 if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
7523 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
7525 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7527 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7529 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
7530 char buf[3*MSG_SIZ];
7532 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
7533 programStats.score / 100.,
7535 programStats.time / 100.,
7536 (unsigned int)programStats.nodes,
7537 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
7538 programStats.movelist);
7540 if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.nodes, programStats.nodes);
7545 /* [AS] Clear stats for next move */
7546 ClearProgramStats();
7547 thinkOutput[0] = NULLCHAR;
7548 hiddenThinkOutputState = 0;
7551 if (gameMode == TwoMachinesPlay) {
7552 /* [HGM] relaying draw offers moved to after reception of move */
7553 /* and interpreting offer as claim if it brings draw condition */
7554 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
7555 SendToProgram("draw\n", cps->other);
7557 if (cps->other->sendTime) {
7558 SendTimeRemaining(cps->other,
7559 cps->other->twoMachinesColor[0] == 'w');
7561 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
7562 if (firstMove && !bookHit) {
7564 if (cps->other->useColors) {
7565 SendToProgram(cps->other->twoMachinesColor, cps->other);
7567 SendToProgram("go\n", cps->other);
7569 cps->other->maybeThinking = TRUE;
7572 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7574 if (!pausing && appData.ringBellAfterMoves) {
7579 * Reenable menu items that were disabled while
7580 * machine was thinking
7582 if (gameMode != TwoMachinesPlay)
7583 SetUserThinkingEnables();
7585 // [HGM] book: after book hit opponent has received move and is now in force mode
7586 // force the book reply into it, and then fake that it outputted this move by jumping
7587 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
7589 static char bookMove[MSG_SIZ]; // a bit generous?
7591 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
7592 strcat(bookMove, bookHit);
7595 programStats.nodes = programStats.depth = programStats.time =
7596 programStats.score = programStats.got_only_move = 0;
7597 sprintf(programStats.movelist, "%s (xbook)", bookHit);
7599 if(cps->lastPing != cps->lastPong) {
7600 savedMessage = message; // args for deferred call
7602 ScheduleDelayedEvent(DeferredBookMove, 10);
7611 /* Set special modes for chess engines. Later something general
7612 * could be added here; for now there is just one kludge feature,
7613 * needed because Crafty 15.10 and earlier don't ignore SIGINT
7614 * when "xboard" is given as an interactive command.
7616 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
7617 cps->useSigint = FALSE;
7618 cps->useSigterm = FALSE;
7620 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
7621 ParseFeatures(message+8, cps);
7622 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
7625 if (!appData.testLegality && !strncmp(message, "setup ", 6)) { // [HGM] allow first engine to define opening position
7626 int dummy, s=6; char buf[MSG_SIZ];
7627 if(appData.icsActive || forwardMostMove != 0 || cps != &first || startedFromSetupPosition) return;
7628 if(sscanf(message, "setup (%s", buf) == 1) s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTable(pieceToChar, buf);
7629 ParseFEN(boards[0], &dummy, message+s);
7630 DrawPosition(TRUE, boards[0]);
7631 startedFromSetupPosition = TRUE;
7634 /* [HGM] Allow engine to set up a position. Don't ask me why one would
7635 * want this, I was asked to put it in, and obliged.
7637 if (!strncmp(message, "setboard ", 9)) {
7638 Board initial_position;
7640 GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
7642 if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9)) {
7643 DisplayError(_("Bad FEN received from engine"), 0);
7647 CopyBoard(boards[0], initial_position);
7648 initialRulePlies = FENrulePlies;
7649 if(blackPlaysFirst) gameMode = MachinePlaysWhite;
7650 else gameMode = MachinePlaysBlack;
7651 DrawPosition(FALSE, boards[currentMove]);
7657 * Look for communication commands
7659 if (!strncmp(message, "telluser ", 9)) {
7660 if(message[9] == '\\' && message[10] == '\\')
7661 EscapeExpand(message+9, message+11); // [HGM] esc: allow escape sequences in popup box
7662 DisplayNote(message + 9);
7665 if (!strncmp(message, "tellusererror ", 14)) {
7667 if(message[14] == '\\' && message[15] == '\\')
7668 EscapeExpand(message+14, message+16); // [HGM] esc: allow escape sequences in popup box
7669 DisplayError(message + 14, 0);
7672 if (!strncmp(message, "tellopponent ", 13)) {
7673 if (appData.icsActive) {
7675 snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
7679 DisplayNote(message + 13);
7683 if (!strncmp(message, "tellothers ", 11)) {
7684 if (appData.icsActive) {
7686 snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
7692 if (!strncmp(message, "tellall ", 8)) {
7693 if (appData.icsActive) {
7695 snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
7699 DisplayNote(message + 8);
7703 if (strncmp(message, "warning", 7) == 0) {
7704 /* Undocumented feature, use tellusererror in new code */
7705 DisplayError(message, 0);
7708 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
7709 safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
7710 strcat(realname, " query");
7711 AskQuestion(realname, buf2, buf1, cps->pr);
7714 /* Commands from the engine directly to ICS. We don't allow these to be
7715 * sent until we are logged on. Crafty kibitzes have been known to
7716 * interfere with the login process.
7719 if (!strncmp(message, "tellics ", 8)) {
7720 SendToICS(message + 8);
7724 if (!strncmp(message, "tellicsnoalias ", 15)) {
7725 SendToICS(ics_prefix);
7726 SendToICS(message + 15);
7730 /* The following are for backward compatibility only */
7731 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
7732 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
7733 SendToICS(ics_prefix);
7739 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
7743 * If the move is illegal, cancel it and redraw the board.
7744 * Also deal with other error cases. Matching is rather loose
7745 * here to accommodate engines written before the spec.
7747 if (strncmp(message + 1, "llegal move", 11) == 0 ||
7748 strncmp(message, "Error", 5) == 0) {
7749 if (StrStr(message, "name") ||
7750 StrStr(message, "rating") || StrStr(message, "?") ||
7751 StrStr(message, "result") || StrStr(message, "board") ||
7752 StrStr(message, "bk") || StrStr(message, "computer") ||
7753 StrStr(message, "variant") || StrStr(message, "hint") ||
7754 StrStr(message, "random") || StrStr(message, "depth") ||
7755 StrStr(message, "accepted")) {
7758 if (StrStr(message, "protover")) {
7759 /* Program is responding to input, so it's apparently done
7760 initializing, and this error message indicates it is
7761 protocol version 1. So we don't need to wait any longer
7762 for it to initialize and send feature commands. */
7763 FeatureDone(cps, 1);
7764 cps->protocolVersion = 1;
7767 cps->maybeThinking = FALSE;
7769 if (StrStr(message, "draw")) {
7770 /* Program doesn't have "draw" command */
7771 cps->sendDrawOffers = 0;
7774 if (cps->sendTime != 1 &&
7775 (StrStr(message, "time") || StrStr(message, "otim"))) {
7776 /* Program apparently doesn't have "time" or "otim" command */
7780 if (StrStr(message, "analyze")) {
7781 cps->analysisSupport = FALSE;
7782 cps->analyzing = FALSE;
7784 snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
7785 DisplayError(buf2, 0);
7788 if (StrStr(message, "(no matching move)st")) {
7789 /* Special kludge for GNU Chess 4 only */
7790 cps->stKludge = TRUE;
7791 SendTimeControl(cps, movesPerSession, timeControl,
7792 timeIncrement, appData.searchDepth,
7796 if (StrStr(message, "(no matching move)sd")) {
7797 /* Special kludge for GNU Chess 4 only */
7798 cps->sdKludge = TRUE;
7799 SendTimeControl(cps, movesPerSession, timeControl,
7800 timeIncrement, appData.searchDepth,
7804 if (!StrStr(message, "llegal")) {
7807 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
7808 gameMode == IcsIdle) return;
7809 if (forwardMostMove <= backwardMostMove) return;
7810 if (pausing) PauseEvent();
7811 if(appData.forceIllegal) {
7812 // [HGM] illegal: machine refused move; force position after move into it
7813 SendToProgram("force\n", cps);
7814 if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
7815 // we have a real problem now, as SendBoard will use the a2a3 kludge
7816 // when black is to move, while there might be nothing on a2 or black
7817 // might already have the move. So send the board as if white has the move.
7818 // But first we must change the stm of the engine, as it refused the last move
7819 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
7820 if(WhiteOnMove(forwardMostMove)) {
7821 SendToProgram("a7a6\n", cps); // for the engine black still had the move
7822 SendBoard(cps, forwardMostMove); // kludgeless board
7824 SendToProgram("a2a3\n", cps); // for the engine white still had the move
7825 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
7826 SendBoard(cps, forwardMostMove+1); // kludgeless board
7828 } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
7829 if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
7830 gameMode == TwoMachinesPlay)
7831 SendToProgram("go\n", cps);
7834 if (gameMode == PlayFromGameFile) {
7835 /* Stop reading this game file */
7836 gameMode = EditGame;
7839 /* [HGM] illegal-move claim should forfeit game when Xboard */
7840 /* only passes fully legal moves */
7841 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
7842 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
7843 "False illegal-move claim", GE_XBOARD );
7844 return; // do not take back move we tested as valid
7846 currentMove = forwardMostMove-1;
7847 DisplayMove(currentMove-1); /* before DisplayMoveError */
7848 SwitchClocks(forwardMostMove-1); // [HGM] race
7849 DisplayBothClocks();
7850 snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
7851 parseList[currentMove], _(cps->which));
7852 DisplayMoveError(buf1);
7853 DrawPosition(FALSE, boards[currentMove]);
7856 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
7857 /* Program has a broken "time" command that
7858 outputs a string not ending in newline.
7864 * If chess program startup fails, exit with an error message.
7865 * Attempts to recover here are futile.
7867 if ((StrStr(message, "unknown host") != NULL)
7868 || (StrStr(message, "No remote directory") != NULL)
7869 || (StrStr(message, "not found") != NULL)
7870 || (StrStr(message, "No such file") != NULL)
7871 || (StrStr(message, "can't alloc") != NULL)
7872 || (StrStr(message, "Permission denied") != NULL)) {
7874 cps->maybeThinking = FALSE;
7875 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
7876 _(cps->which), cps->program, cps->host, message);
7877 RemoveInputSource(cps->isr);
7878 DisplayFatalError(buf1, 0, 1);
7883 * Look for hint output
7885 if (sscanf(message, "Hint: %s", buf1) == 1) {
7886 if (cps == &first && hintRequested) {
7887 hintRequested = FALSE;
7888 if (ParseOneMove(buf1, forwardMostMove, &moveType,
7889 &fromX, &fromY, &toX, &toY, &promoChar)) {
7890 (void) CoordsToAlgebraic(boards[forwardMostMove],
7891 PosFlags(forwardMostMove),
7892 fromY, fromX, toY, toX, promoChar, buf1);
7893 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
7894 DisplayInformation(buf2);
7896 /* Hint move could not be parsed!? */
7897 snprintf(buf2, sizeof(buf2),
7898 _("Illegal hint move \"%s\"\nfrom %s chess program"),
7899 buf1, _(cps->which));
7900 DisplayError(buf2, 0);
7903 safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
7909 * Ignore other messages if game is not in progress
7911 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
7912 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
7915 * look for win, lose, draw, or draw offer
7917 if (strncmp(message, "1-0", 3) == 0) {
7918 char *p, *q, *r = "";
7919 p = strchr(message, '{');
7927 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
7929 } else if (strncmp(message, "0-1", 3) == 0) {
7930 char *p, *q, *r = "";
7931 p = strchr(message, '{');
7939 /* Kludge for Arasan 4.1 bug */
7940 if (strcmp(r, "Black resigns") == 0) {
7941 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
7944 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
7946 } else if (strncmp(message, "1/2", 3) == 0) {
7947 char *p, *q, *r = "";
7948 p = strchr(message, '{');
7957 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
7960 } else if (strncmp(message, "White resign", 12) == 0) {
7961 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
7963 } else if (strncmp(message, "Black resign", 12) == 0) {
7964 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
7966 } else if (strncmp(message, "White matches", 13) == 0 ||
7967 strncmp(message, "Black matches", 13) == 0 ) {
7968 /* [HGM] ignore GNUShogi noises */
7970 } else if (strncmp(message, "White", 5) == 0 &&
7971 message[5] != '(' &&
7972 StrStr(message, "Black") == NULL) {
7973 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
7975 } else if (strncmp(message, "Black", 5) == 0 &&
7976 message[5] != '(') {
7977 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
7979 } else if (strcmp(message, "resign") == 0 ||
7980 strcmp(message, "computer resigns") == 0) {
7982 case MachinePlaysBlack:
7983 case IcsPlayingBlack:
7984 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
7986 case MachinePlaysWhite:
7987 case IcsPlayingWhite:
7988 GameEnds(BlackWins, "White resigns", GE_ENGINE);
7990 case TwoMachinesPlay:
7991 if (cps->twoMachinesColor[0] == 'w')
7992 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
7994 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8001 } else if (strncmp(message, "opponent mates", 14) == 0) {
8003 case MachinePlaysBlack:
8004 case IcsPlayingBlack:
8005 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8007 case MachinePlaysWhite:
8008 case IcsPlayingWhite:
8009 GameEnds(BlackWins, "Black mates", GE_ENGINE);
8011 case TwoMachinesPlay:
8012 if (cps->twoMachinesColor[0] == 'w')
8013 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8015 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8022 } else if (strncmp(message, "computer mates", 14) == 0) {
8024 case MachinePlaysBlack:
8025 case IcsPlayingBlack:
8026 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
8028 case MachinePlaysWhite:
8029 case IcsPlayingWhite:
8030 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8032 case TwoMachinesPlay:
8033 if (cps->twoMachinesColor[0] == 'w')
8034 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8036 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8043 } else if (strncmp(message, "checkmate", 9) == 0) {
8044 if (WhiteOnMove(forwardMostMove)) {
8045 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8047 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8050 } else if (strstr(message, "Draw") != NULL ||
8051 strstr(message, "game is a draw") != NULL) {
8052 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
8054 } else if (strstr(message, "offer") != NULL &&
8055 strstr(message, "draw") != NULL) {
8057 if (appData.zippyPlay && first.initDone) {
8058 /* Relay offer to ICS */
8059 SendToICS(ics_prefix);
8060 SendToICS("draw\n");
8063 cps->offeredDraw = 2; /* valid until this engine moves twice */
8064 if (gameMode == TwoMachinesPlay) {
8065 if (cps->other->offeredDraw) {
8066 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8067 /* [HGM] in two-machine mode we delay relaying draw offer */
8068 /* until after we also have move, to see if it is really claim */
8070 } else if (gameMode == MachinePlaysWhite ||
8071 gameMode == MachinePlaysBlack) {
8072 if (userOfferedDraw) {
8073 DisplayInformation(_("Machine accepts your draw offer"));
8074 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8076 DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
8083 * Look for thinking output
8085 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
8086 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
8088 int plylev, mvleft, mvtot, curscore, time;
8089 char mvname[MOVE_LEN];
8093 int prefixHint = FALSE;
8094 mvname[0] = NULLCHAR;
8097 case MachinePlaysBlack:
8098 case IcsPlayingBlack:
8099 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8101 case MachinePlaysWhite:
8102 case IcsPlayingWhite:
8103 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8108 case IcsObserving: /* [DM] icsEngineAnalyze */
8109 if (!appData.icsEngineAnalyze) ignore = TRUE;
8111 case TwoMachinesPlay:
8112 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
8122 ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
8124 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8125 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
8127 if (plyext != ' ' && plyext != '\t') {
8131 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8132 if( cps->scoreIsAbsolute &&
8133 ( gameMode == MachinePlaysBlack ||
8134 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
8135 gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
8136 (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
8137 !WhiteOnMove(currentMove)
8140 curscore = -curscore;
8144 tempStats.depth = plylev;
8145 tempStats.nodes = nodes;
8146 tempStats.time = time;
8147 tempStats.score = curscore;
8148 tempStats.got_only_move = 0;
8150 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
8153 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
8154 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
8155 if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
8156 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
8157 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
8158 if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
8159 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
8160 blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
8163 /* Buffer overflow protection */
8164 if (buf1[0] != NULLCHAR) {
8165 if (strlen(buf1) >= sizeof(tempStats.movelist)
8166 && appData.debugMode) {
8168 "PV is too long; using the first %u bytes.\n",
8169 (unsigned) sizeof(tempStats.movelist) - 1);
8172 safeStrCpy( tempStats.movelist, buf1, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
8174 sprintf(tempStats.movelist, " no PV\n");
8177 if (tempStats.seen_stat) {
8178 tempStats.ok_to_send = 1;
8181 if (strchr(tempStats.movelist, '(') != NULL) {
8182 tempStats.line_is_book = 1;
8183 tempStats.nr_moves = 0;
8184 tempStats.moves_left = 0;
8186 tempStats.line_is_book = 0;
8189 if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
8190 programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
8192 SendProgramStatsToFrontend( cps, &tempStats );
8195 [AS] Protect the thinkOutput buffer from overflow... this
8196 is only useful if buf1 hasn't overflowed first!
8198 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s",
8200 (gameMode == TwoMachinesPlay ?
8201 ToUpper(cps->twoMachinesColor[0]) : ' '),
8202 ((double) curscore) / 100.0,
8203 prefixHint ? lastHint : "",
8204 prefixHint ? " " : "" );
8206 if( buf1[0] != NULLCHAR ) {
8207 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
8209 if( strlen(buf1) > max_len ) {
8210 if( appData.debugMode) {
8211 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
8213 buf1[max_len+1] = '\0';
8216 strcat( thinkOutput, buf1 );
8219 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
8220 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8221 DisplayMove(currentMove - 1);
8225 } else if ((p=StrStr(message, "(only move)")) != NULL) {
8226 /* crafty (9.25+) says "(only move) <move>"
8227 * if there is only 1 legal move
8229 sscanf(p, "(only move) %s", buf1);
8230 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
8231 sprintf(programStats.movelist, "%s (only move)", buf1);
8232 programStats.depth = 1;
8233 programStats.nr_moves = 1;
8234 programStats.moves_left = 1;
8235 programStats.nodes = 1;
8236 programStats.time = 1;
8237 programStats.got_only_move = 1;
8239 /* Not really, but we also use this member to
8240 mean "line isn't going to change" (Crafty
8241 isn't searching, so stats won't change) */
8242 programStats.line_is_book = 1;
8244 SendProgramStatsToFrontend( cps, &programStats );
8246 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8247 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8248 DisplayMove(currentMove - 1);
8251 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
8252 &time, &nodes, &plylev, &mvleft,
8253 &mvtot, mvname) >= 5) {
8254 /* The stat01: line is from Crafty (9.29+) in response
8255 to the "." command */
8256 programStats.seen_stat = 1;
8257 cps->maybeThinking = TRUE;
8259 if (programStats.got_only_move || !appData.periodicUpdates)
8262 programStats.depth = plylev;
8263 programStats.time = time;
8264 programStats.nodes = nodes;
8265 programStats.moves_left = mvleft;
8266 programStats.nr_moves = mvtot;
8267 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
8268 programStats.ok_to_send = 1;
8269 programStats.movelist[0] = '\0';
8271 SendProgramStatsToFrontend( cps, &programStats );
8275 } else if (strncmp(message,"++",2) == 0) {
8276 /* Crafty 9.29+ outputs this */
8277 programStats.got_fail = 2;
8280 } else if (strncmp(message,"--",2) == 0) {
8281 /* Crafty 9.29+ outputs this */
8282 programStats.got_fail = 1;
8285 } else if (thinkOutput[0] != NULLCHAR &&
8286 strncmp(message, " ", 4) == 0) {
8287 unsigned message_len;
8290 while (*p && *p == ' ') p++;
8292 message_len = strlen( p );
8294 /* [AS] Avoid buffer overflow */
8295 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
8296 strcat(thinkOutput, " ");
8297 strcat(thinkOutput, p);
8300 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
8301 strcat(programStats.movelist, " ");
8302 strcat(programStats.movelist, p);
8305 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8306 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8307 DisplayMove(currentMove - 1);
8315 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8316 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
8318 ChessProgramStats cpstats;
8320 if (plyext != ' ' && plyext != '\t') {
8324 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8325 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
8326 curscore = -curscore;
8329 cpstats.depth = plylev;
8330 cpstats.nodes = nodes;
8331 cpstats.time = time;
8332 cpstats.score = curscore;
8333 cpstats.got_only_move = 0;
8334 cpstats.movelist[0] = '\0';
8336 if (buf1[0] != NULLCHAR) {
8337 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
8340 cpstats.ok_to_send = 0;
8341 cpstats.line_is_book = 0;
8342 cpstats.nr_moves = 0;
8343 cpstats.moves_left = 0;
8345 SendProgramStatsToFrontend( cps, &cpstats );
8352 /* Parse a game score from the character string "game", and
8353 record it as the history of the current game. The game
8354 score is NOT assumed to start from the standard position.
8355 The display is not updated in any way.
8358 ParseGameHistory(game)
8362 int fromX, fromY, toX, toY, boardIndex;
8367 if (appData.debugMode)
8368 fprintf(debugFP, "Parsing game history: %s\n", game);
8370 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
8371 gameInfo.site = StrSave(appData.icsHost);
8372 gameInfo.date = PGNDate();
8373 gameInfo.round = StrSave("-");
8375 /* Parse out names of players */
8376 while (*game == ' ') game++;
8378 while (*game != ' ') *p++ = *game++;
8380 gameInfo.white = StrSave(buf);
8381 while (*game == ' ') game++;
8383 while (*game != ' ' && *game != '\n') *p++ = *game++;
8385 gameInfo.black = StrSave(buf);
8388 boardIndex = blackPlaysFirst ? 1 : 0;
8391 yyboardindex = boardIndex;
8392 moveType = (ChessMove) Myylex();
8394 case IllegalMove: /* maybe suicide chess, etc. */
8395 if (appData.debugMode) {
8396 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
8397 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8398 setbuf(debugFP, NULL);
8400 case WhitePromotion:
8401 case BlackPromotion:
8402 case WhiteNonPromotion:
8403 case BlackNonPromotion:
8405 case WhiteCapturesEnPassant:
8406 case BlackCapturesEnPassant:
8407 case WhiteKingSideCastle:
8408 case WhiteQueenSideCastle:
8409 case BlackKingSideCastle:
8410 case BlackQueenSideCastle:
8411 case WhiteKingSideCastleWild:
8412 case WhiteQueenSideCastleWild:
8413 case BlackKingSideCastleWild:
8414 case BlackQueenSideCastleWild:
8416 case WhiteHSideCastleFR:
8417 case WhiteASideCastleFR:
8418 case BlackHSideCastleFR:
8419 case BlackASideCastleFR:
8421 fromX = currentMoveString[0] - AAA;
8422 fromY = currentMoveString[1] - ONE;
8423 toX = currentMoveString[2] - AAA;
8424 toY = currentMoveString[3] - ONE;
8425 promoChar = currentMoveString[4];
8429 fromX = moveType == WhiteDrop ?
8430 (int) CharToPiece(ToUpper(currentMoveString[0])) :
8431 (int) CharToPiece(ToLower(currentMoveString[0]));
8433 toX = currentMoveString[2] - AAA;
8434 toY = currentMoveString[3] - ONE;
8435 promoChar = NULLCHAR;
8439 snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
8440 if (appData.debugMode) {
8441 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
8442 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8443 setbuf(debugFP, NULL);
8445 DisplayError(buf, 0);
8447 case ImpossibleMove:
8449 snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
8450 if (appData.debugMode) {
8451 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
8452 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8453 setbuf(debugFP, NULL);
8455 DisplayError(buf, 0);
8458 if (boardIndex < backwardMostMove) {
8459 /* Oops, gap. How did that happen? */
8460 DisplayError(_("Gap in move list"), 0);
8463 backwardMostMove = blackPlaysFirst ? 1 : 0;
8464 if (boardIndex > forwardMostMove) {
8465 forwardMostMove = boardIndex;
8469 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
8470 strcat(parseList[boardIndex-1], " ");
8471 strcat(parseList[boardIndex-1], yy_text);
8483 case GameUnfinished:
8484 if (gameMode == IcsExamining) {
8485 if (boardIndex < backwardMostMove) {
8486 /* Oops, gap. How did that happen? */
8489 backwardMostMove = blackPlaysFirst ? 1 : 0;
8492 gameInfo.result = moveType;
8493 p = strchr(yy_text, '{');
8494 if (p == NULL) p = strchr(yy_text, '(');
8497 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
8499 q = strchr(p, *p == '{' ? '}' : ')');
8500 if (q != NULL) *q = NULLCHAR;
8503 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
8504 gameInfo.resultDetails = StrSave(p);
8507 if (boardIndex >= forwardMostMove &&
8508 !(gameMode == IcsObserving && ics_gamenum == -1)) {
8509 backwardMostMove = blackPlaysFirst ? 1 : 0;
8512 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
8513 fromY, fromX, toY, toX, promoChar,
8514 parseList[boardIndex]);
8515 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
8516 /* currentMoveString is set as a side-effect of yylex */
8517 safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
8518 strcat(moveList[boardIndex], "\n");
8520 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
8521 switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
8527 if(gameInfo.variant != VariantShogi)
8528 strcat(parseList[boardIndex - 1], "+");
8532 strcat(parseList[boardIndex - 1], "#");
8539 /* Apply a move to the given board */
8541 ApplyMove(fromX, fromY, toX, toY, promoChar, board)
8542 int fromX, fromY, toX, toY;
8546 ChessSquare captured = board[toY][toX], piece, king; int p, oldEP = EP_NONE, berolina = 0;
8547 int promoRank = gameInfo.variant == VariantMakruk ? 3 : 1;
8549 /* [HGM] compute & store e.p. status and castling rights for new position */
8550 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
8552 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
8553 oldEP = (signed char)board[EP_STATUS];
8554 board[EP_STATUS] = EP_NONE;
8556 if( board[toY][toX] != EmptySquare )
8557 board[EP_STATUS] = EP_CAPTURE;
8559 if (fromY == DROP_RANK) {
8561 piece = board[toY][toX] = (ChessSquare) fromX;
8565 if( board[fromY][fromX] == WhiteLance || board[fromY][fromX] == BlackLance ) {
8566 if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi )
8567 board[EP_STATUS] = EP_PAWN_MOVE; // Lance is Pawn-like in most variants
8569 if( board[fromY][fromX] == WhitePawn ) {
8570 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
8571 board[EP_STATUS] = EP_PAWN_MOVE;
8573 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
8574 gameInfo.variant != VariantBerolina || toX < fromX)
8575 board[EP_STATUS] = toX | berolina;
8576 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
8577 gameInfo.variant != VariantBerolina || toX > fromX)
8578 board[EP_STATUS] = toX;
8581 if( board[fromY][fromX] == BlackPawn ) {
8582 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
8583 board[EP_STATUS] = EP_PAWN_MOVE;
8584 if( toY-fromY== -2) {
8585 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
8586 gameInfo.variant != VariantBerolina || toX < fromX)
8587 board[EP_STATUS] = toX | berolina;
8588 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
8589 gameInfo.variant != VariantBerolina || toX > fromX)
8590 board[EP_STATUS] = toX;
8594 for(i=0; i<nrCastlingRights; i++) {
8595 if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
8596 board[CASTLING][i] == toX && castlingRank[i] == toY
8597 ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
8600 if (fromX == toX && fromY == toY) return;
8602 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
8603 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
8604 if(gameInfo.variant == VariantKnightmate)
8605 king += (int) WhiteUnicorn - (int) WhiteKing;
8607 /* Code added by Tord: */
8608 /* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
8609 if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
8610 board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
8611 board[fromY][fromX] = EmptySquare;
8612 board[toY][toX] = EmptySquare;
8613 if((toX > fromX) != (piece == WhiteRook)) {
8614 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
8616 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
8618 } else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
8619 board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
8620 board[fromY][fromX] = EmptySquare;
8621 board[toY][toX] = EmptySquare;
8622 if((toX > fromX) != (piece == BlackRook)) {
8623 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
8625 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
8627 /* End of code added by Tord */
8629 } else if (board[fromY][fromX] == king
8630 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8631 && toY == fromY && toX > fromX+1) {
8632 board[fromY][fromX] = EmptySquare;
8633 board[toY][toX] = king;
8634 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
8635 board[fromY][BOARD_RGHT-1] = EmptySquare;
8636 } else if (board[fromY][fromX] == king
8637 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8638 && toY == fromY && toX < fromX-1) {
8639 board[fromY][fromX] = EmptySquare;
8640 board[toY][toX] = king;
8641 board[toY][toX+1] = board[fromY][BOARD_LEFT];
8642 board[fromY][BOARD_LEFT] = EmptySquare;
8643 } else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
8644 board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
8645 && toY >= BOARD_HEIGHT-promoRank
8647 /* white pawn promotion */
8648 board[toY][toX] = CharToPiece(ToUpper(promoChar));
8649 if (board[toY][toX] == EmptySquare) {
8650 board[toY][toX] = WhiteQueen;
8652 if(gameInfo.variant==VariantBughouse ||
8653 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
8654 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
8655 board[fromY][fromX] = EmptySquare;
8656 } else if ((fromY == BOARD_HEIGHT-4)
8658 && gameInfo.variant != VariantXiangqi
8659 && gameInfo.variant != VariantBerolina
8660 && (board[fromY][fromX] == WhitePawn)
8661 && (board[toY][toX] == EmptySquare)) {
8662 board[fromY][fromX] = EmptySquare;
8663 board[toY][toX] = WhitePawn;
8664 captured = board[toY - 1][toX];
8665 board[toY - 1][toX] = EmptySquare;
8666 } else if ((fromY == BOARD_HEIGHT-4)
8668 && gameInfo.variant == VariantBerolina
8669 && (board[fromY][fromX] == WhitePawn)
8670 && (board[toY][toX] == EmptySquare)) {
8671 board[fromY][fromX] = EmptySquare;
8672 board[toY][toX] = WhitePawn;
8673 if(oldEP & EP_BEROLIN_A) {
8674 captured = board[fromY][fromX-1];
8675 board[fromY][fromX-1] = EmptySquare;
8676 }else{ captured = board[fromY][fromX+1];
8677 board[fromY][fromX+1] = EmptySquare;
8679 } else if (board[fromY][fromX] == king
8680 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8681 && toY == fromY && toX > fromX+1) {
8682 board[fromY][fromX] = EmptySquare;
8683 board[toY][toX] = king;
8684 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
8685 board[fromY][BOARD_RGHT-1] = EmptySquare;
8686 } else if (board[fromY][fromX] == king
8687 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8688 && toY == fromY && toX < fromX-1) {
8689 board[fromY][fromX] = EmptySquare;
8690 board[toY][toX] = king;
8691 board[toY][toX+1] = board[fromY][BOARD_LEFT];
8692 board[fromY][BOARD_LEFT] = EmptySquare;
8693 } else if (fromY == 7 && fromX == 3
8694 && board[fromY][fromX] == BlackKing
8695 && toY == 7 && toX == 5) {
8696 board[fromY][fromX] = EmptySquare;
8697 board[toY][toX] = BlackKing;
8698 board[fromY][7] = EmptySquare;
8699 board[toY][4] = BlackRook;
8700 } else if (fromY == 7 && fromX == 3
8701 && board[fromY][fromX] == BlackKing
8702 && toY == 7 && toX == 1) {
8703 board[fromY][fromX] = EmptySquare;
8704 board[toY][toX] = BlackKing;
8705 board[fromY][0] = EmptySquare;
8706 board[toY][2] = BlackRook;
8707 } else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
8708 board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
8711 /* black pawn promotion */
8712 board[toY][toX] = CharToPiece(ToLower(promoChar));
8713 if (board[toY][toX] == EmptySquare) {
8714 board[toY][toX] = BlackQueen;
8716 if(gameInfo.variant==VariantBughouse ||
8717 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
8718 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
8719 board[fromY][fromX] = EmptySquare;
8720 } else if ((fromY == 3)
8722 && gameInfo.variant != VariantXiangqi
8723 && gameInfo.variant != VariantBerolina
8724 && (board[fromY][fromX] == BlackPawn)
8725 && (board[toY][toX] == EmptySquare)) {
8726 board[fromY][fromX] = EmptySquare;
8727 board[toY][toX] = BlackPawn;
8728 captured = board[toY + 1][toX];
8729 board[toY + 1][toX] = EmptySquare;
8730 } else if ((fromY == 3)
8732 && gameInfo.variant == VariantBerolina
8733 && (board[fromY][fromX] == BlackPawn)
8734 && (board[toY][toX] == EmptySquare)) {
8735 board[fromY][fromX] = EmptySquare;
8736 board[toY][toX] = BlackPawn;
8737 if(oldEP & EP_BEROLIN_A) {
8738 captured = board[fromY][fromX-1];
8739 board[fromY][fromX-1] = EmptySquare;
8740 }else{ captured = board[fromY][fromX+1];
8741 board[fromY][fromX+1] = EmptySquare;
8744 board[toY][toX] = board[fromY][fromX];
8745 board[fromY][fromX] = EmptySquare;
8749 if (gameInfo.holdingsWidth != 0) {
8751 /* !!A lot more code needs to be written to support holdings */
8752 /* [HGM] OK, so I have written it. Holdings are stored in the */
8753 /* penultimate board files, so they are automaticlly stored */
8754 /* in the game history. */
8755 if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
8756 && promoChar && piece != WhitePawn && piece != BlackPawn) {
8757 /* Delete from holdings, by decreasing count */
8758 /* and erasing image if necessary */
8759 p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
8760 if(p < (int) BlackPawn) { /* white drop */
8761 p -= (int)WhitePawn;
8762 p = PieceToNumber((ChessSquare)p);
8763 if(p >= gameInfo.holdingsSize) p = 0;
8764 if(--board[p][BOARD_WIDTH-2] <= 0)
8765 board[p][BOARD_WIDTH-1] = EmptySquare;
8766 if((int)board[p][BOARD_WIDTH-2] < 0)
8767 board[p][BOARD_WIDTH-2] = 0;
8768 } else { /* black drop */
8769 p -= (int)BlackPawn;
8770 p = PieceToNumber((ChessSquare)p);
8771 if(p >= gameInfo.holdingsSize) p = 0;
8772 if(--board[BOARD_HEIGHT-1-p][1] <= 0)
8773 board[BOARD_HEIGHT-1-p][0] = EmptySquare;
8774 if((int)board[BOARD_HEIGHT-1-p][1] < 0)
8775 board[BOARD_HEIGHT-1-p][1] = 0;
8778 if (captured != EmptySquare && gameInfo.holdingsSize > 0
8779 && gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess ) {
8780 /* [HGM] holdings: Add to holdings, if holdings exist */
8781 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
8782 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
8783 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
8786 if (p >= (int) BlackPawn) {
8787 p -= (int)BlackPawn;
8788 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
8789 /* in Shogi restore piece to its original first */
8790 captured = (ChessSquare) (DEMOTED captured);
8793 p = PieceToNumber((ChessSquare)p);
8794 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
8795 board[p][BOARD_WIDTH-2]++;
8796 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
8798 p -= (int)WhitePawn;
8799 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
8800 captured = (ChessSquare) (DEMOTED captured);
8803 p = PieceToNumber((ChessSquare)p);
8804 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
8805 board[BOARD_HEIGHT-1-p][1]++;
8806 board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
8809 } else if (gameInfo.variant == VariantAtomic) {
8810 if (captured != EmptySquare) {
8812 for (y = toY-1; y <= toY+1; y++) {
8813 for (x = toX-1; x <= toX+1; x++) {
8814 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
8815 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
8816 board[y][x] = EmptySquare;
8820 board[toY][toX] = EmptySquare;
8823 if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
8824 board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
8826 if(promoChar == '+') {
8827 /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite orinary Pawn promotion) */
8828 board[toY][toX] = (ChessSquare) (PROMOTED piece);
8829 } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
8830 board[toY][toX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
8832 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
8833 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
8834 // [HGM] superchess: take promotion piece out of holdings
8835 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
8836 if((int)piece < (int)BlackPawn) { // determine stm from piece color
8837 if(!--board[k][BOARD_WIDTH-2])
8838 board[k][BOARD_WIDTH-1] = EmptySquare;
8840 if(!--board[BOARD_HEIGHT-1-k][1])
8841 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
8847 /* Updates forwardMostMove */
8849 MakeMove(fromX, fromY, toX, toY, promoChar)
8850 int fromX, fromY, toX, toY;
8853 // forwardMostMove++; // [HGM] bare: moved downstream
8855 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
8856 int timeLeft; static int lastLoadFlag=0; int king, piece;
8857 piece = boards[forwardMostMove][fromY][fromX];
8858 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
8859 if(gameInfo.variant == VariantKnightmate)
8860 king += (int) WhiteUnicorn - (int) WhiteKing;
8861 if(forwardMostMove == 0) {
8863 fprintf(serverMoves, "%s;", second.tidy);
8864 fprintf(serverMoves, "%s;", first.tidy);
8865 if(!blackPlaysFirst)
8866 fprintf(serverMoves, "%s;", second.tidy);
8867 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
8868 lastLoadFlag = loadFlag;
8870 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
8871 // print castling suffix
8872 if( toY == fromY && piece == king ) {
8874 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
8876 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
8879 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
8880 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
8881 boards[forwardMostMove][toY][toX] == EmptySquare
8882 && fromX != toX && fromY != toY)
8883 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
8885 if(promoChar != NULLCHAR)
8886 fprintf(serverMoves, ":%c:%c%c", promoChar, AAA+toX, ONE+toY);
8888 fprintf(serverMoves, "/%d/%d",
8889 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
8890 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
8891 else timeLeft = blackTimeRemaining/1000;
8892 fprintf(serverMoves, "/%d", timeLeft);
8894 fflush(serverMoves);
8897 if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations
8898 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
8902 UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
8903 if (commentList[forwardMostMove+1] != NULL) {
8904 free(commentList[forwardMostMove+1]);
8905 commentList[forwardMostMove+1] = NULL;
8907 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
8908 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
8909 // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
8910 SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
8911 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
8912 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
8913 gameInfo.result = GameUnfinished;
8914 if (gameInfo.resultDetails != NULL) {
8915 free(gameInfo.resultDetails);
8916 gameInfo.resultDetails = NULL;
8918 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
8919 moveList[forwardMostMove - 1]);
8920 (void) CoordsToAlgebraic(boards[forwardMostMove - 1],
8921 PosFlags(forwardMostMove - 1),
8922 fromY, fromX, toY, toX, promoChar,
8923 parseList[forwardMostMove - 1]);
8924 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
8930 if(gameInfo.variant != VariantShogi)
8931 strcat(parseList[forwardMostMove - 1], "+");
8935 strcat(parseList[forwardMostMove - 1], "#");
8938 if (appData.debugMode) {
8939 fprintf(debugFP, "move: %s, parse: %s (%c)\n", moveList[forwardMostMove-1], parseList[forwardMostMove-1], moveList[forwardMostMove-1][4]);
8944 /* Updates currentMove if not pausing */
8946 ShowMove(fromX, fromY, toX, toY)
8948 int instant = (gameMode == PlayFromGameFile) ?
8949 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
8950 if(appData.noGUI) return;
8951 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
8953 if (forwardMostMove == currentMove + 1) {
8954 AnimateMove(boards[forwardMostMove - 1],
8955 fromX, fromY, toX, toY);
8957 if (appData.highlightLastMove) {
8958 SetHighlights(fromX, fromY, toX, toY);
8961 currentMove = forwardMostMove;
8964 if (instant) return;
8966 DisplayMove(currentMove - 1);
8967 DrawPosition(FALSE, boards[currentMove]);
8968 DisplayBothClocks();
8969 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
8972 void SendEgtPath(ChessProgramState *cps)
8973 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
8974 char buf[MSG_SIZ], name[MSG_SIZ], *p;
8976 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
8979 char c, *q = name+1, *r, *s;
8981 name[0] = ','; // extract next format name from feature and copy with prefixed ','
8982 while(*p && *p != ',') *q++ = *p++;
8984 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
8985 strcmp(name, ",nalimov:") == 0 ) {
8986 // take nalimov path from the menu-changeable option first, if it is defined
8987 snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
8988 SendToProgram(buf,cps); // send egtbpath command for nalimov
8990 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
8991 (s = StrStr(appData.egtFormats, name)) != NULL) {
8992 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
8993 s = r = StrStr(s, ":") + 1; // beginning of path info
8994 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
8995 c = *r; *r = 0; // temporarily null-terminate path info
8996 *--q = 0; // strip of trailig ':' from name
8997 snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
8999 SendToProgram(buf,cps); // send egtbpath command for this format
9001 if(*p == ',') p++; // read away comma to position for next format name
9006 InitChessProgram(cps, setup)
9007 ChessProgramState *cps;
9008 int setup; /* [HGM] needed to setup FRC opening position */
9010 char buf[MSG_SIZ], b[MSG_SIZ]; int overruled;
9011 if (appData.noChessProgram) return;
9012 hintRequested = FALSE;
9013 bookRequested = FALSE;
9015 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
9016 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
9017 if(cps->memSize) { /* [HGM] memory */
9018 snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
9019 SendToProgram(buf, cps);
9021 SendEgtPath(cps); /* [HGM] EGT */
9022 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
9023 snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
9024 SendToProgram(buf, cps);
9027 SendToProgram(cps->initString, cps);
9028 if (gameInfo.variant != VariantNormal &&
9029 gameInfo.variant != VariantLoadable
9030 /* [HGM] also send variant if board size non-standard */
9031 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0
9033 char *v = VariantName(gameInfo.variant);
9034 if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) {
9035 /* [HGM] in protocol 1 we have to assume all variants valid */
9036 snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), v, cps->tidy);
9037 DisplayFatalError(buf, 0, 1);
9041 /* [HGM] make prefix for non-standard board size. Awkward testing... */
9042 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9043 if( gameInfo.variant == VariantXiangqi )
9044 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 0;
9045 if( gameInfo.variant == VariantShogi )
9046 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 9 || gameInfo.holdingsSize != 7;
9047 if( gameInfo.variant == VariantBughouse || gameInfo.variant == VariantCrazyhouse )
9048 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 5;
9049 if( gameInfo.variant == VariantCapablanca || gameInfo.variant == VariantCapaRandom ||
9050 gameInfo.variant == VariantGothic || gameInfo.variant == VariantFalcon || gameInfo.variant == VariantJanus )
9051 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9052 if( gameInfo.variant == VariantCourier )
9053 overruled = gameInfo.boardWidth != 12 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9054 if( gameInfo.variant == VariantSuper )
9055 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9056 if( gameInfo.variant == VariantGreat )
9057 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9058 if( gameInfo.variant == VariantSChess )
9059 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 7;
9062 snprintf(b, MSG_SIZ, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
9063 gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
9064 /* [HGM] varsize: try first if this defiant size variant is specifically known */
9065 if(StrStr(cps->variants, b) == NULL) {
9066 // specific sized variant not known, check if general sizing allowed
9067 if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best
9068 if(StrStr(cps->variants, "boardsize") == NULL) {
9069 snprintf(buf, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
9070 gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy);
9071 DisplayFatalError(buf, 0, 1);
9074 /* [HGM] here we really should compare with the maximum supported board size */
9077 } else snprintf(b, MSG_SIZ,"%s", VariantName(gameInfo.variant));
9078 snprintf(buf, MSG_SIZ, "variant %s\n", b);
9079 SendToProgram(buf, cps);
9081 currentlyInitializedVariant = gameInfo.variant;
9083 /* [HGM] send opening position in FRC to first engine */
9085 SendToProgram("force\n", cps);
9087 /* engine is now in force mode! Set flag to wake it up after first move. */
9088 setboardSpoiledMachineBlack = 1;
9092 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
9093 SendToProgram(buf, cps);
9095 cps->maybeThinking = FALSE;
9096 cps->offeredDraw = 0;
9097 if (!appData.icsActive) {
9098 SendTimeControl(cps, movesPerSession, timeControl,
9099 timeIncrement, appData.searchDepth,
9102 if (appData.showThinking
9103 // [HGM] thinking: four options require thinking output to be sent
9104 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
9106 SendToProgram("post\n", cps);
9108 SendToProgram("hard\n", cps);
9109 if (!appData.ponderNextMove) {
9110 /* Warning: "easy" is a toggle in GNU Chess, so don't send
9111 it without being sure what state we are in first. "hard"
9112 is not a toggle, so that one is OK.
9114 SendToProgram("easy\n", cps);
9117 snprintf(buf, MSG_SIZ, "ping %d\n", ++cps->lastPing);
9118 SendToProgram(buf, cps);
9120 cps->initDone = TRUE;
9125 StartChessProgram(cps)
9126 ChessProgramState *cps;
9131 if (appData.noChessProgram) return;
9132 cps->initDone = FALSE;
9134 if (strcmp(cps->host, "localhost") == 0) {
9135 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
9136 } else if (*appData.remoteShell == NULLCHAR) {
9137 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
9139 if (*appData.remoteUser == NULLCHAR) {
9140 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
9143 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
9144 cps->host, appData.remoteUser, cps->program);
9146 err = StartChildProcess(buf, "", &cps->pr);
9150 snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
9151 DisplayFatalError(buf, err, 1);
9157 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
9158 if (cps->protocolVersion > 1) {
9159 snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
9160 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
9161 cps->comboCnt = 0; // and values of combo boxes
9162 SendToProgram(buf, cps);
9164 SendToProgram("xboard\n", cps);
9170 TwoMachinesEventIfReady P((void))
9172 if (first.lastPing != first.lastPong) {
9173 DisplayMessage("", _("Waiting for first chess program"));
9174 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9177 if (second.lastPing != second.lastPong) {
9178 DisplayMessage("", _("Waiting for second chess program"));
9179 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9187 NextMatchGame P((void))
9189 int index; /* [HGM] autoinc: step load index during match */
9191 if (*appData.loadGameFile != NULLCHAR) {
9192 index = appData.loadGameIndex;
9193 if(index < 0) { // [HGM] autoinc
9194 lastIndex = index = (index == -2 && first.twoMachinesColor[0] == 'b') ? lastIndex : lastIndex+1;
9195 if(appData.rewindIndex > 0 && index > appData.rewindIndex) lastIndex = index = 1;
9197 LoadGameFromFile(appData.loadGameFile,
9199 appData.loadGameFile, FALSE);
9200 } else if (*appData.loadPositionFile != NULLCHAR) {
9201 index = appData.loadPositionIndex;
9202 if(index < 0) { // [HGM] autoinc
9203 lastIndex = index = (index == -2 && first.twoMachinesColor[0] == 'b') ? lastIndex : lastIndex+1;
9204 if(appData.rewindIndex > 0 && index > appData.rewindIndex) lastIndex = index = 1;
9206 LoadPositionFromFile(appData.loadPositionFile,
9208 appData.loadPositionFile);
9210 TwoMachinesEventIfReady();
9213 void UserAdjudicationEvent( int result )
9215 ChessMove gameResult = GameIsDrawn;
9218 gameResult = WhiteWins;
9220 else if( result < 0 ) {
9221 gameResult = BlackWins;
9224 if( gameMode == TwoMachinesPlay ) {
9225 GameEnds( gameResult, "User adjudication", GE_XBOARD );
9230 // [HGM] save: calculate checksum of game to make games easily identifiable
9231 int StringCheckSum(char *s)
9234 if(s==NULL) return 0;
9235 while(*s) i = i*259 + *s++;
9242 for(i=backwardMostMove; i<forwardMostMove; i++) {
9243 sum += pvInfoList[i].depth;
9244 sum += StringCheckSum(parseList[i]);
9245 sum += StringCheckSum(commentList[i]);
9248 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
9249 return sum + StringCheckSum(commentList[i]);
9250 } // end of save patch
9253 GameEnds(result, resultDetails, whosays)
9255 char *resultDetails;
9258 GameMode nextGameMode;
9260 char buf[MSG_SIZ], popupRequested = 0;
9262 if(endingGame) return; /* [HGM] crash: forbid recursion */
9264 if(twoBoards) { // [HGM] dual: switch back to one board
9265 twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
9266 DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
9268 if (appData.debugMode) {
9269 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
9270 result, resultDetails ? resultDetails : "(null)", whosays);
9273 fromX = fromY = -1; // [HGM] abort any move the user is entering.
9275 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
9276 /* If we are playing on ICS, the server decides when the
9277 game is over, but the engine can offer to draw, claim
9281 if (appData.zippyPlay && first.initDone) {
9282 if (result == GameIsDrawn) {
9283 /* In case draw still needs to be claimed */
9284 SendToICS(ics_prefix);
9285 SendToICS("draw\n");
9286 } else if (StrCaseStr(resultDetails, "resign")) {
9287 SendToICS(ics_prefix);
9288 SendToICS("resign\n");
9292 endingGame = 0; /* [HGM] crash */
9296 /* If we're loading the game from a file, stop */
9297 if (whosays == GE_FILE) {
9298 (void) StopLoadGameTimer();
9302 /* Cancel draw offers */
9303 first.offeredDraw = second.offeredDraw = 0;
9305 /* If this is an ICS game, only ICS can really say it's done;
9306 if not, anyone can. */
9307 isIcsGame = (gameMode == IcsPlayingWhite ||
9308 gameMode == IcsPlayingBlack ||
9309 gameMode == IcsObserving ||
9310 gameMode == IcsExamining);
9312 if (!isIcsGame || whosays == GE_ICS) {
9313 /* OK -- not an ICS game, or ICS said it was done */
9315 if (!isIcsGame && !appData.noChessProgram)
9316 SetUserThinkingEnables();
9318 /* [HGM] if a machine claims the game end we verify this claim */
9319 if(gameMode == TwoMachinesPlay && appData.testClaims) {
9320 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
9322 ChessMove trueResult = (ChessMove) -1;
9324 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
9325 first.twoMachinesColor[0] :
9326 second.twoMachinesColor[0] ;
9328 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
9329 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
9330 /* [HGM] verify: engine mate claims accepted if they were flagged */
9331 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
9333 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
9334 /* [HGM] verify: engine mate claims accepted if they were flagged */
9335 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
9337 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
9338 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
9341 // now verify win claims, but not in drop games, as we don't understand those yet
9342 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
9343 || gameInfo.variant == VariantGreat) &&
9344 (result == WhiteWins && claimer == 'w' ||
9345 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
9346 if (appData.debugMode) {
9347 fprintf(debugFP, "result=%d sp=%d move=%d\n",
9348 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
9350 if(result != trueResult) {
9351 snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
9352 result = claimer == 'w' ? BlackWins : WhiteWins;
9353 resultDetails = buf;
9356 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
9357 && (forwardMostMove <= backwardMostMove ||
9358 (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
9359 (claimer=='b')==(forwardMostMove&1))
9361 /* [HGM] verify: draws that were not flagged are false claims */
9362 snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
9363 result = claimer == 'w' ? BlackWins : WhiteWins;
9364 resultDetails = buf;
9366 /* (Claiming a loss is accepted no questions asked!) */
9368 /* [HGM] bare: don't allow bare King to win */
9369 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
9370 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
9371 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
9372 && result != GameIsDrawn)
9373 { int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
9374 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
9375 int p = (signed char)boards[forwardMostMove][i][j] - color;
9376 if(p >= 0 && p <= (int)WhiteKing) k++;
9378 if (appData.debugMode) {
9379 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
9380 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
9383 result = GameIsDrawn;
9384 snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
9385 resultDetails = buf;
9391 if(serverMoves != NULL && !loadFlag) { char c = '=';
9392 if(result==WhiteWins) c = '+';
9393 if(result==BlackWins) c = '-';
9394 if(resultDetails != NULL)
9395 fprintf(serverMoves, ";%c;%s\n", c, resultDetails);
9397 if (resultDetails != NULL) {
9398 gameInfo.result = result;
9399 gameInfo.resultDetails = StrSave(resultDetails);
9401 /* display last move only if game was not loaded from file */
9402 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
9403 DisplayMove(currentMove - 1);
9405 if (forwardMostMove != 0) {
9406 if (gameMode != PlayFromGameFile && gameMode != EditGame
9407 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
9409 if (*appData.saveGameFile != NULLCHAR) {
9410 SaveGameToFile(appData.saveGameFile, TRUE);
9411 } else if (appData.autoSaveGames) {
9414 if (*appData.savePositionFile != NULLCHAR) {
9415 SavePositionToFile(appData.savePositionFile);
9420 /* Tell program how game ended in case it is learning */
9421 /* [HGM] Moved this to after saving the PGN, just in case */
9422 /* engine died and we got here through time loss. In that */
9423 /* case we will get a fatal error writing the pipe, which */
9424 /* would otherwise lose us the PGN. */
9425 /* [HGM] crash: not needed anymore, but doesn't hurt; */
9426 /* output during GameEnds should never be fatal anymore */
9427 if (gameMode == MachinePlaysWhite ||
9428 gameMode == MachinePlaysBlack ||
9429 gameMode == TwoMachinesPlay ||
9430 gameMode == IcsPlayingWhite ||
9431 gameMode == IcsPlayingBlack ||
9432 gameMode == BeginningOfGame) {
9434 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
9436 if (first.pr != NoProc) {
9437 SendToProgram(buf, &first);
9439 if (second.pr != NoProc &&
9440 gameMode == TwoMachinesPlay) {
9441 SendToProgram(buf, &second);
9446 if (appData.icsActive) {
9447 if (appData.quietPlay &&
9448 (gameMode == IcsPlayingWhite ||
9449 gameMode == IcsPlayingBlack)) {
9450 SendToICS(ics_prefix);
9451 SendToICS("set shout 1\n");
9453 nextGameMode = IcsIdle;
9454 ics_user_moved = FALSE;
9455 /* clean up premove. It's ugly when the game has ended and the
9456 * premove highlights are still on the board.
9460 ClearPremoveHighlights();
9461 DrawPosition(FALSE, boards[currentMove]);
9463 if (whosays == GE_ICS) {
9466 if (gameMode == IcsPlayingWhite)
9468 else if(gameMode == IcsPlayingBlack)
9472 if (gameMode == IcsPlayingBlack)
9474 else if(gameMode == IcsPlayingWhite)
9481 PlayIcsUnfinishedSound();
9484 } else if (gameMode == EditGame ||
9485 gameMode == PlayFromGameFile ||
9486 gameMode == AnalyzeMode ||
9487 gameMode == AnalyzeFile) {
9488 nextGameMode = gameMode;
9490 nextGameMode = EndOfGame;
9495 nextGameMode = gameMode;
9498 if (appData.noChessProgram) {
9499 gameMode = nextGameMode;
9501 endingGame = 0; /* [HGM] crash */
9506 /* Put first chess program into idle state */
9507 if (first.pr != NoProc &&
9508 (gameMode == MachinePlaysWhite ||
9509 gameMode == MachinePlaysBlack ||
9510 gameMode == TwoMachinesPlay ||
9511 gameMode == IcsPlayingWhite ||
9512 gameMode == IcsPlayingBlack ||
9513 gameMode == BeginningOfGame)) {
9514 SendToProgram("force\n", &first);
9515 if (first.usePing) {
9517 snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
9518 SendToProgram(buf, &first);
9521 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
9522 /* Kill off first chess program */
9523 if (first.isr != NULL)
9524 RemoveInputSource(first.isr);
9527 if (first.pr != NoProc) {
9529 DoSleep( appData.delayBeforeQuit );
9530 SendToProgram("quit\n", &first);
9531 DoSleep( appData.delayAfterQuit );
9532 DestroyChildProcess(first.pr, first.useSigterm);
9537 /* Put second chess program into idle state */
9538 if (second.pr != NoProc &&
9539 gameMode == TwoMachinesPlay) {
9540 SendToProgram("force\n", &second);
9541 if (second.usePing) {
9543 snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
9544 SendToProgram(buf, &second);
9547 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
9548 /* Kill off second chess program */
9549 if (second.isr != NULL)
9550 RemoveInputSource(second.isr);
9553 if (second.pr != NoProc) {
9554 DoSleep( appData.delayBeforeQuit );
9555 SendToProgram("quit\n", &second);
9556 DoSleep( appData.delayAfterQuit );
9557 DestroyChildProcess(second.pr, second.useSigterm);
9562 if (matchMode && gameMode == TwoMachinesPlay) {
9565 if (first.twoMachinesColor[0] == 'w') {
9572 if (first.twoMachinesColor[0] == 'b') {
9581 if (matchGame < appData.matchGames) {
9583 if(appData.sameColorGames <= 1) { /* [HGM] alternate: suppress color swap */
9584 tmp = first.twoMachinesColor;
9585 first.twoMachinesColor = second.twoMachinesColor;
9586 second.twoMachinesColor = tmp;
9588 gameMode = nextGameMode;
9590 if(appData.matchPause>10000 || appData.matchPause<10)
9591 appData.matchPause = 10000; /* [HGM] make pause adjustable */
9592 ScheduleDelayedEvent(NextMatchGame, appData.matchPause);
9593 endingGame = 0; /* [HGM] crash */
9596 gameMode = nextGameMode;
9597 snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
9598 first.tidy, second.tidy,
9599 first.matchWins, second.matchWins,
9600 appData.matchGames - (first.matchWins + second.matchWins));
9601 popupRequested++; // [HGM] crash: postpone to after resetting endingGame
9602 if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
9603 first.twoMachinesColor = "black\n";
9604 second.twoMachinesColor = "white\n";
9606 first.twoMachinesColor = "white\n";
9607 second.twoMachinesColor = "black\n";
9611 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
9612 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
9614 gameMode = nextGameMode;
9616 endingGame = 0; /* [HGM] crash */
9617 if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
9618 if(matchMode == TRUE) DisplayFatalError(buf, 0, 0); else {
9619 matchMode = FALSE; appData.matchGames = matchGame = 0;
9625 /* Assumes program was just initialized (initString sent).
9626 Leaves program in force mode. */
9628 FeedMovesToProgram(cps, upto)
9629 ChessProgramState *cps;
9634 if (appData.debugMode)
9635 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
9636 startedFromSetupPosition ? "position and " : "",
9637 backwardMostMove, upto, cps->which);
9638 if(currentlyInitializedVariant != gameInfo.variant) {
9640 // [HGM] variantswitch: make engine aware of new variant
9641 if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL)
9642 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
9643 snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
9644 SendToProgram(buf, cps);
9645 currentlyInitializedVariant = gameInfo.variant;
9647 SendToProgram("force\n", cps);
9648 if (startedFromSetupPosition) {
9649 SendBoard(cps, backwardMostMove);
9650 if (appData.debugMode) {
9651 fprintf(debugFP, "feedMoves\n");
9654 for (i = backwardMostMove; i < upto; i++) {
9655 SendMoveToProgram(i, cps);
9661 ResurrectChessProgram()
9663 /* The chess program may have exited.
9664 If so, restart it and feed it all the moves made so far. */
9666 if (appData.noChessProgram || first.pr != NoProc) return;
9668 StartChessProgram(&first);
9669 InitChessProgram(&first, FALSE);
9670 FeedMovesToProgram(&first, currentMove);
9672 if (!first.sendTime) {
9673 /* can't tell gnuchess what its clock should read,
9674 so we bow to its notion. */
9676 timeRemaining[0][currentMove] = whiteTimeRemaining;
9677 timeRemaining[1][currentMove] = blackTimeRemaining;
9680 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
9681 appData.icsEngineAnalyze) && first.analysisSupport) {
9682 SendToProgram("analyze\n", &first);
9683 first.analyzing = TRUE;
9696 if (appData.debugMode) {
9697 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
9698 redraw, init, gameMode);
9700 CleanupTail(); // [HGM] vari: delete any stored variations
9701 pausing = pauseExamInvalid = FALSE;
9702 startedFromSetupPosition = blackPlaysFirst = FALSE;
9704 whiteFlag = blackFlag = FALSE;
9705 userOfferedDraw = FALSE;
9706 hintRequested = bookRequested = FALSE;
9707 first.maybeThinking = FALSE;
9708 second.maybeThinking = FALSE;
9709 first.bookSuspend = FALSE; // [HGM] book
9710 second.bookSuspend = FALSE;
9711 thinkOutput[0] = NULLCHAR;
9712 lastHint[0] = NULLCHAR;
9713 ClearGameInfo(&gameInfo);
9714 gameInfo.variant = StringToVariant(appData.variant);
9715 ics_user_moved = ics_clock_paused = FALSE;
9716 ics_getting_history = H_FALSE;
9718 white_holding[0] = black_holding[0] = NULLCHAR;
9719 ClearProgramStats();
9720 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
9724 flipView = appData.flipView;
9725 ClearPremoveHighlights();
9727 alarmSounded = FALSE;
9729 GameEnds(EndOfFile, NULL, GE_PLAYER);
9730 if(appData.serverMovesName != NULL) {
9731 /* [HGM] prepare to make moves file for broadcasting */
9732 clock_t t = clock();
9733 if(serverMoves != NULL) fclose(serverMoves);
9734 serverMoves = fopen(appData.serverMovesName, "r");
9735 if(serverMoves != NULL) {
9736 fclose(serverMoves);
9737 /* delay 15 sec before overwriting, so all clients can see end */
9738 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
9740 serverMoves = fopen(appData.serverMovesName, "w");
9744 gameMode = BeginningOfGame;
9746 if(appData.icsActive) gameInfo.variant = VariantNormal;
9747 currentMove = forwardMostMove = backwardMostMove = 0;
9748 InitPosition(redraw);
9749 for (i = 0; i < MAX_MOVES; i++) {
9750 if (commentList[i] != NULL) {
9751 free(commentList[i]);
9752 commentList[i] = NULL;
9756 timeRemaining[0][0] = whiteTimeRemaining;
9757 timeRemaining[1][0] = blackTimeRemaining;
9758 if (first.pr == NULL) {
9759 StartChessProgram(&first);
9762 InitChessProgram(&first, startedFromSetupPosition);
9765 DisplayMessage("", "");
9766 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
9767 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
9774 if (!AutoPlayOneMove())
9776 if (matchMode || appData.timeDelay == 0)
9778 if (appData.timeDelay < 0)
9780 StartLoadGameTimer((long)(1000.0 * appData.timeDelay));
9789 int fromX, fromY, toX, toY;
9791 if (appData.debugMode) {
9792 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
9795 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
9798 if (gameMode == AnalyzeFile && currentMove > backwardMostMove) {
9799 pvInfoList[currentMove].depth = programStats.depth;
9800 pvInfoList[currentMove].score = programStats.score;
9801 pvInfoList[currentMove].time = 0;
9802 if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
9805 if (currentMove >= forwardMostMove) {
9806 if(gameMode == AnalyzeFile) { ExitAnalyzeMode(); SendToProgram("force\n", &first); }
9807 gameMode = EditGame;
9810 /* [AS] Clear current move marker at the end of a game */
9811 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
9816 toX = moveList[currentMove][2] - AAA;
9817 toY = moveList[currentMove][3] - ONE;
9819 if (moveList[currentMove][1] == '@') {
9820 if (appData.highlightLastMove) {
9821 SetHighlights(-1, -1, toX, toY);
9824 fromX = moveList[currentMove][0] - AAA;
9825 fromY = moveList[currentMove][1] - ONE;
9827 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
9829 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
9831 if (appData.highlightLastMove) {
9832 SetHighlights(fromX, fromY, toX, toY);
9835 DisplayMove(currentMove);
9836 SendMoveToProgram(currentMove++, &first);
9837 DisplayBothClocks();
9838 DrawPosition(FALSE, boards[currentMove]);
9839 // [HGM] PV info: always display, routine tests if empty
9840 DisplayComment(currentMove - 1, commentList[currentMove]);
9846 LoadGameOneMove(readAhead)
9847 ChessMove readAhead;
9849 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
9850 char promoChar = NULLCHAR;
9855 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
9856 gameMode != AnalyzeMode && gameMode != Training) {
9861 yyboardindex = forwardMostMove;
9862 if (readAhead != EndOfFile) {
9863 moveType = readAhead;
9865 if (gameFileFP == NULL)
9867 moveType = (ChessMove) Myylex();
9873 if (appData.debugMode)
9874 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
9877 /* append the comment but don't display it */
9878 AppendComment(currentMove, p, FALSE);
9881 case WhiteCapturesEnPassant:
9882 case BlackCapturesEnPassant:
9883 case WhitePromotion:
9884 case BlackPromotion:
9885 case WhiteNonPromotion:
9886 case BlackNonPromotion:
9888 case WhiteKingSideCastle:
9889 case WhiteQueenSideCastle:
9890 case BlackKingSideCastle:
9891 case BlackQueenSideCastle:
9892 case WhiteKingSideCastleWild:
9893 case WhiteQueenSideCastleWild:
9894 case BlackKingSideCastleWild:
9895 case BlackQueenSideCastleWild:
9897 case WhiteHSideCastleFR:
9898 case WhiteASideCastleFR:
9899 case BlackHSideCastleFR:
9900 case BlackASideCastleFR:
9902 if (appData.debugMode)
9903 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
9904 fromX = currentMoveString[0] - AAA;
9905 fromY = currentMoveString[1] - ONE;
9906 toX = currentMoveString[2] - AAA;
9907 toY = currentMoveString[3] - ONE;
9908 promoChar = currentMoveString[4];
9913 if (appData.debugMode)
9914 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
9915 fromX = moveType == WhiteDrop ?
9916 (int) CharToPiece(ToUpper(currentMoveString[0])) :
9917 (int) CharToPiece(ToLower(currentMoveString[0]));
9919 toX = currentMoveString[2] - AAA;
9920 toY = currentMoveString[3] - ONE;
9926 case GameUnfinished:
9927 if (appData.debugMode)
9928 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
9929 p = strchr(yy_text, '{');
9930 if (p == NULL) p = strchr(yy_text, '(');
9933 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
9935 q = strchr(p, *p == '{' ? '}' : ')');
9936 if (q != NULL) *q = NULLCHAR;
9939 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
9940 GameEnds(moveType, p, GE_FILE);
9942 if (cmailMsgLoaded) {
9944 flipView = WhiteOnMove(currentMove);
9945 if (moveType == GameUnfinished) flipView = !flipView;
9946 if (appData.debugMode)
9947 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
9952 if (appData.debugMode)
9953 fprintf(debugFP, "Parser hit end of file\n");
9954 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
9960 if (WhiteOnMove(currentMove)) {
9961 GameEnds(BlackWins, "Black mates", GE_FILE);
9963 GameEnds(WhiteWins, "White mates", GE_FILE);
9967 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
9974 if (lastLoadGameStart == GNUChessGame) {
9975 /* GNUChessGames have numbers, but they aren't move numbers */
9976 if (appData.debugMode)
9977 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
9978 yy_text, (int) moveType);
9979 return LoadGameOneMove(EndOfFile); /* tail recursion */
9981 /* else fall thru */
9986 /* Reached start of next game in file */
9987 if (appData.debugMode)
9988 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
9989 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
9995 if (WhiteOnMove(currentMove)) {
9996 GameEnds(BlackWins, "Black mates", GE_FILE);
9998 GameEnds(WhiteWins, "White mates", GE_FILE);
10002 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
10008 case PositionDiagram: /* should not happen; ignore */
10009 case ElapsedTime: /* ignore */
10010 case NAG: /* ignore */
10011 if (appData.debugMode)
10012 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
10013 yy_text, (int) moveType);
10014 return LoadGameOneMove(EndOfFile); /* tail recursion */
10017 if (appData.testLegality) {
10018 if (appData.debugMode)
10019 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
10020 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
10021 (forwardMostMove / 2) + 1,
10022 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10023 DisplayError(move, 0);
10026 if (appData.debugMode)
10027 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
10028 yy_text, currentMoveString);
10029 fromX = currentMoveString[0] - AAA;
10030 fromY = currentMoveString[1] - ONE;
10031 toX = currentMoveString[2] - AAA;
10032 toY = currentMoveString[3] - ONE;
10033 promoChar = currentMoveString[4];
10037 case AmbiguousMove:
10038 if (appData.debugMode)
10039 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
10040 snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
10041 (forwardMostMove / 2) + 1,
10042 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10043 DisplayError(move, 0);
10048 case ImpossibleMove:
10049 if (appData.debugMode)
10050 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
10051 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
10052 (forwardMostMove / 2) + 1,
10053 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10054 DisplayError(move, 0);
10060 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
10061 DrawPosition(FALSE, boards[currentMove]);
10062 DisplayBothClocks();
10063 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
10064 DisplayComment(currentMove - 1, commentList[currentMove]);
10066 (void) StopLoadGameTimer();
10068 cmailOldMove = forwardMostMove;
10071 /* currentMoveString is set as a side-effect of yylex */
10073 thinkOutput[0] = NULLCHAR;
10074 MakeMove(fromX, fromY, toX, toY, promoChar);
10075 currentMove = forwardMostMove;
10080 /* Load the nth game from the given file */
10082 LoadGameFromFile(filename, n, title, useList)
10086 /*Boolean*/ int useList;
10091 if (strcmp(filename, "-") == 0) {
10095 f = fopen(filename, "rb");
10097 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10098 DisplayError(buf, errno);
10102 if (fseek(f, 0, 0) == -1) {
10103 /* f is not seekable; probably a pipe */
10106 if (useList && n == 0) {
10107 int error = GameListBuild(f);
10109 DisplayError(_("Cannot build game list"), error);
10110 } else if (!ListEmpty(&gameList) &&
10111 ((ListGame *) gameList.tailPred)->number > 1) {
10112 GameListPopUp(f, title);
10119 return LoadGame(f, n, title, FALSE);
10124 MakeRegisteredMove()
10126 int fromX, fromY, toX, toY;
10128 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
10129 switch (cmailMoveType[lastLoadGameNumber - 1]) {
10132 if (appData.debugMode)
10133 fprintf(debugFP, "Restoring %s for game %d\n",
10134 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
10136 thinkOutput[0] = NULLCHAR;
10137 safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
10138 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
10139 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
10140 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
10141 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
10142 promoChar = cmailMove[lastLoadGameNumber - 1][4];
10143 MakeMove(fromX, fromY, toX, toY, promoChar);
10144 ShowMove(fromX, fromY, toX, toY);
10146 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
10153 if (WhiteOnMove(currentMove)) {
10154 GameEnds(BlackWins, "Black mates", GE_PLAYER);
10156 GameEnds(WhiteWins, "White mates", GE_PLAYER);
10161 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
10168 if (WhiteOnMove(currentMove)) {
10169 GameEnds(BlackWins, "White resigns", GE_PLAYER);
10171 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
10176 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
10187 /* Wrapper around LoadGame for use when a Cmail message is loaded */
10189 CmailLoadGame(f, gameNumber, title, useList)
10197 if (gameNumber > nCmailGames) {
10198 DisplayError(_("No more games in this message"), 0);
10201 if (f == lastLoadGameFP) {
10202 int offset = gameNumber - lastLoadGameNumber;
10204 cmailMsg[0] = NULLCHAR;
10205 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
10206 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
10207 nCmailMovesRegistered--;
10209 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
10210 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
10211 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
10214 if (! RegisterMove()) return FALSE;
10218 retVal = LoadGame(f, gameNumber, title, useList);
10220 /* Make move registered during previous look at this game, if any */
10221 MakeRegisteredMove();
10223 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
10224 commentList[currentMove]
10225 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
10226 DisplayComment(currentMove - 1, commentList[currentMove]);
10232 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
10237 int gameNumber = lastLoadGameNumber + offset;
10238 if (lastLoadGameFP == NULL) {
10239 DisplayError(_("No game has been loaded yet"), 0);
10242 if (gameNumber <= 0) {
10243 DisplayError(_("Can't back up any further"), 0);
10246 if (cmailMsgLoaded) {
10247 return CmailLoadGame(lastLoadGameFP, gameNumber,
10248 lastLoadGameTitle, lastLoadGameUseList);
10250 return LoadGame(lastLoadGameFP, gameNumber,
10251 lastLoadGameTitle, lastLoadGameUseList);
10257 /* Load the nth game from open file f */
10259 LoadGame(f, gameNumber, title, useList)
10267 int gn = gameNumber;
10268 ListGame *lg = NULL;
10269 int numPGNTags = 0;
10271 GameMode oldGameMode;
10272 VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
10274 if (appData.debugMode)
10275 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
10277 if (gameMode == Training )
10278 SetTrainingModeOff();
10280 oldGameMode = gameMode;
10281 if (gameMode != BeginningOfGame) {
10282 Reset(FALSE, TRUE);
10286 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
10287 fclose(lastLoadGameFP);
10291 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
10294 fseek(f, lg->offset, 0);
10295 GameListHighlight(gameNumber);
10299 DisplayError(_("Game number out of range"), 0);
10304 if (fseek(f, 0, 0) == -1) {
10305 if (f == lastLoadGameFP ?
10306 gameNumber == lastLoadGameNumber + 1 :
10310 DisplayError(_("Can't seek on game file"), 0);
10315 lastLoadGameFP = f;
10316 lastLoadGameNumber = gameNumber;
10317 safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
10318 lastLoadGameUseList = useList;
10322 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
10323 snprintf(buf, sizeof(buf), "%s vs. %s", lg->gameInfo.white,
10324 lg->gameInfo.black);
10326 } else if (*title != NULLCHAR) {
10327 if (gameNumber > 1) {
10328 snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
10331 DisplayTitle(title);
10335 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
10336 gameMode = PlayFromGameFile;
10340 currentMove = forwardMostMove = backwardMostMove = 0;
10341 CopyBoard(boards[0], initialPosition);
10345 * Skip the first gn-1 games in the file.
10346 * Also skip over anything that precedes an identifiable
10347 * start of game marker, to avoid being confused by
10348 * garbage at the start of the file. Currently
10349 * recognized start of game markers are the move number "1",
10350 * the pattern "gnuchess .* game", the pattern
10351 * "^[#;%] [^ ]* game file", and a PGN tag block.
10352 * A game that starts with one of the latter two patterns
10353 * will also have a move number 1, possibly
10354 * following a position diagram.
10355 * 5-4-02: Let's try being more lenient and allowing a game to
10356 * start with an unnumbered move. Does that break anything?
10358 cm = lastLoadGameStart = EndOfFile;
10360 yyboardindex = forwardMostMove;
10361 cm = (ChessMove) Myylex();
10364 if (cmailMsgLoaded) {
10365 nCmailGames = CMAIL_MAX_GAMES - gn;
10368 DisplayError(_("Game not found in file"), 0);
10375 lastLoadGameStart = cm;
10378 case MoveNumberOne:
10379 switch (lastLoadGameStart) {
10384 case MoveNumberOne:
10386 gn--; /* count this game */
10387 lastLoadGameStart = cm;
10396 switch (lastLoadGameStart) {
10399 case MoveNumberOne:
10401 gn--; /* count this game */
10402 lastLoadGameStart = cm;
10405 lastLoadGameStart = cm; /* game counted already */
10413 yyboardindex = forwardMostMove;
10414 cm = (ChessMove) Myylex();
10415 } while (cm == PGNTag || cm == Comment);
10422 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
10423 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
10424 != CMAIL_OLD_RESULT) {
10426 cmailResult[ CMAIL_MAX_GAMES
10427 - gn - 1] = CMAIL_OLD_RESULT;
10433 /* Only a NormalMove can be at the start of a game
10434 * without a position diagram. */
10435 if (lastLoadGameStart == EndOfFile ) {
10437 lastLoadGameStart = MoveNumberOne;
10446 if (appData.debugMode)
10447 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
10449 if (cm == XBoardGame) {
10450 /* Skip any header junk before position diagram and/or move 1 */
10452 yyboardindex = forwardMostMove;
10453 cm = (ChessMove) Myylex();
10455 if (cm == EndOfFile ||
10456 cm == GNUChessGame || cm == XBoardGame) {
10457 /* Empty game; pretend end-of-file and handle later */
10462 if (cm == MoveNumberOne || cm == PositionDiagram ||
10463 cm == PGNTag || cm == Comment)
10466 } else if (cm == GNUChessGame) {
10467 if (gameInfo.event != NULL) {
10468 free(gameInfo.event);
10470 gameInfo.event = StrSave(yy_text);
10473 startedFromSetupPosition = FALSE;
10474 while (cm == PGNTag) {
10475 if (appData.debugMode)
10476 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
10477 err = ParsePGNTag(yy_text, &gameInfo);
10478 if (!err) numPGNTags++;
10480 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
10481 if(gameInfo.variant != oldVariant) {
10482 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
10483 ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
10484 InitPosition(TRUE);
10485 oldVariant = gameInfo.variant;
10486 if (appData.debugMode)
10487 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
10491 if (gameInfo.fen != NULL) {
10492 Board initial_position;
10493 startedFromSetupPosition = TRUE;
10494 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
10496 DisplayError(_("Bad FEN position in file"), 0);
10499 CopyBoard(boards[0], initial_position);
10500 if (blackPlaysFirst) {
10501 currentMove = forwardMostMove = backwardMostMove = 1;
10502 CopyBoard(boards[1], initial_position);
10503 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10504 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10505 timeRemaining[0][1] = whiteTimeRemaining;
10506 timeRemaining[1][1] = blackTimeRemaining;
10507 if (commentList[0] != NULL) {
10508 commentList[1] = commentList[0];
10509 commentList[0] = NULL;
10512 currentMove = forwardMostMove = backwardMostMove = 0;
10514 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
10516 initialRulePlies = FENrulePlies;
10517 for( i=0; i< nrCastlingRights; i++ )
10518 initialRights[i] = initial_position[CASTLING][i];
10520 yyboardindex = forwardMostMove;
10521 free(gameInfo.fen);
10522 gameInfo.fen = NULL;
10525 yyboardindex = forwardMostMove;
10526 cm = (ChessMove) Myylex();
10528 /* Handle comments interspersed among the tags */
10529 while (cm == Comment) {
10531 if (appData.debugMode)
10532 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10534 AppendComment(currentMove, p, FALSE);
10535 yyboardindex = forwardMostMove;
10536 cm = (ChessMove) Myylex();
10540 /* don't rely on existence of Event tag since if game was
10541 * pasted from clipboard the Event tag may not exist
10543 if (numPGNTags > 0){
10545 if (gameInfo.variant == VariantNormal) {
10546 VariantClass v = StringToVariant(gameInfo.event);
10547 // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
10548 if(v < VariantShogi) gameInfo.variant = v;
10551 if( appData.autoDisplayTags ) {
10552 tags = PGNTags(&gameInfo);
10553 TagsPopUp(tags, CmailMsg());
10558 /* Make something up, but don't display it now */
10563 if (cm == PositionDiagram) {
10566 Board initial_position;
10568 if (appData.debugMode)
10569 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
10571 if (!startedFromSetupPosition) {
10573 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
10574 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
10585 initial_position[i][j++] = CharToPiece(*p);
10588 while (*p == ' ' || *p == '\t' ||
10589 *p == '\n' || *p == '\r') p++;
10591 if (strncmp(p, "black", strlen("black"))==0)
10592 blackPlaysFirst = TRUE;
10594 blackPlaysFirst = FALSE;
10595 startedFromSetupPosition = TRUE;
10597 CopyBoard(boards[0], initial_position);
10598 if (blackPlaysFirst) {
10599 currentMove = forwardMostMove = backwardMostMove = 1;
10600 CopyBoard(boards[1], initial_position);
10601 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10602 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10603 timeRemaining[0][1] = whiteTimeRemaining;
10604 timeRemaining[1][1] = blackTimeRemaining;
10605 if (commentList[0] != NULL) {
10606 commentList[1] = commentList[0];
10607 commentList[0] = NULL;
10610 currentMove = forwardMostMove = backwardMostMove = 0;
10613 yyboardindex = forwardMostMove;
10614 cm = (ChessMove) Myylex();
10617 if (first.pr == NoProc) {
10618 StartChessProgram(&first);
10620 InitChessProgram(&first, FALSE);
10621 SendToProgram("force\n", &first);
10622 if (startedFromSetupPosition) {
10623 SendBoard(&first, forwardMostMove);
10624 if (appData.debugMode) {
10625 fprintf(debugFP, "Load Game\n");
10627 DisplayBothClocks();
10630 /* [HGM] server: flag to write setup moves in broadcast file as one */
10631 loadFlag = appData.suppressLoadMoves;
10633 while (cm == Comment) {
10635 if (appData.debugMode)
10636 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10638 AppendComment(currentMove, p, FALSE);
10639 yyboardindex = forwardMostMove;
10640 cm = (ChessMove) Myylex();
10643 if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
10644 cm == WhiteWins || cm == BlackWins ||
10645 cm == GameIsDrawn || cm == GameUnfinished) {
10646 DisplayMessage("", _("No moves in game"));
10647 if (cmailMsgLoaded) {
10648 if (appData.debugMode)
10649 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
10653 DrawPosition(FALSE, boards[currentMove]);
10654 DisplayBothClocks();
10655 gameMode = EditGame;
10662 // [HGM] PV info: routine tests if comment empty
10663 if (!matchMode && (pausing || appData.timeDelay != 0)) {
10664 DisplayComment(currentMove - 1, commentList[currentMove]);
10666 if (!matchMode && appData.timeDelay != 0)
10667 DrawPosition(FALSE, boards[currentMove]);
10669 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
10670 programStats.ok_to_send = 1;
10673 /* if the first token after the PGN tags is a move
10674 * and not move number 1, retrieve it from the parser
10676 if (cm != MoveNumberOne)
10677 LoadGameOneMove(cm);
10679 /* load the remaining moves from the file */
10680 while (LoadGameOneMove(EndOfFile)) {
10681 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
10682 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
10685 /* rewind to the start of the game */
10686 currentMove = backwardMostMove;
10688 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
10690 if (oldGameMode == AnalyzeFile ||
10691 oldGameMode == AnalyzeMode) {
10692 AnalyzeFileEvent();
10695 if (matchMode || appData.timeDelay == 0) {
10697 gameMode = EditGame;
10699 } else if (appData.timeDelay > 0) {
10700 AutoPlayGameLoop();
10703 if (appData.debugMode)
10704 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
10706 loadFlag = 0; /* [HGM] true game starts */
10710 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
10712 ReloadPosition(offset)
10715 int positionNumber = lastLoadPositionNumber + offset;
10716 if (lastLoadPositionFP == NULL) {
10717 DisplayError(_("No position has been loaded yet"), 0);
10720 if (positionNumber <= 0) {
10721 DisplayError(_("Can't back up any further"), 0);
10724 return LoadPosition(lastLoadPositionFP, positionNumber,
10725 lastLoadPositionTitle);
10728 /* Load the nth position from the given file */
10730 LoadPositionFromFile(filename, n, title)
10738 if (strcmp(filename, "-") == 0) {
10739 return LoadPosition(stdin, n, "stdin");
10741 f = fopen(filename, "rb");
10743 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10744 DisplayError(buf, errno);
10747 return LoadPosition(f, n, title);
10752 /* Load the nth position from the given open file, and close it */
10754 LoadPosition(f, positionNumber, title)
10756 int positionNumber;
10759 char *p, line[MSG_SIZ];
10760 Board initial_position;
10761 int i, j, fenMode, pn;
10763 if (gameMode == Training )
10764 SetTrainingModeOff();
10766 if (gameMode != BeginningOfGame) {
10767 Reset(FALSE, TRUE);
10769 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
10770 fclose(lastLoadPositionFP);
10772 if (positionNumber == 0) positionNumber = 1;
10773 lastLoadPositionFP = f;
10774 lastLoadPositionNumber = positionNumber;
10775 safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
10776 if (first.pr == NoProc) {
10777 StartChessProgram(&first);
10778 InitChessProgram(&first, FALSE);
10780 pn = positionNumber;
10781 if (positionNumber < 0) {
10782 /* Negative position number means to seek to that byte offset */
10783 if (fseek(f, -positionNumber, 0) == -1) {
10784 DisplayError(_("Can't seek on position file"), 0);
10789 if (fseek(f, 0, 0) == -1) {
10790 if (f == lastLoadPositionFP ?
10791 positionNumber == lastLoadPositionNumber + 1 :
10792 positionNumber == 1) {
10795 DisplayError(_("Can't seek on position file"), 0);
10800 /* See if this file is FEN or old-style xboard */
10801 if (fgets(line, MSG_SIZ, f) == NULL) {
10802 DisplayError(_("Position not found in file"), 0);
10805 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
10806 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
10809 if (fenMode || line[0] == '#') pn--;
10811 /* skip positions before number pn */
10812 if (fgets(line, MSG_SIZ, f) == NULL) {
10814 DisplayError(_("Position not found in file"), 0);
10817 if (fenMode || line[0] == '#') pn--;
10822 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
10823 DisplayError(_("Bad FEN position in file"), 0);
10827 (void) fgets(line, MSG_SIZ, f);
10828 (void) fgets(line, MSG_SIZ, f);
10830 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
10831 (void) fgets(line, MSG_SIZ, f);
10832 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
10835 initial_position[i][j++] = CharToPiece(*p);
10839 blackPlaysFirst = FALSE;
10841 (void) fgets(line, MSG_SIZ, f);
10842 if (strncmp(line, "black", strlen("black"))==0)
10843 blackPlaysFirst = TRUE;
10846 startedFromSetupPosition = TRUE;
10848 SendToProgram("force\n", &first);
10849 CopyBoard(boards[0], initial_position);
10850 if (blackPlaysFirst) {
10851 currentMove = forwardMostMove = backwardMostMove = 1;
10852 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10853 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10854 CopyBoard(boards[1], initial_position);
10855 DisplayMessage("", _("Black to play"));
10857 currentMove = forwardMostMove = backwardMostMove = 0;
10858 DisplayMessage("", _("White to play"));
10860 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
10861 SendBoard(&first, forwardMostMove);
10862 if (appData.debugMode) {
10864 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
10865 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
10866 fprintf(debugFP, "Load Position\n");
10869 if (positionNumber > 1) {
10870 snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
10871 DisplayTitle(line);
10873 DisplayTitle(title);
10875 gameMode = EditGame;
10878 timeRemaining[0][1] = whiteTimeRemaining;
10879 timeRemaining[1][1] = blackTimeRemaining;
10880 DrawPosition(FALSE, boards[currentMove]);
10887 CopyPlayerNameIntoFileName(dest, src)
10890 while (*src != NULLCHAR && *src != ',') {
10895 *(*dest)++ = *src++;
10900 char *DefaultFileName(ext)
10903 static char def[MSG_SIZ];
10906 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
10908 CopyPlayerNameIntoFileName(&p, gameInfo.white);
10910 CopyPlayerNameIntoFileName(&p, gameInfo.black);
10912 safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
10919 /* Save the current game to the given file */
10921 SaveGameToFile(filename, append)
10928 if (strcmp(filename, "-") == 0) {
10929 return SaveGame(stdout, 0, NULL);
10931 f = fopen(filename, append ? "a" : "w");
10933 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10934 DisplayError(buf, errno);
10937 return SaveGame(f, 0, NULL);
10946 static char buf[MSG_SIZ];
10949 p = strchr(str, ' ');
10950 if (p == NULL) return str;
10951 strncpy(buf, str, p - str);
10952 buf[p - str] = NULLCHAR;
10956 #define PGN_MAX_LINE 75
10958 #define PGN_SIDE_WHITE 0
10959 #define PGN_SIDE_BLACK 1
10962 static int FindFirstMoveOutOfBook( int side )
10966 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
10967 int index = backwardMostMove;
10968 int has_book_hit = 0;
10970 if( (index % 2) != side ) {
10974 while( index < forwardMostMove ) {
10975 /* Check to see if engine is in book */
10976 int depth = pvInfoList[index].depth;
10977 int score = pvInfoList[index].score;
10983 else if( score == 0 && depth == 63 ) {
10984 in_book = 1; /* Zappa */
10986 else if( score == 2 && depth == 99 ) {
10987 in_book = 1; /* Abrok */
10990 has_book_hit += in_book;
11006 void GetOutOfBookInfo( char * buf )
11010 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
11012 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
11013 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
11017 if( oob[0] >= 0 || oob[1] >= 0 ) {
11018 for( i=0; i<2; i++ ) {
11022 if( i > 0 && oob[0] >= 0 ) {
11023 strcat( buf, " " );
11026 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
11027 sprintf( buf+strlen(buf), "%s%.2f",
11028 pvInfoList[idx].score >= 0 ? "+" : "",
11029 pvInfoList[idx].score / 100.0 );
11035 /* Save game in PGN style and close the file */
11040 int i, offset, linelen, newblock;
11044 int movelen, numlen, blank;
11045 char move_buffer[100]; /* [AS] Buffer for move+PV info */
11047 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
11049 tm = time((time_t *) NULL);
11051 PrintPGNTags(f, &gameInfo);
11053 if (backwardMostMove > 0 || startedFromSetupPosition) {
11054 char *fen = PositionToFEN(backwardMostMove, NULL);
11055 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
11056 fprintf(f, "\n{--------------\n");
11057 PrintPosition(f, backwardMostMove);
11058 fprintf(f, "--------------}\n");
11062 /* [AS] Out of book annotation */
11063 if( appData.saveOutOfBookInfo ) {
11066 GetOutOfBookInfo( buf );
11068 if( buf[0] != '\0' ) {
11069 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
11076 i = backwardMostMove;
11080 while (i < forwardMostMove) {
11081 /* Print comments preceding this move */
11082 if (commentList[i] != NULL) {
11083 if (linelen > 0) fprintf(f, "\n");
11084 fprintf(f, "%s", commentList[i]);
11089 /* Format move number */
11091 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
11094 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
11096 numtext[0] = NULLCHAR;
11098 numlen = strlen(numtext);
11101 /* Print move number */
11102 blank = linelen > 0 && numlen > 0;
11103 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
11112 fprintf(f, "%s", numtext);
11116 safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
11117 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
11120 blank = linelen > 0 && movelen > 0;
11121 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
11130 fprintf(f, "%s", move_buffer);
11131 linelen += movelen;
11133 /* [AS] Add PV info if present */
11134 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
11135 /* [HGM] add time */
11136 char buf[MSG_SIZ]; int seconds;
11138 seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
11144 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
11147 seconds = (seconds + 4)/10; // round to full seconds
11149 snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
11151 snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
11154 snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
11155 pvInfoList[i].score >= 0 ? "+" : "",
11156 pvInfoList[i].score / 100.0,
11157 pvInfoList[i].depth,
11160 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
11162 /* Print score/depth */
11163 blank = linelen > 0 && movelen > 0;
11164 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
11173 fprintf(f, "%s", move_buffer);
11174 linelen += movelen;
11180 /* Start a new line */
11181 if (linelen > 0) fprintf(f, "\n");
11183 /* Print comments after last move */
11184 if (commentList[i] != NULL) {
11185 fprintf(f, "%s\n", commentList[i]);
11189 if (gameInfo.resultDetails != NULL &&
11190 gameInfo.resultDetails[0] != NULLCHAR) {
11191 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
11192 PGNResult(gameInfo.result));
11194 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
11198 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
11202 /* Save game in old style and close the file */
11204 SaveGameOldStyle(f)
11210 tm = time((time_t *) NULL);
11212 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
11215 if (backwardMostMove > 0 || startedFromSetupPosition) {
11216 fprintf(f, "\n[--------------\n");
11217 PrintPosition(f, backwardMostMove);
11218 fprintf(f, "--------------]\n");
11223 i = backwardMostMove;
11224 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
11226 while (i < forwardMostMove) {
11227 if (commentList[i] != NULL) {
11228 fprintf(f, "[%s]\n", commentList[i]);
11231 if ((i % 2) == 1) {
11232 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
11235 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
11237 if (commentList[i] != NULL) {
11241 if (i >= forwardMostMove) {
11245 fprintf(f, "%s\n", parseList[i]);
11250 if (commentList[i] != NULL) {
11251 fprintf(f, "[%s]\n", commentList[i]);
11254 /* This isn't really the old style, but it's close enough */
11255 if (gameInfo.resultDetails != NULL &&
11256 gameInfo.resultDetails[0] != NULLCHAR) {
11257 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
11258 gameInfo.resultDetails);
11260 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
11267 /* Save the current game to open file f and close the file */
11269 SaveGame(f, dummy, dummy2)
11274 if (gameMode == EditPosition) EditPositionDone(TRUE);
11275 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
11276 if (appData.oldSaveStyle)
11277 return SaveGameOldStyle(f);
11279 return SaveGamePGN(f);
11282 /* Save the current position to the given file */
11284 SavePositionToFile(filename)
11290 if (strcmp(filename, "-") == 0) {
11291 return SavePosition(stdout, 0, NULL);
11293 f = fopen(filename, "a");
11295 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
11296 DisplayError(buf, errno);
11299 SavePosition(f, 0, NULL);
11305 /* Save the current position to the given open file and close the file */
11307 SavePosition(f, dummy, dummy2)
11315 if (gameMode == EditPosition) EditPositionDone(TRUE);
11316 if (appData.oldSaveStyle) {
11317 tm = time((time_t *) NULL);
11319 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
11321 fprintf(f, "[--------------\n");
11322 PrintPosition(f, currentMove);
11323 fprintf(f, "--------------]\n");
11325 fen = PositionToFEN(currentMove, NULL);
11326 fprintf(f, "%s\n", fen);
11334 ReloadCmailMsgEvent(unregister)
11338 static char *inFilename = NULL;
11339 static char *outFilename;
11341 struct stat inbuf, outbuf;
11344 /* Any registered moves are unregistered if unregister is set, */
11345 /* i.e. invoked by the signal handler */
11347 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
11348 cmailMoveRegistered[i] = FALSE;
11349 if (cmailCommentList[i] != NULL) {
11350 free(cmailCommentList[i]);
11351 cmailCommentList[i] = NULL;
11354 nCmailMovesRegistered = 0;
11357 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
11358 cmailResult[i] = CMAIL_NOT_RESULT;
11362 if (inFilename == NULL) {
11363 /* Because the filenames are static they only get malloced once */
11364 /* and they never get freed */
11365 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
11366 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
11368 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
11369 sprintf(outFilename, "%s.out", appData.cmailGameName);
11372 status = stat(outFilename, &outbuf);
11374 cmailMailedMove = FALSE;
11376 status = stat(inFilename, &inbuf);
11377 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
11380 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
11381 counts the games, notes how each one terminated, etc.
11383 It would be nice to remove this kludge and instead gather all
11384 the information while building the game list. (And to keep it
11385 in the game list nodes instead of having a bunch of fixed-size
11386 parallel arrays.) Note this will require getting each game's
11387 termination from the PGN tags, as the game list builder does
11388 not process the game moves. --mann
11390 cmailMsgLoaded = TRUE;
11391 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
11393 /* Load first game in the file or popup game menu */
11394 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
11396 #endif /* !WIN32 */
11404 char string[MSG_SIZ];
11406 if ( cmailMailedMove
11407 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
11408 return TRUE; /* Allow free viewing */
11411 /* Unregister move to ensure that we don't leave RegisterMove */
11412 /* with the move registered when the conditions for registering no */
11414 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11415 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
11416 nCmailMovesRegistered --;
11418 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
11420 free(cmailCommentList[lastLoadGameNumber - 1]);
11421 cmailCommentList[lastLoadGameNumber - 1] = NULL;
11425 if (cmailOldMove == -1) {
11426 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
11430 if (currentMove > cmailOldMove + 1) {
11431 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
11435 if (currentMove < cmailOldMove) {
11436 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
11440 if (forwardMostMove > currentMove) {
11441 /* Silently truncate extra moves */
11445 if ( (currentMove == cmailOldMove + 1)
11446 || ( (currentMove == cmailOldMove)
11447 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
11448 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
11449 if (gameInfo.result != GameUnfinished) {
11450 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
11453 if (commentList[currentMove] != NULL) {
11454 cmailCommentList[lastLoadGameNumber - 1]
11455 = StrSave(commentList[currentMove]);
11457 safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
11459 if (appData.debugMode)
11460 fprintf(debugFP, "Saving %s for game %d\n",
11461 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
11463 snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
11465 f = fopen(string, "w");
11466 if (appData.oldSaveStyle) {
11467 SaveGameOldStyle(f); /* also closes the file */
11469 snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
11470 f = fopen(string, "w");
11471 SavePosition(f, 0, NULL); /* also closes the file */
11473 fprintf(f, "{--------------\n");
11474 PrintPosition(f, currentMove);
11475 fprintf(f, "--------------}\n\n");
11477 SaveGame(f, 0, NULL); /* also closes the file*/
11480 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
11481 nCmailMovesRegistered ++;
11482 } else if (nCmailGames == 1) {
11483 DisplayError(_("You have not made a move yet"), 0);
11494 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
11495 FILE *commandOutput;
11496 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
11497 int nBytes = 0; /* Suppress warnings on uninitialized variables */
11503 if (! cmailMsgLoaded) {
11504 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
11508 if (nCmailGames == nCmailResults) {
11509 DisplayError(_("No unfinished games"), 0);
11513 #if CMAIL_PROHIBIT_REMAIL
11514 if (cmailMailedMove) {
11515 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);
11516 DisplayError(msg, 0);
11521 if (! (cmailMailedMove || RegisterMove())) return;
11523 if ( cmailMailedMove
11524 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
11525 snprintf(string, MSG_SIZ, partCommandString,
11526 appData.debugMode ? " -v" : "", appData.cmailGameName);
11527 commandOutput = popen(string, "r");
11529 if (commandOutput == NULL) {
11530 DisplayError(_("Failed to invoke cmail"), 0);
11532 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
11533 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
11535 if (nBuffers > 1) {
11536 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
11537 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
11538 nBytes = MSG_SIZ - 1;
11540 (void) memcpy(msg, buffer, nBytes);
11542 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
11544 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
11545 cmailMailedMove = TRUE; /* Prevent >1 moves */
11548 for (i = 0; i < nCmailGames; i ++) {
11549 if (cmailResult[i] == CMAIL_NOT_RESULT) {
11554 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
11556 snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
11558 appData.cmailGameName,
11560 LoadGameFromFile(buffer, 1, buffer, FALSE);
11561 cmailMsgLoaded = FALSE;
11565 DisplayInformation(msg);
11566 pclose(commandOutput);
11569 if ((*cmailMsg) != '\0') {
11570 DisplayInformation(cmailMsg);
11575 #endif /* !WIN32 */
11584 int prependComma = 0;
11586 char string[MSG_SIZ]; /* Space for game-list */
11589 if (!cmailMsgLoaded) return "";
11591 if (cmailMailedMove) {
11592 snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
11594 /* Create a list of games left */
11595 snprintf(string, MSG_SIZ, "[");
11596 for (i = 0; i < nCmailGames; i ++) {
11597 if (! ( cmailMoveRegistered[i]
11598 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
11599 if (prependComma) {
11600 snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
11602 snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
11606 strcat(string, number);
11609 strcat(string, "]");
11611 if (nCmailMovesRegistered + nCmailResults == 0) {
11612 switch (nCmailGames) {
11614 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
11618 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
11622 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
11627 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
11629 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
11634 if (nCmailResults == nCmailGames) {
11635 snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
11637 snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
11642 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
11654 if (gameMode == Training)
11655 SetTrainingModeOff();
11658 cmailMsgLoaded = FALSE;
11659 if (appData.icsActive) {
11660 SendToICS(ics_prefix);
11661 SendToICS("refresh\n");
11671 /* Give up on clean exit */
11675 /* Keep trying for clean exit */
11679 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
11681 if (telnetISR != NULL) {
11682 RemoveInputSource(telnetISR);
11684 if (icsPR != NoProc) {
11685 DestroyChildProcess(icsPR, TRUE);
11688 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
11689 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
11691 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
11692 /* make sure this other one finishes before killing it! */
11693 if(endingGame) { int count = 0;
11694 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
11695 while(endingGame && count++ < 10) DoSleep(1);
11696 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
11699 /* Kill off chess programs */
11700 if (first.pr != NoProc) {
11703 DoSleep( appData.delayBeforeQuit );
11704 SendToProgram("quit\n", &first);
11705 DoSleep( appData.delayAfterQuit );
11706 DestroyChildProcess(first.pr, 10 /* [AS] first.useSigterm */ );
11708 if (second.pr != NoProc) {
11709 DoSleep( appData.delayBeforeQuit );
11710 SendToProgram("quit\n", &second);
11711 DoSleep( appData.delayAfterQuit );
11712 DestroyChildProcess(second.pr, 10 /* [AS] second.useSigterm */ );
11714 if (first.isr != NULL) {
11715 RemoveInputSource(first.isr);
11717 if (second.isr != NULL) {
11718 RemoveInputSource(second.isr);
11721 ShutDownFrontEnd();
11728 if (appData.debugMode)
11729 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
11733 if (gameMode == MachinePlaysWhite ||
11734 gameMode == MachinePlaysBlack) {
11737 DisplayBothClocks();
11739 if (gameMode == PlayFromGameFile) {
11740 if (appData.timeDelay >= 0)
11741 AutoPlayGameLoop();
11742 } else if (gameMode == IcsExamining && pauseExamInvalid) {
11743 Reset(FALSE, TRUE);
11744 SendToICS(ics_prefix);
11745 SendToICS("refresh\n");
11746 } else if (currentMove < forwardMostMove) {
11747 ForwardInner(forwardMostMove);
11749 pauseExamInvalid = FALSE;
11751 switch (gameMode) {
11755 pauseExamForwardMostMove = forwardMostMove;
11756 pauseExamInvalid = FALSE;
11759 case IcsPlayingWhite:
11760 case IcsPlayingBlack:
11764 case PlayFromGameFile:
11765 (void) StopLoadGameTimer();
11769 case BeginningOfGame:
11770 if (appData.icsActive) return;
11771 /* else fall through */
11772 case MachinePlaysWhite:
11773 case MachinePlaysBlack:
11774 case TwoMachinesPlay:
11775 if (forwardMostMove == 0)
11776 return; /* don't pause if no one has moved */
11777 if ((gameMode == MachinePlaysWhite &&
11778 !WhiteOnMove(forwardMostMove)) ||
11779 (gameMode == MachinePlaysBlack &&
11780 WhiteOnMove(forwardMostMove))) {
11793 char title[MSG_SIZ];
11795 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
11796 safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
11798 snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
11799 WhiteOnMove(currentMove - 1) ? " " : ".. ",
11800 parseList[currentMove - 1]);
11803 EditCommentPopUp(currentMove, title, commentList[currentMove]);
11810 char *tags = PGNTags(&gameInfo);
11811 EditTagsPopUp(tags, NULL);
11818 if (appData.noChessProgram || gameMode == AnalyzeMode)
11821 if (gameMode != AnalyzeFile) {
11822 if (!appData.icsEngineAnalyze) {
11824 if (gameMode != EditGame) return;
11826 ResurrectChessProgram();
11827 SendToProgram("analyze\n", &first);
11828 first.analyzing = TRUE;
11829 /*first.maybeThinking = TRUE;*/
11830 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11831 EngineOutputPopUp();
11833 if (!appData.icsEngineAnalyze) gameMode = AnalyzeMode;
11838 StartAnalysisClock();
11839 GetTimeMark(&lastNodeCountTime);
11846 if (appData.noChessProgram || gameMode == AnalyzeFile)
11849 if (gameMode != AnalyzeMode) {
11851 if (gameMode != EditGame) return;
11852 ResurrectChessProgram();
11853 SendToProgram("analyze\n", &first);
11854 first.analyzing = TRUE;
11855 /*first.maybeThinking = TRUE;*/
11856 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11857 EngineOutputPopUp();
11859 gameMode = AnalyzeFile;
11864 StartAnalysisClock();
11865 GetTimeMark(&lastNodeCountTime);
11870 MachineWhiteEvent()
11873 char *bookHit = NULL;
11875 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
11879 if (gameMode == PlayFromGameFile ||
11880 gameMode == TwoMachinesPlay ||
11881 gameMode == Training ||
11882 gameMode == AnalyzeMode ||
11883 gameMode == EndOfGame)
11886 if (gameMode == EditPosition)
11887 EditPositionDone(TRUE);
11889 if (!WhiteOnMove(currentMove)) {
11890 DisplayError(_("It is not White's turn"), 0);
11894 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
11897 if (gameMode == EditGame || gameMode == AnalyzeMode ||
11898 gameMode == AnalyzeFile)
11901 ResurrectChessProgram(); /* in case it isn't running */
11902 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
11903 gameMode = MachinePlaysWhite;
11906 gameMode = MachinePlaysWhite;
11910 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
11912 if (first.sendName) {
11913 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
11914 SendToProgram(buf, &first);
11916 if (first.sendTime) {
11917 if (first.useColors) {
11918 SendToProgram("black\n", &first); /*gnu kludge*/
11920 SendTimeRemaining(&first, TRUE);
11922 if (first.useColors) {
11923 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
11925 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
11926 SetMachineThinkingEnables();
11927 first.maybeThinking = TRUE;
11931 if (appData.autoFlipView && !flipView) {
11932 flipView = !flipView;
11933 DrawPosition(FALSE, NULL);
11934 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
11937 if(bookHit) { // [HGM] book: simulate book reply
11938 static char bookMove[MSG_SIZ]; // a bit generous?
11940 programStats.nodes = programStats.depth = programStats.time =
11941 programStats.score = programStats.got_only_move = 0;
11942 sprintf(programStats.movelist, "%s (xbook)", bookHit);
11944 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
11945 strcat(bookMove, bookHit);
11946 HandleMachineMove(bookMove, &first);
11951 MachineBlackEvent()
11954 char *bookHit = NULL;
11956 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
11960 if (gameMode == PlayFromGameFile ||
11961 gameMode == TwoMachinesPlay ||
11962 gameMode == Training ||
11963 gameMode == AnalyzeMode ||
11964 gameMode == EndOfGame)
11967 if (gameMode == EditPosition)
11968 EditPositionDone(TRUE);
11970 if (WhiteOnMove(currentMove)) {
11971 DisplayError(_("It is not Black's turn"), 0);
11975 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
11978 if (gameMode == EditGame || gameMode == AnalyzeMode ||
11979 gameMode == AnalyzeFile)
11982 ResurrectChessProgram(); /* in case it isn't running */
11983 gameMode = MachinePlaysBlack;
11987 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
11989 if (first.sendName) {
11990 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
11991 SendToProgram(buf, &first);
11993 if (first.sendTime) {
11994 if (first.useColors) {
11995 SendToProgram("white\n", &first); /*gnu kludge*/
11997 SendTimeRemaining(&first, FALSE);
11999 if (first.useColors) {
12000 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
12002 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
12003 SetMachineThinkingEnables();
12004 first.maybeThinking = TRUE;
12007 if (appData.autoFlipView && flipView) {
12008 flipView = !flipView;
12009 DrawPosition(FALSE, NULL);
12010 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
12012 if(bookHit) { // [HGM] book: simulate book reply
12013 static char bookMove[MSG_SIZ]; // a bit generous?
12015 programStats.nodes = programStats.depth = programStats.time =
12016 programStats.score = programStats.got_only_move = 0;
12017 sprintf(programStats.movelist, "%s (xbook)", bookHit);
12019 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
12020 strcat(bookMove, bookHit);
12021 HandleMachineMove(bookMove, &first);
12027 DisplayTwoMachinesTitle()
12030 if (appData.matchGames > 0) {
12031 if (first.twoMachinesColor[0] == 'w') {
12032 snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
12033 gameInfo.white, gameInfo.black,
12034 first.matchWins, second.matchWins,
12035 matchGame - 1 - (first.matchWins + second.matchWins));
12037 snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
12038 gameInfo.white, gameInfo.black,
12039 second.matchWins, first.matchWins,
12040 matchGame - 1 - (first.matchWins + second.matchWins));
12043 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
12049 SettingsMenuIfReady()
12051 if (second.lastPing != second.lastPong) {
12052 DisplayMessage("", _("Waiting for second chess program"));
12053 ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
12057 DisplayMessage("", "");
12058 SettingsPopUp(&second);
12062 WaitForSecond(DelayedEventCallback retry)
12064 if (second.pr == NULL) {
12065 StartChessProgram(&second);
12066 if (second.protocolVersion == 1) {
12069 /* kludge: allow timeout for initial "feature" command */
12071 DisplayMessage("", _("Starting second chess program"));
12072 ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
12080 TwoMachinesEvent P((void))
12084 ChessProgramState *onmove;
12085 char *bookHit = NULL;
12086 static int stalling = 0;
12088 if (appData.noChessProgram) return;
12090 switch (gameMode) {
12091 case TwoMachinesPlay:
12093 case MachinePlaysWhite:
12094 case MachinePlaysBlack:
12095 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
12096 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
12100 case BeginningOfGame:
12101 case PlayFromGameFile:
12104 if (gameMode != EditGame) return;
12107 EditPositionDone(TRUE);
12118 // forwardMostMove = currentMove;
12119 TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
12120 ResurrectChessProgram(); /* in case first program isn't running */
12122 if(WaitForSecond(TwoMachinesEventIfReady)) return;
12123 if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
12124 DisplayMessage("", _("Waiting for first chess program"));
12125 ScheduleDelayedEvent(TwoMachinesEvent, 10);
12129 InitChessProgram(&second, FALSE);
12130 SendToProgram("force\n", &second);
12132 if(second.lastPing != second.lastPong) { // [HGM] second engine might have to reallocate hash
12133 if(!stalling) DisplayMessage("", _("Waiting for second chess program"));
12135 ScheduleDelayedEvent(TwoMachinesEvent, 10);
12139 DisplayMessage("", "");
12140 if (startedFromSetupPosition) {
12141 SendBoard(&second, backwardMostMove);
12142 if (appData.debugMode) {
12143 fprintf(debugFP, "Two Machines\n");
12146 for (i = backwardMostMove; i < forwardMostMove; i++) {
12147 SendMoveToProgram(i, &second);
12150 gameMode = TwoMachinesPlay;
12154 DisplayTwoMachinesTitle();
12156 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
12162 SendToProgram(first.computerString, &first);
12163 if (first.sendName) {
12164 snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
12165 SendToProgram(buf, &first);
12167 SendToProgram(second.computerString, &second);
12168 if (second.sendName) {
12169 snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
12170 SendToProgram(buf, &second);
12174 if (!first.sendTime || !second.sendTime) {
12175 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
12176 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
12178 if (onmove->sendTime) {
12179 if (onmove->useColors) {
12180 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
12182 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
12184 if (onmove->useColors) {
12185 SendToProgram(onmove->twoMachinesColor, onmove);
12187 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
12188 // SendToProgram("go\n", onmove);
12189 onmove->maybeThinking = TRUE;
12190 SetMachineThinkingEnables();
12194 if(bookHit) { // [HGM] book: simulate book reply
12195 static char bookMove[MSG_SIZ]; // a bit generous?
12197 programStats.nodes = programStats.depth = programStats.time =
12198 programStats.score = programStats.got_only_move = 0;
12199 sprintf(programStats.movelist, "%s (xbook)", bookHit);
12201 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
12202 strcat(bookMove, bookHit);
12203 savedMessage = bookMove; // args for deferred call
12204 savedState = onmove;
12205 ScheduleDelayedEvent(DeferredBookMove, 1);
12212 if (gameMode == Training) {
12213 SetTrainingModeOff();
12214 gameMode = PlayFromGameFile;
12215 DisplayMessage("", _("Training mode off"));
12217 gameMode = Training;
12218 animateTraining = appData.animate;
12220 /* make sure we are not already at the end of the game */
12221 if (currentMove < forwardMostMove) {
12222 SetTrainingModeOn();
12223 DisplayMessage("", _("Training mode on"));
12225 gameMode = PlayFromGameFile;
12226 DisplayError(_("Already at end of game"), 0);
12235 if (!appData.icsActive) return;
12236 switch (gameMode) {
12237 case IcsPlayingWhite:
12238 case IcsPlayingBlack:
12241 case BeginningOfGame:
12249 EditPositionDone(TRUE);
12262 gameMode = IcsIdle;
12273 switch (gameMode) {
12275 SetTrainingModeOff();
12277 case MachinePlaysWhite:
12278 case MachinePlaysBlack:
12279 case BeginningOfGame:
12280 SendToProgram("force\n", &first);
12281 SetUserThinkingEnables();
12283 case PlayFromGameFile:
12284 (void) StopLoadGameTimer();
12285 if (gameFileFP != NULL) {
12290 EditPositionDone(TRUE);
12295 SendToProgram("force\n", &first);
12297 case TwoMachinesPlay:
12298 GameEnds(EndOfFile, NULL, GE_PLAYER);
12299 ResurrectChessProgram();
12300 SetUserThinkingEnables();
12303 ResurrectChessProgram();
12305 case IcsPlayingBlack:
12306 case IcsPlayingWhite:
12307 DisplayError(_("Warning: You are still playing a game"), 0);
12310 DisplayError(_("Warning: You are still observing a game"), 0);
12313 DisplayError(_("Warning: You are still examining a game"), 0);
12324 first.offeredDraw = second.offeredDraw = 0;
12326 if (gameMode == PlayFromGameFile) {
12327 whiteTimeRemaining = timeRemaining[0][currentMove];
12328 blackTimeRemaining = timeRemaining[1][currentMove];
12332 if (gameMode == MachinePlaysWhite ||
12333 gameMode == MachinePlaysBlack ||
12334 gameMode == TwoMachinesPlay ||
12335 gameMode == EndOfGame) {
12336 i = forwardMostMove;
12337 while (i > currentMove) {
12338 SendToProgram("undo\n", &first);
12341 whiteTimeRemaining = timeRemaining[0][currentMove];
12342 blackTimeRemaining = timeRemaining[1][currentMove];
12343 DisplayBothClocks();
12344 if (whiteFlag || blackFlag) {
12345 whiteFlag = blackFlag = 0;
12350 gameMode = EditGame;
12357 EditPositionEvent()
12359 if (gameMode == EditPosition) {
12365 if (gameMode != EditGame) return;
12367 gameMode = EditPosition;
12370 if (currentMove > 0)
12371 CopyBoard(boards[0], boards[currentMove]);
12373 blackPlaysFirst = !WhiteOnMove(currentMove);
12375 currentMove = forwardMostMove = backwardMostMove = 0;
12376 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12383 /* [DM] icsEngineAnalyze - possible call from other functions */
12384 if (appData.icsEngineAnalyze) {
12385 appData.icsEngineAnalyze = FALSE;
12387 DisplayMessage("",_("Close ICS engine analyze..."));
12389 if (first.analysisSupport && first.analyzing) {
12390 SendToProgram("exit\n", &first);
12391 first.analyzing = FALSE;
12393 thinkOutput[0] = NULLCHAR;
12397 EditPositionDone(Boolean fakeRights)
12399 int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
12401 startedFromSetupPosition = TRUE;
12402 InitChessProgram(&first, FALSE);
12403 if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
12404 boards[0][EP_STATUS] = EP_NONE;
12405 boards[0][CASTLING][2] = boards[0][CASTLING][5] = BOARD_WIDTH>>1;
12406 if(boards[0][0][BOARD_WIDTH>>1] == king) {
12407 boards[0][CASTLING][1] = boards[0][0][BOARD_LEFT] == WhiteRook ? 0 : NoRights;
12408 boards[0][CASTLING][0] = boards[0][0][BOARD_RGHT-1] == WhiteRook ? BOARD_RGHT-1 : NoRights;
12409 } else boards[0][CASTLING][2] = NoRights;
12410 if(boards[0][BOARD_HEIGHT-1][BOARD_WIDTH>>1] == WHITE_TO_BLACK king) {
12411 boards[0][CASTLING][4] = boards[0][BOARD_HEIGHT-1][BOARD_LEFT] == BlackRook ? 0 : NoRights;
12412 boards[0][CASTLING][3] = boards[0][BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook ? BOARD_RGHT-1 : NoRights;
12413 } else boards[0][CASTLING][5] = NoRights;
12415 SendToProgram("force\n", &first);
12416 if (blackPlaysFirst) {
12417 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12418 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12419 currentMove = forwardMostMove = backwardMostMove = 1;
12420 CopyBoard(boards[1], boards[0]);
12422 currentMove = forwardMostMove = backwardMostMove = 0;
12424 SendBoard(&first, forwardMostMove);
12425 if (appData.debugMode) {
12426 fprintf(debugFP, "EditPosDone\n");
12429 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
12430 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
12431 gameMode = EditGame;
12433 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12434 ClearHighlights(); /* [AS] */
12437 /* Pause for `ms' milliseconds */
12438 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
12448 } while (SubtractTimeMarks(&m2, &m1) < ms);
12451 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
12453 SendMultiLineToICS(buf)
12456 char temp[MSG_SIZ+1], *p;
12463 strncpy(temp, buf, len);
12468 if (*p == '\n' || *p == '\r')
12473 strcat(temp, "\n");
12475 SendToPlayer(temp, strlen(temp));
12479 SetWhiteToPlayEvent()
12481 if (gameMode == EditPosition) {
12482 blackPlaysFirst = FALSE;
12483 DisplayBothClocks(); /* works because currentMove is 0 */
12484 } else if (gameMode == IcsExamining) {
12485 SendToICS(ics_prefix);
12486 SendToICS("tomove white\n");
12491 SetBlackToPlayEvent()
12493 if (gameMode == EditPosition) {
12494 blackPlaysFirst = TRUE;
12495 currentMove = 1; /* kludge */
12496 DisplayBothClocks();
12498 } else if (gameMode == IcsExamining) {
12499 SendToICS(ics_prefix);
12500 SendToICS("tomove black\n");
12505 EditPositionMenuEvent(selection, x, y)
12506 ChessSquare selection;
12510 ChessSquare piece = boards[0][y][x];
12512 if (gameMode != EditPosition && gameMode != IcsExamining) return;
12514 switch (selection) {
12516 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
12517 SendToICS(ics_prefix);
12518 SendToICS("bsetup clear\n");
12519 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
12520 SendToICS(ics_prefix);
12521 SendToICS("clearboard\n");
12523 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
12524 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
12525 for (y = 0; y < BOARD_HEIGHT; y++) {
12526 if (gameMode == IcsExamining) {
12527 if (boards[currentMove][y][x] != EmptySquare) {
12528 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
12533 boards[0][y][x] = p;
12538 if (gameMode == EditPosition) {
12539 DrawPosition(FALSE, boards[0]);
12544 SetWhiteToPlayEvent();
12548 SetBlackToPlayEvent();
12552 if (gameMode == IcsExamining) {
12553 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
12554 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
12557 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
12558 if(x == BOARD_LEFT-2) {
12559 if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
12560 boards[0][y][1] = 0;
12562 if(x == BOARD_RGHT+1) {
12563 if(y >= gameInfo.holdingsSize) break;
12564 boards[0][y][BOARD_WIDTH-2] = 0;
12567 boards[0][y][x] = EmptySquare;
12568 DrawPosition(FALSE, boards[0]);
12573 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
12574 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
12575 selection = (ChessSquare) (PROMOTED piece);
12576 } else if(piece == EmptySquare) selection = WhiteSilver;
12577 else selection = (ChessSquare)((int)piece - 1);
12581 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
12582 piece > (int)BlackMan && piece <= (int)BlackKing ) {
12583 selection = (ChessSquare) (DEMOTED piece);
12584 } else if(piece == EmptySquare) selection = BlackSilver;
12585 else selection = (ChessSquare)((int)piece + 1);
12590 if(gameInfo.variant == VariantShatranj ||
12591 gameInfo.variant == VariantXiangqi ||
12592 gameInfo.variant == VariantCourier ||
12593 gameInfo.variant == VariantMakruk )
12594 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
12599 if(gameInfo.variant == VariantXiangqi)
12600 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
12601 if(gameInfo.variant == VariantKnightmate)
12602 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
12605 if (gameMode == IcsExamining) {
12606 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
12607 snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
12608 PieceToChar(selection), AAA + x, ONE + y);
12611 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
12613 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
12614 n = PieceToNumber(selection - BlackPawn);
12615 if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
12616 boards[0][BOARD_HEIGHT-1-n][0] = selection;
12617 boards[0][BOARD_HEIGHT-1-n][1]++;
12619 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
12620 n = PieceToNumber(selection);
12621 if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
12622 boards[0][n][BOARD_WIDTH-1] = selection;
12623 boards[0][n][BOARD_WIDTH-2]++;
12626 boards[0][y][x] = selection;
12627 DrawPosition(TRUE, boards[0]);
12635 DropMenuEvent(selection, x, y)
12636 ChessSquare selection;
12639 ChessMove moveType;
12641 switch (gameMode) {
12642 case IcsPlayingWhite:
12643 case MachinePlaysBlack:
12644 if (!WhiteOnMove(currentMove)) {
12645 DisplayMoveError(_("It is Black's turn"));
12648 moveType = WhiteDrop;
12650 case IcsPlayingBlack:
12651 case MachinePlaysWhite:
12652 if (WhiteOnMove(currentMove)) {
12653 DisplayMoveError(_("It is White's turn"));
12656 moveType = BlackDrop;
12659 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
12665 if (moveType == BlackDrop && selection < BlackPawn) {
12666 selection = (ChessSquare) ((int) selection
12667 + (int) BlackPawn - (int) WhitePawn);
12669 if (boards[currentMove][y][x] != EmptySquare) {
12670 DisplayMoveError(_("That square is occupied"));
12674 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
12680 /* Accept a pending offer of any kind from opponent */
12682 if (appData.icsActive) {
12683 SendToICS(ics_prefix);
12684 SendToICS("accept\n");
12685 } else if (cmailMsgLoaded) {
12686 if (currentMove == cmailOldMove &&
12687 commentList[cmailOldMove] != NULL &&
12688 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12689 "Black offers a draw" : "White offers a draw")) {
12691 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12692 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
12694 DisplayError(_("There is no pending offer on this move"), 0);
12695 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12698 /* Not used for offers from chess program */
12705 /* Decline a pending offer of any kind from opponent */
12707 if (appData.icsActive) {
12708 SendToICS(ics_prefix);
12709 SendToICS("decline\n");
12710 } else if (cmailMsgLoaded) {
12711 if (currentMove == cmailOldMove &&
12712 commentList[cmailOldMove] != NULL &&
12713 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12714 "Black offers a draw" : "White offers a draw")) {
12716 AppendComment(cmailOldMove, "Draw declined", TRUE);
12717 DisplayComment(cmailOldMove - 1, "Draw declined");
12720 DisplayError(_("There is no pending offer on this move"), 0);
12723 /* Not used for offers from chess program */
12730 /* Issue ICS rematch command */
12731 if (appData.icsActive) {
12732 SendToICS(ics_prefix);
12733 SendToICS("rematch\n");
12740 /* Call your opponent's flag (claim a win on time) */
12741 if (appData.icsActive) {
12742 SendToICS(ics_prefix);
12743 SendToICS("flag\n");
12745 switch (gameMode) {
12748 case MachinePlaysWhite:
12751 GameEnds(GameIsDrawn, "Both players ran out of time",
12754 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
12756 DisplayError(_("Your opponent is not out of time"), 0);
12759 case MachinePlaysBlack:
12762 GameEnds(GameIsDrawn, "Both players ran out of time",
12765 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
12767 DisplayError(_("Your opponent is not out of time"), 0);
12775 ClockClick(int which)
12776 { // [HGM] code moved to back-end from winboard.c
12777 if(which) { // black clock
12778 if (gameMode == EditPosition || gameMode == IcsExamining) {
12779 if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
12780 SetBlackToPlayEvent();
12781 } else if (gameMode == EditGame || shiftKey) {
12782 AdjustClock(which, -1);
12783 } else if (gameMode == IcsPlayingWhite ||
12784 gameMode == MachinePlaysBlack) {
12787 } else { // white clock
12788 if (gameMode == EditPosition || gameMode == IcsExamining) {
12789 if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
12790 SetWhiteToPlayEvent();
12791 } else if (gameMode == EditGame || shiftKey) {
12792 AdjustClock(which, -1);
12793 } else if (gameMode == IcsPlayingBlack ||
12794 gameMode == MachinePlaysWhite) {
12803 /* Offer draw or accept pending draw offer from opponent */
12805 if (appData.icsActive) {
12806 /* Note: tournament rules require draw offers to be
12807 made after you make your move but before you punch
12808 your clock. Currently ICS doesn't let you do that;
12809 instead, you immediately punch your clock after making
12810 a move, but you can offer a draw at any time. */
12812 SendToICS(ics_prefix);
12813 SendToICS("draw\n");
12814 userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
12815 } else if (cmailMsgLoaded) {
12816 if (currentMove == cmailOldMove &&
12817 commentList[cmailOldMove] != NULL &&
12818 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12819 "Black offers a draw" : "White offers a draw")) {
12820 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12821 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
12822 } else if (currentMove == cmailOldMove + 1) {
12823 char *offer = WhiteOnMove(cmailOldMove) ?
12824 "White offers a draw" : "Black offers a draw";
12825 AppendComment(currentMove, offer, TRUE);
12826 DisplayComment(currentMove - 1, offer);
12827 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
12829 DisplayError(_("You must make your move before offering a draw"), 0);
12830 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12832 } else if (first.offeredDraw) {
12833 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
12835 if (first.sendDrawOffers) {
12836 SendToProgram("draw\n", &first);
12837 userOfferedDraw = TRUE;
12845 /* Offer Adjourn or accept pending Adjourn offer from opponent */
12847 if (appData.icsActive) {
12848 SendToICS(ics_prefix);
12849 SendToICS("adjourn\n");
12851 /* Currently GNU Chess doesn't offer or accept Adjourns */
12859 /* Offer Abort or accept pending Abort offer from opponent */
12861 if (appData.icsActive) {
12862 SendToICS(ics_prefix);
12863 SendToICS("abort\n");
12865 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
12872 /* Resign. You can do this even if it's not your turn. */
12874 if (appData.icsActive) {
12875 SendToICS(ics_prefix);
12876 SendToICS("resign\n");
12878 switch (gameMode) {
12879 case MachinePlaysWhite:
12880 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12882 case MachinePlaysBlack:
12883 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12886 if (cmailMsgLoaded) {
12888 if (WhiteOnMove(cmailOldMove)) {
12889 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12891 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12893 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
12904 StopObservingEvent()
12906 /* Stop observing current games */
12907 SendToICS(ics_prefix);
12908 SendToICS("unobserve\n");
12912 StopExaminingEvent()
12914 /* Stop observing current game */
12915 SendToICS(ics_prefix);
12916 SendToICS("unexamine\n");
12920 ForwardInner(target)
12925 if (appData.debugMode)
12926 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
12927 target, currentMove, forwardMostMove);
12929 if (gameMode == EditPosition)
12932 if (gameMode == PlayFromGameFile && !pausing)
12935 if (gameMode == IcsExamining && pausing)
12936 limit = pauseExamForwardMostMove;
12938 limit = forwardMostMove;
12940 if (target > limit) target = limit;
12942 if (target > 0 && moveList[target - 1][0]) {
12943 int fromX, fromY, toX, toY;
12944 toX = moveList[target - 1][2] - AAA;
12945 toY = moveList[target - 1][3] - ONE;
12946 if (moveList[target - 1][1] == '@') {
12947 if (appData.highlightLastMove) {
12948 SetHighlights(-1, -1, toX, toY);
12951 fromX = moveList[target - 1][0] - AAA;
12952 fromY = moveList[target - 1][1] - ONE;
12953 if (target == currentMove + 1) {
12954 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
12956 if (appData.highlightLastMove) {
12957 SetHighlights(fromX, fromY, toX, toY);
12961 if (gameMode == EditGame || gameMode == AnalyzeMode ||
12962 gameMode == Training || gameMode == PlayFromGameFile ||
12963 gameMode == AnalyzeFile) {
12964 while (currentMove < target) {
12965 SendMoveToProgram(currentMove++, &first);
12968 currentMove = target;
12971 if (gameMode == EditGame || gameMode == EndOfGame) {
12972 whiteTimeRemaining = timeRemaining[0][currentMove];
12973 blackTimeRemaining = timeRemaining[1][currentMove];
12975 DisplayBothClocks();
12976 DisplayMove(currentMove - 1);
12977 DrawPosition(FALSE, boards[currentMove]);
12978 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
12979 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
12980 DisplayComment(currentMove - 1, commentList[currentMove]);
12988 if (gameMode == IcsExamining && !pausing) {
12989 SendToICS(ics_prefix);
12990 SendToICS("forward\n");
12992 ForwardInner(currentMove + 1);
12999 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13000 /* to optimze, we temporarily turn off analysis mode while we feed
13001 * the remaining moves to the engine. Otherwise we get analysis output
13004 if (first.analysisSupport) {
13005 SendToProgram("exit\nforce\n", &first);
13006 first.analyzing = FALSE;
13010 if (gameMode == IcsExamining && !pausing) {
13011 SendToICS(ics_prefix);
13012 SendToICS("forward 999999\n");
13014 ForwardInner(forwardMostMove);
13017 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13018 /* we have fed all the moves, so reactivate analysis mode */
13019 SendToProgram("analyze\n", &first);
13020 first.analyzing = TRUE;
13021 /*first.maybeThinking = TRUE;*/
13022 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13027 BackwardInner(target)
13030 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
13032 if (appData.debugMode)
13033 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
13034 target, currentMove, forwardMostMove);
13036 if (gameMode == EditPosition) return;
13037 if (currentMove <= backwardMostMove) {
13039 DrawPosition(full_redraw, boards[currentMove]);
13042 if (gameMode == PlayFromGameFile && !pausing)
13045 if (moveList[target][0]) {
13046 int fromX, fromY, toX, toY;
13047 toX = moveList[target][2] - AAA;
13048 toY = moveList[target][3] - ONE;
13049 if (moveList[target][1] == '@') {
13050 if (appData.highlightLastMove) {
13051 SetHighlights(-1, -1, toX, toY);
13054 fromX = moveList[target][0] - AAA;
13055 fromY = moveList[target][1] - ONE;
13056 if (target == currentMove - 1) {
13057 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
13059 if (appData.highlightLastMove) {
13060 SetHighlights(fromX, fromY, toX, toY);
13064 if (gameMode == EditGame || gameMode==AnalyzeMode ||
13065 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
13066 while (currentMove > target) {
13067 SendToProgram("undo\n", &first);
13071 currentMove = target;
13074 if (gameMode == EditGame || gameMode == EndOfGame) {
13075 whiteTimeRemaining = timeRemaining[0][currentMove];
13076 blackTimeRemaining = timeRemaining[1][currentMove];
13078 DisplayBothClocks();
13079 DisplayMove(currentMove - 1);
13080 DrawPosition(full_redraw, boards[currentMove]);
13081 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
13082 // [HGM] PV info: routine tests if comment empty
13083 DisplayComment(currentMove - 1, commentList[currentMove]);
13089 if (gameMode == IcsExamining && !pausing) {
13090 SendToICS(ics_prefix);
13091 SendToICS("backward\n");
13093 BackwardInner(currentMove - 1);
13100 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13101 /* to optimize, we temporarily turn off analysis mode while we undo
13102 * all the moves. Otherwise we get analysis output after each undo.
13104 if (first.analysisSupport) {
13105 SendToProgram("exit\nforce\n", &first);
13106 first.analyzing = FALSE;
13110 if (gameMode == IcsExamining && !pausing) {
13111 SendToICS(ics_prefix);
13112 SendToICS("backward 999999\n");
13114 BackwardInner(backwardMostMove);
13117 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13118 /* we have fed all the moves, so reactivate analysis mode */
13119 SendToProgram("analyze\n", &first);
13120 first.analyzing = TRUE;
13121 /*first.maybeThinking = TRUE;*/
13122 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13129 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
13130 if (to >= forwardMostMove) to = forwardMostMove;
13131 if (to <= backwardMostMove) to = backwardMostMove;
13132 if (to < currentMove) {
13140 RevertEvent(Boolean annotate)
13142 if(PopTail(annotate)) { // [HGM] vari: restore old game tail
13145 if (gameMode != IcsExamining) {
13146 DisplayError(_("You are not examining a game"), 0);
13150 DisplayError(_("You can't revert while pausing"), 0);
13153 SendToICS(ics_prefix);
13154 SendToICS("revert\n");
13160 switch (gameMode) {
13161 case MachinePlaysWhite:
13162 case MachinePlaysBlack:
13163 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
13164 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
13167 if (forwardMostMove < 2) return;
13168 currentMove = forwardMostMove = forwardMostMove - 2;
13169 whiteTimeRemaining = timeRemaining[0][currentMove];
13170 blackTimeRemaining = timeRemaining[1][currentMove];
13171 DisplayBothClocks();
13172 DisplayMove(currentMove - 1);
13173 ClearHighlights();/*!! could figure this out*/
13174 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
13175 SendToProgram("remove\n", &first);
13176 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
13179 case BeginningOfGame:
13183 case IcsPlayingWhite:
13184 case IcsPlayingBlack:
13185 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
13186 SendToICS(ics_prefix);
13187 SendToICS("takeback 2\n");
13189 SendToICS(ics_prefix);
13190 SendToICS("takeback 1\n");
13199 ChessProgramState *cps;
13201 switch (gameMode) {
13202 case MachinePlaysWhite:
13203 if (!WhiteOnMove(forwardMostMove)) {
13204 DisplayError(_("It is your turn"), 0);
13209 case MachinePlaysBlack:
13210 if (WhiteOnMove(forwardMostMove)) {
13211 DisplayError(_("It is your turn"), 0);
13216 case TwoMachinesPlay:
13217 if (WhiteOnMove(forwardMostMove) ==
13218 (first.twoMachinesColor[0] == 'w')) {
13224 case BeginningOfGame:
13228 SendToProgram("?\n", cps);
13232 TruncateGameEvent()
13235 if (gameMode != EditGame) return;
13242 CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
13243 if (forwardMostMove > currentMove) {
13244 if (gameInfo.resultDetails != NULL) {
13245 free(gameInfo.resultDetails);
13246 gameInfo.resultDetails = NULL;
13247 gameInfo.result = GameUnfinished;
13249 forwardMostMove = currentMove;
13250 HistorySet(parseList, backwardMostMove, forwardMostMove,
13258 if (appData.noChessProgram) return;
13259 switch (gameMode) {
13260 case MachinePlaysWhite:
13261 if (WhiteOnMove(forwardMostMove)) {
13262 DisplayError(_("Wait until your turn"), 0);
13266 case BeginningOfGame:
13267 case MachinePlaysBlack:
13268 if (!WhiteOnMove(forwardMostMove)) {
13269 DisplayError(_("Wait until your turn"), 0);
13274 DisplayError(_("No hint available"), 0);
13277 SendToProgram("hint\n", &first);
13278 hintRequested = TRUE;
13284 if (appData.noChessProgram) return;
13285 switch (gameMode) {
13286 case MachinePlaysWhite:
13287 if (WhiteOnMove(forwardMostMove)) {
13288 DisplayError(_("Wait until your turn"), 0);
13292 case BeginningOfGame:
13293 case MachinePlaysBlack:
13294 if (!WhiteOnMove(forwardMostMove)) {
13295 DisplayError(_("Wait until your turn"), 0);
13300 EditPositionDone(TRUE);
13302 case TwoMachinesPlay:
13307 SendToProgram("bk\n", &first);
13308 bookOutput[0] = NULLCHAR;
13309 bookRequested = TRUE;
13315 char *tags = PGNTags(&gameInfo);
13316 TagsPopUp(tags, CmailMsg());
13320 /* end button procedures */
13323 PrintPosition(fp, move)
13329 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
13330 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
13331 char c = PieceToChar(boards[move][i][j]);
13332 fputc(c == 'x' ? '.' : c, fp);
13333 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
13336 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
13337 fprintf(fp, "white to play\n");
13339 fprintf(fp, "black to play\n");
13346 if (gameInfo.white != NULL) {
13347 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
13353 /* Find last component of program's own name, using some heuristics */
13355 TidyProgramName(prog, host, buf)
13356 char *prog, *host, buf[MSG_SIZ];
13359 int local = (strcmp(host, "localhost") == 0);
13360 while (!local && (p = strchr(prog, ';')) != NULL) {
13362 while (*p == ' ') p++;
13365 if (*prog == '"' || *prog == '\'') {
13366 q = strchr(prog + 1, *prog);
13368 q = strchr(prog, ' ');
13370 if (q == NULL) q = prog + strlen(prog);
13372 while (p >= prog && *p != '/' && *p != '\\') p--;
13374 if(p == prog && *p == '"') p++;
13375 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) q -= 4;
13376 memcpy(buf, p, q - p);
13377 buf[q - p] = NULLCHAR;
13385 TimeControlTagValue()
13388 if (!appData.clockMode) {
13389 safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
13390 } else if (movesPerSession > 0) {
13391 snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
13392 } else if (timeIncrement == 0) {
13393 snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
13395 snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
13397 return StrSave(buf);
13403 /* This routine is used only for certain modes */
13404 VariantClass v = gameInfo.variant;
13405 ChessMove r = GameUnfinished;
13408 if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
13409 r = gameInfo.result;
13410 p = gameInfo.resultDetails;
13411 gameInfo.resultDetails = NULL;
13413 ClearGameInfo(&gameInfo);
13414 gameInfo.variant = v;
13416 switch (gameMode) {
13417 case MachinePlaysWhite:
13418 gameInfo.event = StrSave( appData.pgnEventHeader );
13419 gameInfo.site = StrSave(HostName());
13420 gameInfo.date = PGNDate();
13421 gameInfo.round = StrSave("-");
13422 gameInfo.white = StrSave(first.tidy);
13423 gameInfo.black = StrSave(UserName());
13424 gameInfo.timeControl = TimeControlTagValue();
13427 case MachinePlaysBlack:
13428 gameInfo.event = StrSave( appData.pgnEventHeader );
13429 gameInfo.site = StrSave(HostName());
13430 gameInfo.date = PGNDate();
13431 gameInfo.round = StrSave("-");
13432 gameInfo.white = StrSave(UserName());
13433 gameInfo.black = StrSave(first.tidy);
13434 gameInfo.timeControl = TimeControlTagValue();
13437 case TwoMachinesPlay:
13438 gameInfo.event = StrSave( appData.pgnEventHeader );
13439 gameInfo.site = StrSave(HostName());
13440 gameInfo.date = PGNDate();
13441 if (matchGame > 0) {
13443 snprintf(buf, MSG_SIZ, "%d", matchGame);
13444 gameInfo.round = StrSave(buf);
13446 gameInfo.round = StrSave("-");
13448 if (first.twoMachinesColor[0] == 'w') {
13449 gameInfo.white = StrSave(first.tidy);
13450 gameInfo.black = StrSave(second.tidy);
13452 gameInfo.white = StrSave(second.tidy);
13453 gameInfo.black = StrSave(first.tidy);
13455 gameInfo.timeControl = TimeControlTagValue();
13459 gameInfo.event = StrSave("Edited game");
13460 gameInfo.site = StrSave(HostName());
13461 gameInfo.date = PGNDate();
13462 gameInfo.round = StrSave("-");
13463 gameInfo.white = StrSave("-");
13464 gameInfo.black = StrSave("-");
13465 gameInfo.result = r;
13466 gameInfo.resultDetails = p;
13470 gameInfo.event = StrSave("Edited position");
13471 gameInfo.site = StrSave(HostName());
13472 gameInfo.date = PGNDate();
13473 gameInfo.round = StrSave("-");
13474 gameInfo.white = StrSave("-");
13475 gameInfo.black = StrSave("-");
13478 case IcsPlayingWhite:
13479 case IcsPlayingBlack:
13484 case PlayFromGameFile:
13485 gameInfo.event = StrSave("Game from non-PGN file");
13486 gameInfo.site = StrSave(HostName());
13487 gameInfo.date = PGNDate();
13488 gameInfo.round = StrSave("-");
13489 gameInfo.white = StrSave("?");
13490 gameInfo.black = StrSave("?");
13499 ReplaceComment(index, text)
13507 if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
13508 pvInfoList[index-1].depth == len &&
13509 fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
13510 (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
13511 while (*text == '\n') text++;
13512 len = strlen(text);
13513 while (len > 0 && text[len - 1] == '\n') len--;
13515 if (commentList[index] != NULL)
13516 free(commentList[index]);
13519 commentList[index] = NULL;
13522 if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
13523 *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
13524 *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
13525 commentList[index] = (char *) malloc(len + 2);
13526 strncpy(commentList[index], text, len);
13527 commentList[index][len] = '\n';
13528 commentList[index][len + 1] = NULLCHAR;
13530 // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
13532 commentList[index] = (char *) malloc(len + 7);
13533 safeStrCpy(commentList[index], "{\n", 3);
13534 safeStrCpy(commentList[index]+2, text, len+1);
13535 commentList[index][len+2] = NULLCHAR;
13536 while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
13537 strcat(commentList[index], "\n}\n");
13551 if (ch == '\r') continue;
13553 } while (ch != '\0');
13557 AppendComment(index, text, addBraces)
13560 Boolean addBraces; // [HGM] braces: tells if we should add {}
13565 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces); fflush(debugFP);
13566 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
13569 while (*text == '\n') text++;
13570 len = strlen(text);
13571 while (len > 0 && text[len - 1] == '\n') len--;
13573 if (len == 0) return;
13575 if (commentList[index] != NULL) {
13576 old = commentList[index];
13577 oldlen = strlen(old);
13578 while(commentList[index][oldlen-1] == '\n')
13579 commentList[index][--oldlen] = NULLCHAR;
13580 commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
13581 safeStrCpy(commentList[index], old, oldlen + len + 6);
13583 // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
13584 if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
13585 if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
13586 while (*text == '\n') { text++; len--; }
13587 commentList[index][--oldlen] = NULLCHAR;
13589 if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
13590 else strcat(commentList[index], "\n");
13591 strcat(commentList[index], text);
13592 if(addBraces) strcat(commentList[index], addBraces == 2 ? ")\n" : "\n}\n");
13593 else strcat(commentList[index], "\n");
13595 commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
13597 safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
13598 else commentList[index][0] = NULLCHAR;
13599 strcat(commentList[index], text);
13600 strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
13601 if(addBraces == TRUE) strcat(commentList[index], "}\n");
13605 static char * FindStr( char * text, char * sub_text )
13607 char * result = strstr( text, sub_text );
13609 if( result != NULL ) {
13610 result += strlen( sub_text );
13616 /* [AS] Try to extract PV info from PGN comment */
13617 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
13618 char *GetInfoFromComment( int index, char * text )
13620 char * sep = text, *p;
13622 if( text != NULL && index > 0 ) {
13625 int time = -1, sec = 0, deci;
13626 char * s_eval = FindStr( text, "[%eval " );
13627 char * s_emt = FindStr( text, "[%emt " );
13629 if( s_eval != NULL || s_emt != NULL ) {
13633 if( s_eval != NULL ) {
13634 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
13638 if( delim != ']' ) {
13643 if( s_emt != NULL ) {
13648 /* We expect something like: [+|-]nnn.nn/dd */
13651 if(*text != '{') return text; // [HGM] braces: must be normal comment
13653 sep = strchr( text, '/' );
13654 if( sep == NULL || sep < (text+4) ) {
13659 if(p[1] == '(') { // comment starts with PV
13660 p = strchr(p, ')'); // locate end of PV
13661 if(p == NULL || sep < p+5) return text;
13662 // at this point we have something like "{(.*) +0.23/6 ..."
13663 p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
13664 *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
13665 // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
13667 time = -1; sec = -1; deci = -1;
13668 if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
13669 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
13670 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
13671 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
13675 if( score_lo < 0 || score_lo >= 100 ) {
13679 if(sec >= 0) time = 600*time + 10*sec; else
13680 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
13682 score = score >= 0 ? score*100 + score_lo : score*100 - score_lo;
13684 /* [HGM] PV time: now locate end of PV info */
13685 while( *++sep >= '0' && *sep <= '9'); // strip depth
13687 while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
13689 while( *++sep >= '0' && *sep <= '9'); // strip seconds
13691 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
13692 while(*sep == ' ') sep++;
13703 pvInfoList[index-1].depth = depth;
13704 pvInfoList[index-1].score = score;
13705 pvInfoList[index-1].time = 10*time; // centi-sec
13706 if(*sep == '}') *sep = 0; else *--sep = '{';
13707 if(p != text) { while(*p++ = *sep++); sep = text; } // squeeze out space between PV and comment, and return both
13713 SendToProgram(message, cps)
13715 ChessProgramState *cps;
13717 int count, outCount, error;
13720 if (cps->pr == NULL) return;
13723 if (appData.debugMode) {
13726 fprintf(debugFP, "%ld >%-6s: %s",
13727 SubtractTimeMarks(&now, &programStartTime),
13728 cps->which, message);
13731 count = strlen(message);
13732 outCount = OutputToProcess(cps->pr, message, count, &error);
13733 if (outCount < count && !exiting
13734 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
13735 snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
13736 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
13737 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
13738 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
13739 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
13741 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
13743 gameInfo.resultDetails = StrSave(buf);
13745 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
13750 ReceiveFromProgram(isr, closure, message, count, error)
13751 InputSourceRef isr;
13759 ChessProgramState *cps = (ChessProgramState *)closure;
13761 if (isr != cps->isr) return; /* Killed intentionally */
13764 snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
13765 _(cps->which), cps->program);
13766 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
13767 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
13768 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
13769 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
13771 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
13773 gameInfo.resultDetails = StrSave(buf);
13775 RemoveInputSource(cps->isr);
13776 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
13778 snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
13779 _(cps->which), cps->program);
13780 RemoveInputSource(cps->isr);
13782 /* [AS] Program is misbehaving badly... kill it */
13783 if( count == -2 ) {
13784 DestroyChildProcess( cps->pr, 9 );
13788 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
13793 if ((end_str = strchr(message, '\r')) != NULL)
13794 *end_str = NULLCHAR;
13795 if ((end_str = strchr(message, '\n')) != NULL)
13796 *end_str = NULLCHAR;
13798 if (appData.debugMode) {
13799 TimeMark now; int print = 1;
13800 char *quote = ""; char c; int i;
13802 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
13803 char start = message[0];
13804 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
13805 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
13806 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
13807 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
13808 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
13809 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
13810 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
13811 sscanf(message, "setboard %c", &c)!=1 && sscanf(message, "setup %c", &c)!=1 &&
13812 sscanf(message, "hint: %c", &c)!=1 &&
13813 sscanf(message, "pong %c", &c)!=1 && start != '#') {
13814 quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
13815 print = (appData.engineComments >= 2);
13817 message[0] = start; // restore original message
13821 fprintf(debugFP, "%ld <%-6s: %s%s\n",
13822 SubtractTimeMarks(&now, &programStartTime), cps->which,
13828 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
13829 if (appData.icsEngineAnalyze) {
13830 if (strstr(message, "whisper") != NULL ||
13831 strstr(message, "kibitz") != NULL ||
13832 strstr(message, "tellics") != NULL) return;
13835 HandleMachineMove(message, cps);
13840 SendTimeControl(cps, mps, tc, inc, sd, st)
13841 ChessProgramState *cps;
13842 int mps, inc, sd, st;
13848 if( timeControl_2 > 0 ) {
13849 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
13850 tc = timeControl_2;
13853 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
13854 inc /= cps->timeOdds;
13855 st /= cps->timeOdds;
13857 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
13860 /* Set exact time per move, normally using st command */
13861 if (cps->stKludge) {
13862 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
13864 if (seconds == 0) {
13865 snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
13867 snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
13870 snprintf(buf, MSG_SIZ, "st %d\n", st);
13873 /* Set conventional or incremental time control, using level command */
13874 if (seconds == 0) {
13875 /* Note old gnuchess bug -- minutes:seconds used to not work.
13876 Fixed in later versions, but still avoid :seconds
13877 when seconds is 0. */
13878 snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
13880 snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
13881 seconds, inc/1000.);
13884 SendToProgram(buf, cps);
13886 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
13887 /* Orthogonally, limit search to given depth */
13889 if (cps->sdKludge) {
13890 snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
13892 snprintf(buf, MSG_SIZ, "sd %d\n", sd);
13894 SendToProgram(buf, cps);
13897 if(cps->nps >= 0) { /* [HGM] nps */
13898 if(cps->supportsNPS == FALSE)
13899 cps->nps = -1; // don't use if engine explicitly says not supported!
13901 snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
13902 SendToProgram(buf, cps);
13907 ChessProgramState *WhitePlayer()
13908 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
13910 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
13911 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
13917 SendTimeRemaining(cps, machineWhite)
13918 ChessProgramState *cps;
13919 int /*boolean*/ machineWhite;
13921 char message[MSG_SIZ];
13924 /* Note: this routine must be called when the clocks are stopped
13925 or when they have *just* been set or switched; otherwise
13926 it will be off by the time since the current tick started.
13928 if (machineWhite) {
13929 time = whiteTimeRemaining / 10;
13930 otime = blackTimeRemaining / 10;
13932 time = blackTimeRemaining / 10;
13933 otime = whiteTimeRemaining / 10;
13935 /* [HGM] translate opponent's time by time-odds factor */
13936 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
13937 if (appData.debugMode) {
13938 fprintf(debugFP, "time odds: %f %f \n", cps->timeOdds, cps->other->timeOdds);
13941 if (time <= 0) time = 1;
13942 if (otime <= 0) otime = 1;
13944 snprintf(message, MSG_SIZ, "time %ld\n", time);
13945 SendToProgram(message, cps);
13947 snprintf(message, MSG_SIZ, "otim %ld\n", otime);
13948 SendToProgram(message, cps);
13952 BoolFeature(p, name, loc, cps)
13956 ChessProgramState *cps;
13959 int len = strlen(name);
13962 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
13964 sscanf(*p, "%d", &val);
13966 while (**p && **p != ' ')
13968 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
13969 SendToProgram(buf, cps);
13976 IntFeature(p, name, loc, cps)
13980 ChessProgramState *cps;
13983 int len = strlen(name);
13984 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
13986 sscanf(*p, "%d", loc);
13987 while (**p && **p != ' ') (*p)++;
13988 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
13989 SendToProgram(buf, cps);
13996 StringFeature(p, name, loc, cps)
14000 ChessProgramState *cps;
14003 int len = strlen(name);
14004 if (strncmp((*p), name, len) == 0
14005 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
14007 sscanf(*p, "%[^\"]", loc);
14008 while (**p && **p != '\"') (*p)++;
14009 if (**p == '\"') (*p)++;
14010 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
14011 SendToProgram(buf, cps);
14018 ParseOption(Option *opt, ChessProgramState *cps)
14019 // [HGM] options: process the string that defines an engine option, and determine
14020 // name, type, default value, and allowed value range
14022 char *p, *q, buf[MSG_SIZ];
14023 int n, min = (-1)<<31, max = 1<<31, def;
14025 if(p = strstr(opt->name, " -spin ")) {
14026 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
14027 if(max < min) max = min; // enforce consistency
14028 if(def < min) def = min;
14029 if(def > max) def = max;
14034 } else if((p = strstr(opt->name, " -slider "))) {
14035 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
14036 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
14037 if(max < min) max = min; // enforce consistency
14038 if(def < min) def = min;
14039 if(def > max) def = max;
14043 opt->type = Spin; // Slider;
14044 } else if((p = strstr(opt->name, " -string "))) {
14045 opt->textValue = p+9;
14046 opt->type = TextBox;
14047 } else if((p = strstr(opt->name, " -file "))) {
14048 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
14049 opt->textValue = p+7;
14050 opt->type = FileName; // FileName;
14051 } else if((p = strstr(opt->name, " -path "))) {
14052 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
14053 opt->textValue = p+7;
14054 opt->type = PathName; // PathName;
14055 } else if(p = strstr(opt->name, " -check ")) {
14056 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
14057 opt->value = (def != 0);
14058 opt->type = CheckBox;
14059 } else if(p = strstr(opt->name, " -combo ")) {
14060 opt->textValue = (char*) (&cps->comboList[cps->comboCnt]); // cheat with pointer type
14061 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
14062 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
14063 opt->value = n = 0;
14064 while(q = StrStr(q, " /// ")) {
14065 n++; *q = 0; // count choices, and null-terminate each of them
14067 if(*q == '*') { // remember default, which is marked with * prefix
14071 cps->comboList[cps->comboCnt++] = q;
14073 cps->comboList[cps->comboCnt++] = NULL;
14075 opt->type = ComboBox;
14076 } else if(p = strstr(opt->name, " -button")) {
14077 opt->type = Button;
14078 } else if(p = strstr(opt->name, " -save")) {
14079 opt->type = SaveButton;
14080 } else return FALSE;
14081 *p = 0; // terminate option name
14082 // now look if the command-line options define a setting for this engine option.
14083 if(cps->optionSettings && cps->optionSettings[0])
14084 p = strstr(cps->optionSettings, opt->name); else p = NULL;
14085 if(p && (p == cps->optionSettings || p[-1] == ',')) {
14086 snprintf(buf, MSG_SIZ, "option %s", p);
14087 if(p = strstr(buf, ",")) *p = 0;
14088 if(q = strchr(buf, '=')) switch(opt->type) {
14090 for(n=0; n<opt->max; n++)
14091 if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
14094 safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
14098 opt->value = atoi(q+1);
14103 SendToProgram(buf, cps);
14109 FeatureDone(cps, val)
14110 ChessProgramState* cps;
14113 DelayedEventCallback cb = GetDelayedEvent();
14114 if ((cb == InitBackEnd3 && cps == &first) ||
14115 (cb == SettingsMenuIfReady && cps == &second) ||
14116 (cb == TwoMachinesEventIfReady && cps == &second)) {
14117 CancelDelayedEvent();
14118 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
14120 cps->initDone = val;
14123 /* Parse feature command from engine */
14125 ParseFeatures(args, cps)
14127 ChessProgramState *cps;
14135 while (*p == ' ') p++;
14136 if (*p == NULLCHAR) return;
14138 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
14139 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
14140 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
14141 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
14142 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
14143 if (BoolFeature(&p, "reuse", &val, cps)) {
14144 /* Engine can disable reuse, but can't enable it if user said no */
14145 if (!val) cps->reuse = FALSE;
14148 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
14149 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
14150 if (gameMode == TwoMachinesPlay) {
14151 DisplayTwoMachinesTitle();
14157 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
14158 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
14159 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
14160 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
14161 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
14162 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
14163 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
14164 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
14165 if (BoolFeature(&p, "pause", &val, cps)) continue; /* unused at present */
14166 if (IntFeature(&p, "done", &val, cps)) {
14167 FeatureDone(cps, val);
14170 /* Added by Tord: */
14171 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
14172 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
14173 /* End of additions by Tord */
14175 /* [HGM] added features: */
14176 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
14177 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
14178 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
14179 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
14180 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
14181 if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
14182 if (StringFeature(&p, "option", &(cps->option[cps->nrOptions].name), cps)) {
14183 if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
14184 snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
14185 SendToProgram(buf, cps);
14188 if(cps->nrOptions >= MAX_OPTIONS) {
14190 snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
14191 DisplayError(buf, 0);
14195 /* End of additions by HGM */
14197 /* unknown feature: complain and skip */
14199 while (*q && *q != '=') q++;
14200 snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
14201 SendToProgram(buf, cps);
14207 while (*p && *p != '\"') p++;
14208 if (*p == '\"') p++;
14210 while (*p && *p != ' ') p++;
14218 PeriodicUpdatesEvent(newState)
14221 if (newState == appData.periodicUpdates)
14224 appData.periodicUpdates=newState;
14226 /* Display type changes, so update it now */
14227 // DisplayAnalysis();
14229 /* Get the ball rolling again... */
14231 AnalysisPeriodicEvent(1);
14232 StartAnalysisClock();
14237 PonderNextMoveEvent(newState)
14240 if (newState == appData.ponderNextMove) return;
14241 if (gameMode == EditPosition) EditPositionDone(TRUE);
14243 SendToProgram("hard\n", &first);
14244 if (gameMode == TwoMachinesPlay) {
14245 SendToProgram("hard\n", &second);
14248 SendToProgram("easy\n", &first);
14249 thinkOutput[0] = NULLCHAR;
14250 if (gameMode == TwoMachinesPlay) {
14251 SendToProgram("easy\n", &second);
14254 appData.ponderNextMove = newState;
14258 NewSettingEvent(option, feature, command, value)
14260 int option, value, *feature;
14264 if (gameMode == EditPosition) EditPositionDone(TRUE);
14265 snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
14266 if(feature == NULL || *feature) SendToProgram(buf, &first);
14267 if (gameMode == TwoMachinesPlay) {
14268 if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
14273 ShowThinkingEvent()
14274 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
14276 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
14277 int newState = appData.showThinking
14278 // [HGM] thinking: other features now need thinking output as well
14279 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
14281 if (oldState == newState) return;
14282 oldState = newState;
14283 if (gameMode == EditPosition) EditPositionDone(TRUE);
14285 SendToProgram("post\n", &first);
14286 if (gameMode == TwoMachinesPlay) {
14287 SendToProgram("post\n", &second);
14290 SendToProgram("nopost\n", &first);
14291 thinkOutput[0] = NULLCHAR;
14292 if (gameMode == TwoMachinesPlay) {
14293 SendToProgram("nopost\n", &second);
14296 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
14300 AskQuestionEvent(title, question, replyPrefix, which)
14301 char *title; char *question; char *replyPrefix; char *which;
14303 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
14304 if (pr == NoProc) return;
14305 AskQuestion(title, question, replyPrefix, pr);
14309 TypeInEvent(char firstChar)
14311 if ((gameMode == BeginningOfGame && !appData.icsActive) ||
\r
14312 gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
\r
14313 gameMode == AnalyzeMode || gameMode == EditGame ||
\r
14314 gameMode == EditPosition || gameMode == IcsExamining ||
\r
14315 gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
\r
14316 isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
\r
14317 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
\r
14318 gameMode == IcsObserving || gameMode == TwoMachinesPlay ) ||
\r
14319 gameMode == Training) PopUpMoveDialog(firstChar);
14323 TypeInDoneEvent(char *move)
14326 int n, fromX, fromY, toX, toY;
14328 ChessMove moveType;
\r
14331 if(gameMode == EditPosition && ParseFEN(board, &n, move) ) {
\r
14332 EditPositionPasteFEN(move);
\r
14335 // [HGM] movenum: allow move number to be typed in any mode
\r
14336 if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
\r
14337 ToNrEvent(2*n-1);
\r
14341 if (gameMode != EditGame && currentMove != forwardMostMove &&
\r
14342 gameMode != Training) {
\r
14343 DisplayMoveError(_("Displayed move is not current"));
\r
14345 int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
\r
14346 &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
\r
14347 if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
\r
14348 if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
\r
14349 &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
\r
14350 UserMoveEvent(fromX, fromY, toX, toY, promoChar);
\r
14352 DisplayMoveError(_("Could not parse move"));
\r
14358 DisplayMove(moveNumber)
14361 char message[MSG_SIZ];
14363 char cpThinkOutput[MSG_SIZ];
14365 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
14367 if (moveNumber == forwardMostMove - 1 ||
14368 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14370 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
14372 if (strchr(cpThinkOutput, '\n')) {
14373 *strchr(cpThinkOutput, '\n') = NULLCHAR;
14376 *cpThinkOutput = NULLCHAR;
14379 /* [AS] Hide thinking from human user */
14380 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
14381 *cpThinkOutput = NULLCHAR;
14382 if( thinkOutput[0] != NULLCHAR ) {
14385 for( i=0; i<=hiddenThinkOutputState; i++ ) {
14386 cpThinkOutput[i] = '.';
14388 cpThinkOutput[i] = NULLCHAR;
14389 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
14393 if (moveNumber == forwardMostMove - 1 &&
14394 gameInfo.resultDetails != NULL) {
14395 if (gameInfo.resultDetails[0] == NULLCHAR) {
14396 snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
14398 snprintf(res, MSG_SIZ, " {%s} %s",
14399 T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
14405 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
14406 DisplayMessage(res, cpThinkOutput);
14408 snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
14409 WhiteOnMove(moveNumber) ? " " : ".. ",
14410 parseList[moveNumber], res);
14411 DisplayMessage(message, cpThinkOutput);
14416 DisplayComment(moveNumber, text)
14420 char title[MSG_SIZ];
14421 char buf[8000]; // comment can be long!
14424 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
14425 safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
14427 snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
14428 WhiteOnMove(moveNumber) ? " " : ".. ",
14429 parseList[moveNumber]);
14431 // [HGM] PV info: display PV info together with (or as) comment
14432 if(moveNumber >= 0 && (depth = pvInfoList[moveNumber].depth) > 0) {
14433 if(text == NULL) text = "";
14434 score = pvInfoList[moveNumber].score;
14435 snprintf(buf,sizeof(buf)/sizeof(buf[0]), "%s%.2f/%d %d\n%s", score>0 ? "+" : "", score/100.,
14436 depth, (pvInfoList[moveNumber].time+50)/100, text);
14439 if (text != NULL && (appData.autoDisplayComment || commentUp))
14440 CommentPopUp(title, text);
14443 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
14444 * might be busy thinking or pondering. It can be omitted if your
14445 * gnuchess is configured to stop thinking immediately on any user
14446 * input. However, that gnuchess feature depends on the FIONREAD
14447 * ioctl, which does not work properly on some flavors of Unix.
14451 ChessProgramState *cps;
14454 if (!cps->useSigint) return;
14455 if (appData.noChessProgram || (cps->pr == NoProc)) return;
14456 switch (gameMode) {
14457 case MachinePlaysWhite:
14458 case MachinePlaysBlack:
14459 case TwoMachinesPlay:
14460 case IcsPlayingWhite:
14461 case IcsPlayingBlack:
14464 /* Skip if we know it isn't thinking */
14465 if (!cps->maybeThinking) return;
14466 if (appData.debugMode)
14467 fprintf(debugFP, "Interrupting %s\n", cps->which);
14468 InterruptChildProcess(cps->pr);
14469 cps->maybeThinking = FALSE;
14474 #endif /*ATTENTION*/
14480 if (whiteTimeRemaining <= 0) {
14483 if (appData.icsActive) {
14484 if (appData.autoCallFlag &&
14485 gameMode == IcsPlayingBlack && !blackFlag) {
14486 SendToICS(ics_prefix);
14487 SendToICS("flag\n");
14491 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
14493 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
14494 if (appData.autoCallFlag) {
14495 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
14502 if (blackTimeRemaining <= 0) {
14505 if (appData.icsActive) {
14506 if (appData.autoCallFlag &&
14507 gameMode == IcsPlayingWhite && !whiteFlag) {
14508 SendToICS(ics_prefix);
14509 SendToICS("flag\n");
14513 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
14515 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
14516 if (appData.autoCallFlag) {
14517 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
14530 if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
14531 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
14534 * add time to clocks when time control is achieved ([HGM] now also used for increment)
14536 if ( !WhiteOnMove(forwardMostMove) ) {
14537 /* White made time control */
14538 lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
14539 whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
14540 /* [HGM] time odds: correct new time quota for time odds! */
14541 / WhitePlayer()->timeOdds;
14542 lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
14544 lastBlack -= blackTimeRemaining;
14545 /* Black made time control */
14546 blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
14547 / WhitePlayer()->other->timeOdds;
14548 lastWhite = whiteTimeRemaining;
14553 DisplayBothClocks()
14555 int wom = gameMode == EditPosition ?
14556 !blackPlaysFirst : WhiteOnMove(currentMove);
14557 DisplayWhiteClock(whiteTimeRemaining, wom);
14558 DisplayBlackClock(blackTimeRemaining, !wom);
14562 /* Timekeeping seems to be a portability nightmare. I think everyone
14563 has ftime(), but I'm really not sure, so I'm including some ifdefs
14564 to use other calls if you don't. Clocks will be less accurate if
14565 you have neither ftime nor gettimeofday.
14568 /* VS 2008 requires the #include outside of the function */
14569 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
14570 #include <sys/timeb.h>
14573 /* Get the current time as a TimeMark */
14578 #if HAVE_GETTIMEOFDAY
14580 struct timeval timeVal;
14581 struct timezone timeZone;
14583 gettimeofday(&timeVal, &timeZone);
14584 tm->sec = (long) timeVal.tv_sec;
14585 tm->ms = (int) (timeVal.tv_usec / 1000L);
14587 #else /*!HAVE_GETTIMEOFDAY*/
14590 // include <sys/timeb.h> / moved to just above start of function
14591 struct timeb timeB;
14594 tm->sec = (long) timeB.time;
14595 tm->ms = (int) timeB.millitm;
14597 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
14598 tm->sec = (long) time(NULL);
14604 /* Return the difference in milliseconds between two
14605 time marks. We assume the difference will fit in a long!
14608 SubtractTimeMarks(tm2, tm1)
14609 TimeMark *tm2, *tm1;
14611 return 1000L*(tm2->sec - tm1->sec) +
14612 (long) (tm2->ms - tm1->ms);
14617 * Code to manage the game clocks.
14619 * In tournament play, black starts the clock and then white makes a move.
14620 * We give the human user a slight advantage if he is playing white---the
14621 * clocks don't run until he makes his first move, so it takes zero time.
14622 * Also, we don't account for network lag, so we could get out of sync
14623 * with GNU Chess's clock -- but then, referees are always right.
14626 static TimeMark tickStartTM;
14627 static long intendedTickLength;
14630 NextTickLength(timeRemaining)
14631 long timeRemaining;
14633 long nominalTickLength, nextTickLength;
14635 if (timeRemaining > 0L && timeRemaining <= 10000L)
14636 nominalTickLength = 100L;
14638 nominalTickLength = 1000L;
14639 nextTickLength = timeRemaining % nominalTickLength;
14640 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
14642 return nextTickLength;
14645 /* Adjust clock one minute up or down */
14647 AdjustClock(Boolean which, int dir)
14649 if(which) blackTimeRemaining += 60000*dir;
14650 else whiteTimeRemaining += 60000*dir;
14651 DisplayBothClocks();
14654 /* Stop clocks and reset to a fresh time control */
14658 (void) StopClockTimer();
14659 if (appData.icsActive) {
14660 whiteTimeRemaining = blackTimeRemaining = 0;
14661 } else if (searchTime) {
14662 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
14663 blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
14664 } else { /* [HGM] correct new time quote for time odds */
14665 whiteTC = blackTC = fullTimeControlString;
14666 whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
14667 blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
14669 if (whiteFlag || blackFlag) {
14671 whiteFlag = blackFlag = FALSE;
14673 lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
14674 DisplayBothClocks();
14677 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
14679 /* Decrement running clock by amount of time that has passed */
14683 long timeRemaining;
14684 long lastTickLength, fudge;
14687 if (!appData.clockMode) return;
14688 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
14692 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14694 /* Fudge if we woke up a little too soon */
14695 fudge = intendedTickLength - lastTickLength;
14696 if (fudge < 0 || fudge > FUDGE) fudge = 0;
14698 if (WhiteOnMove(forwardMostMove)) {
14699 if(whiteNPS >= 0) lastTickLength = 0;
14700 timeRemaining = whiteTimeRemaining -= lastTickLength;
14701 if(timeRemaining < 0 && !appData.icsActive) {
14702 GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
14703 if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
14704 whiteStartMove = forwardMostMove; whiteTC = nextSession;
14705 lastWhite= timeRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
14708 DisplayWhiteClock(whiteTimeRemaining - fudge,
14709 WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
14711 if(blackNPS >= 0) lastTickLength = 0;
14712 timeRemaining = blackTimeRemaining -= lastTickLength;
14713 if(timeRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
14714 GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
14716 blackStartMove = forwardMostMove;
14717 lastBlack = timeRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
14720 DisplayBlackClock(blackTimeRemaining - fudge,
14721 !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
14723 if (CheckFlags()) return;
14726 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
14727 StartClockTimer(intendedTickLength);
14729 /* if the time remaining has fallen below the alarm threshold, sound the
14730 * alarm. if the alarm has sounded and (due to a takeback or time control
14731 * with increment) the time remaining has increased to a level above the
14732 * threshold, reset the alarm so it can sound again.
14735 if (appData.icsActive && appData.icsAlarm) {
14737 /* make sure we are dealing with the user's clock */
14738 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
14739 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
14742 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
14743 alarmSounded = FALSE;
14744 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
14746 alarmSounded = TRUE;
14752 /* A player has just moved, so stop the previously running
14753 clock and (if in clock mode) start the other one.
14754 We redisplay both clocks in case we're in ICS mode, because
14755 ICS gives us an update to both clocks after every move.
14756 Note that this routine is called *after* forwardMostMove
14757 is updated, so the last fractional tick must be subtracted
14758 from the color that is *not* on move now.
14761 SwitchClocks(int newMoveNr)
14763 long lastTickLength;
14765 int flagged = FALSE;
14769 if (StopClockTimer() && appData.clockMode) {
14770 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14771 if (!WhiteOnMove(forwardMostMove)) {
14772 if(blackNPS >= 0) lastTickLength = 0;
14773 blackTimeRemaining -= lastTickLength;
14774 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
14775 // if(pvInfoList[forwardMostMove].time == -1)
14776 pvInfoList[forwardMostMove].time = // use GUI time
14777 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
14779 if(whiteNPS >= 0) lastTickLength = 0;
14780 whiteTimeRemaining -= lastTickLength;
14781 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
14782 // if(pvInfoList[forwardMostMove].time == -1)
14783 pvInfoList[forwardMostMove].time =
14784 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
14786 flagged = CheckFlags();
14788 forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
14789 CheckTimeControl();
14791 if (flagged || !appData.clockMode) return;
14793 switch (gameMode) {
14794 case MachinePlaysBlack:
14795 case MachinePlaysWhite:
14796 case BeginningOfGame:
14797 if (pausing) return;
14801 case PlayFromGameFile:
14809 if (searchTime) { // [HGM] st: set clock of player that has to move to max time
14810 if(WhiteOnMove(forwardMostMove))
14811 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
14812 else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
14816 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
14817 whiteTimeRemaining : blackTimeRemaining);
14818 StartClockTimer(intendedTickLength);
14822 /* Stop both clocks */
14826 long lastTickLength;
14829 if (!StopClockTimer()) return;
14830 if (!appData.clockMode) return;
14834 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14835 if (WhiteOnMove(forwardMostMove)) {
14836 if(whiteNPS >= 0) lastTickLength = 0;
14837 whiteTimeRemaining -= lastTickLength;
14838 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
14840 if(blackNPS >= 0) lastTickLength = 0;
14841 blackTimeRemaining -= lastTickLength;
14842 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
14847 /* Start clock of player on move. Time may have been reset, so
14848 if clock is already running, stop and restart it. */
14852 (void) StopClockTimer(); /* in case it was running already */
14853 DisplayBothClocks();
14854 if (CheckFlags()) return;
14856 if (!appData.clockMode) return;
14857 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
14859 GetTimeMark(&tickStartTM);
14860 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
14861 whiteTimeRemaining : blackTimeRemaining);
14863 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
14864 whiteNPS = blackNPS = -1;
14865 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
14866 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
14867 whiteNPS = first.nps;
14868 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
14869 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
14870 blackNPS = first.nps;
14871 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
14872 whiteNPS = second.nps;
14873 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
14874 blackNPS = second.nps;
14875 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
14877 StartClockTimer(intendedTickLength);
14884 long second, minute, hour, day;
14886 static char buf[32];
14888 if (ms > 0 && ms <= 9900) {
14889 /* convert milliseconds to tenths, rounding up */
14890 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
14892 snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
14896 /* convert milliseconds to seconds, rounding up */
14897 /* use floating point to avoid strangeness of integer division
14898 with negative dividends on many machines */
14899 second = (long) floor(((double) (ms + 999L)) / 1000.0);
14906 day = second / (60 * 60 * 24);
14907 second = second % (60 * 60 * 24);
14908 hour = second / (60 * 60);
14909 second = second % (60 * 60);
14910 minute = second / 60;
14911 second = second % 60;
14914 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ",
14915 sign, day, hour, minute, second);
14917 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
14919 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second);
14926 * This is necessary because some C libraries aren't ANSI C compliant yet.
14929 StrStr(string, match)
14930 char *string, *match;
14934 length = strlen(match);
14936 for (i = strlen(string) - length; i >= 0; i--, string++)
14937 if (!strncmp(match, string, length))
14944 StrCaseStr(string, match)
14945 char *string, *match;
14949 length = strlen(match);
14951 for (i = strlen(string) - length; i >= 0; i--, string++) {
14952 for (j = 0; j < length; j++) {
14953 if (ToLower(match[j]) != ToLower(string[j]))
14956 if (j == length) return string;
14970 c1 = ToLower(*s1++);
14971 c2 = ToLower(*s2++);
14972 if (c1 > c2) return 1;
14973 if (c1 < c2) return -1;
14974 if (c1 == NULLCHAR) return 0;
14983 return isupper(c) ? tolower(c) : c;
14991 return islower(c) ? toupper(c) : c;
14993 #endif /* !_amigados */
15001 if ((ret = (char *) malloc(strlen(s) + 1)))
15003 safeStrCpy(ret, s, strlen(s)+1);
15009 StrSavePtr(s, savePtr)
15010 char *s, **savePtr;
15015 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
15016 safeStrCpy(*savePtr, s, strlen(s)+1);
15028 clock = time((time_t *)NULL);
15029 tm = localtime(&clock);
15030 snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
15031 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
15032 return StrSave(buf);
15037 PositionToFEN(move, overrideCastling)
15039 char *overrideCastling;
15041 int i, j, fromX, fromY, toX, toY;
15048 whiteToPlay = (gameMode == EditPosition) ?
15049 !blackPlaysFirst : (move % 2 == 0);
15052 /* Piece placement data */
15053 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
15055 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
15056 if (boards[move][i][j] == EmptySquare) {
15058 } else { ChessSquare piece = boards[move][i][j];
15059 if (emptycount > 0) {
15060 if(emptycount<10) /* [HGM] can be >= 10 */
15061 *p++ = '0' + emptycount;
15062 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
15065 if(PieceToChar(piece) == '+') {
15066 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
15068 piece = (ChessSquare)(DEMOTED piece);
15070 *p++ = PieceToChar(piece);
15072 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
15073 p[-1] = PieceToChar((ChessSquare)(DEMOTED piece));
15078 if (emptycount > 0) {
15079 if(emptycount<10) /* [HGM] can be >= 10 */
15080 *p++ = '0' + emptycount;
15081 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
15088 /* [HGM] print Crazyhouse or Shogi holdings */
15089 if( gameInfo.holdingsWidth ) {
15090 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
15092 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
15093 piece = boards[move][i][BOARD_WIDTH-1];
15094 if( piece != EmptySquare )
15095 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
15096 *p++ = PieceToChar(piece);
15098 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
15099 piece = boards[move][BOARD_HEIGHT-i-1][0];
15100 if( piece != EmptySquare )
15101 for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
15102 *p++ = PieceToChar(piece);
15105 if( q == p ) *p++ = '-';
15111 *p++ = whiteToPlay ? 'w' : 'b';
15114 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
15115 while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' '; else --p;
15117 if(nrCastlingRights) {
15119 if(gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) {
15120 /* [HGM] write directly from rights */
15121 if(boards[move][CASTLING][2] != NoRights &&
15122 boards[move][CASTLING][0] != NoRights )
15123 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
15124 if(boards[move][CASTLING][2] != NoRights &&
15125 boards[move][CASTLING][1] != NoRights )
15126 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
15127 if(boards[move][CASTLING][5] != NoRights &&
15128 boards[move][CASTLING][3] != NoRights )
15129 *p++ = boards[move][CASTLING][3] + AAA;
15130 if(boards[move][CASTLING][5] != NoRights &&
15131 boards[move][CASTLING][4] != NoRights )
15132 *p++ = boards[move][CASTLING][4] + AAA;
15135 /* [HGM] write true castling rights */
15136 if( nrCastlingRights == 6 ) {
15137 if(boards[move][CASTLING][0] == BOARD_RGHT-1 &&
15138 boards[move][CASTLING][2] != NoRights ) *p++ = 'K';
15139 if(boards[move][CASTLING][1] == BOARD_LEFT &&
15140 boards[move][CASTLING][2] != NoRights ) *p++ = 'Q';
15141 if(boards[move][CASTLING][3] == BOARD_RGHT-1 &&
15142 boards[move][CASTLING][5] != NoRights ) *p++ = 'k';
15143 if(boards[move][CASTLING][4] == BOARD_LEFT &&
15144 boards[move][CASTLING][5] != NoRights ) *p++ = 'q';
15147 if (q == p) *p++ = '-'; /* No castling rights */
15151 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
15152 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
15153 /* En passant target square */
15154 if (move > backwardMostMove) {
15155 fromX = moveList[move - 1][0] - AAA;
15156 fromY = moveList[move - 1][1] - ONE;
15157 toX = moveList[move - 1][2] - AAA;
15158 toY = moveList[move - 1][3] - ONE;
15159 if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
15160 toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
15161 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
15163 /* 2-square pawn move just happened */
15165 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
15169 } else if(move == backwardMostMove) {
15170 // [HGM] perhaps we should always do it like this, and forget the above?
15171 if((signed char)boards[move][EP_STATUS] >= 0) {
15172 *p++ = boards[move][EP_STATUS] + AAA;
15173 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
15184 /* [HGM] find reversible plies */
15185 { int i = 0, j=move;
15187 if (appData.debugMode) { int k;
15188 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
15189 for(k=backwardMostMove; k<=forwardMostMove; k++)
15190 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
15194 while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
15195 if( j == backwardMostMove ) i += initialRulePlies;
15196 sprintf(p, "%d ", i);
15197 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
15199 /* Fullmove number */
15200 sprintf(p, "%d", (move / 2) + 1);
15202 return StrSave(buf);
15206 ParseFEN(board, blackPlaysFirst, fen)
15208 int *blackPlaysFirst;
15218 /* [HGM] by default clear Crazyhouse holdings, if present */
15219 if(gameInfo.holdingsWidth) {
15220 for(i=0; i<BOARD_HEIGHT; i++) {
15221 board[i][0] = EmptySquare; /* black holdings */
15222 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
15223 board[i][1] = (ChessSquare) 0; /* black counts */
15224 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
15228 /* Piece placement data */
15229 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
15232 if (*p == '/' || *p == ' ' || (*p == '[' && i == 0) ) {
15233 if (*p == '/') p++;
15234 emptycount = gameInfo.boardWidth - j;
15235 while (emptycount--)
15236 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
15238 #if(BOARD_FILES >= 10)
15239 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
15240 p++; emptycount=10;
15241 if (j + emptycount > gameInfo.boardWidth) return FALSE;
15242 while (emptycount--)
15243 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
15245 } else if (isdigit(*p)) {
15246 emptycount = *p++ - '0';
15247 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
15248 if (j + emptycount > gameInfo.boardWidth) return FALSE;
15249 while (emptycount--)
15250 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
15251 } else if (*p == '+' || isalpha(*p)) {
15252 if (j >= gameInfo.boardWidth) return FALSE;
15254 piece = CharToPiece(*++p);
15255 if(piece == EmptySquare) return FALSE; /* unknown piece */
15256 piece = (ChessSquare) (PROMOTED piece ); p++;
15257 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
15258 } else piece = CharToPiece(*p++);
15260 if(piece==EmptySquare) return FALSE; /* unknown piece */
15261 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
15262 piece = (ChessSquare) (PROMOTED piece);
15263 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
15266 board[i][(j++)+gameInfo.holdingsWidth] = piece;
15272 while (*p == '/' || *p == ' ') p++;
15274 /* [HGM] look for Crazyhouse holdings here */
15275 while(*p==' ') p++;
15276 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
15278 if(*p == '-' ) p++; /* empty holdings */ else {
15279 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
15280 /* if we would allow FEN reading to set board size, we would */
15281 /* have to add holdings and shift the board read so far here */
15282 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
15284 if((int) piece >= (int) BlackPawn ) {
15285 i = (int)piece - (int)BlackPawn;
15286 i = PieceToNumber((ChessSquare)i);
15287 if( i >= gameInfo.holdingsSize ) return FALSE;
15288 board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
15289 board[BOARD_HEIGHT-1-i][1]++; /* black counts */
15291 i = (int)piece - (int)WhitePawn;
15292 i = PieceToNumber((ChessSquare)i);
15293 if( i >= gameInfo.holdingsSize ) return FALSE;
15294 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
15295 board[i][BOARD_WIDTH-2]++; /* black holdings */
15302 while(*p == ' ') p++;
15306 if(appData.colorNickNames) {
15307 if( c == appData.colorNickNames[0] ) c = 'w'; else
15308 if( c == appData.colorNickNames[1] ) c = 'b';
15312 *blackPlaysFirst = FALSE;
15315 *blackPlaysFirst = TRUE;
15321 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
15322 /* return the extra info in global variiables */
15324 /* set defaults in case FEN is incomplete */
15325 board[EP_STATUS] = EP_UNKNOWN;
15326 for(i=0; i<nrCastlingRights; i++ ) {
15327 board[CASTLING][i] =
15328 gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom ? NoRights : initialRights[i];
15329 } /* assume possible unless obviously impossible */
15330 if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
15331 if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
15332 if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
15333 && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
15334 if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
15335 if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
15336 if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
15337 && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
15340 while(*p==' ') p++;
15341 if(nrCastlingRights) {
15342 if(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-') {
15343 /* castling indicator present, so default becomes no castlings */
15344 for(i=0; i<nrCastlingRights; i++ ) {
15345 board[CASTLING][i] = NoRights;
15348 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
15349 (gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) &&
15350 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
15351 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
15352 char c = *p++; int whiteKingFile=NoRights, blackKingFile=NoRights;
15354 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
15355 if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
15356 if(board[0 ][i] == WhiteKing) whiteKingFile = i;
15358 if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
15359 whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
15360 if(whiteKingFile == NoRights || board[0][whiteKingFile] != WhiteUnicorn
15361 && board[0][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
15362 if(blackKingFile == NoRights || board[BOARD_HEIGHT-1][blackKingFile] != BlackUnicorn
15363 && board[BOARD_HEIGHT-1][blackKingFile] != BlackKing) blackKingFile = NoRights;
15366 for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
15367 board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
15368 board[CASTLING][2] = whiteKingFile;
15371 for(i=BOARD_LEFT; i<BOARD_RGHT && board[0][i]!=WhiteRook && i<whiteKingFile; i++);
15372 board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
15373 board[CASTLING][2] = whiteKingFile;
15376 for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
15377 board[CASTLING][3] = i != blackKingFile ? i : NoRights;
15378 board[CASTLING][5] = blackKingFile;
15381 for(i=BOARD_LEFT; i<BOARD_RGHT && board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
15382 board[CASTLING][4] = i != blackKingFile ? i : NoRights;
15383 board[CASTLING][5] = blackKingFile;
15386 default: /* FRC castlings */
15387 if(c >= 'a') { /* black rights */
15388 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
15389 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
15390 if(i == BOARD_RGHT) break;
15391 board[CASTLING][5] = i;
15393 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
15394 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
15396 board[CASTLING][3] = c;
15398 board[CASTLING][4] = c;
15399 } else { /* white rights */
15400 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
15401 if(board[0][i] == WhiteKing) break;
15402 if(i == BOARD_RGHT) break;
15403 board[CASTLING][2] = i;
15404 c -= AAA - 'a' + 'A';
15405 if(board[0][c] >= WhiteKing) break;
15407 board[CASTLING][0] = c;
15409 board[CASTLING][1] = c;
15413 for(i=0; i<nrCastlingRights; i++)
15414 if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
15415 if (appData.debugMode) {
15416 fprintf(debugFP, "FEN castling rights:");
15417 for(i=0; i<nrCastlingRights; i++)
15418 fprintf(debugFP, " %d", board[CASTLING][i]);
15419 fprintf(debugFP, "\n");
15422 while(*p==' ') p++;
15425 /* read e.p. field in games that know e.p. capture */
15426 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
15427 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
15429 p++; board[EP_STATUS] = EP_NONE;
15431 char c = *p++ - AAA;
15433 if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
15434 if(*p >= '0' && *p <='9') p++;
15435 board[EP_STATUS] = c;
15440 if(sscanf(p, "%d", &i) == 1) {
15441 FENrulePlies = i; /* 50-move ply counter */
15442 /* (The move number is still ignored) */
15449 EditPositionPasteFEN(char *fen)
15452 Board initial_position;
15454 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
15455 DisplayError(_("Bad FEN position in clipboard"), 0);
15458 int savedBlackPlaysFirst = blackPlaysFirst;
15459 EditPositionEvent();
15460 blackPlaysFirst = savedBlackPlaysFirst;
15461 CopyBoard(boards[0], initial_position);
15462 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
15463 EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
15464 DisplayBothClocks();
15465 DrawPosition(FALSE, boards[currentMove]);
15470 static char cseq[12] = "\\ ";
15472 Boolean set_cont_sequence(char *new_seq)
15477 // handle bad attempts to set the sequence
15479 return 0; // acceptable error - no debug
15481 len = strlen(new_seq);
15482 ret = (len > 0) && (len < sizeof(cseq));
15484 safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
15485 else if (appData.debugMode)
15486 fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
15491 reformat a source message so words don't cross the width boundary. internal
15492 newlines are not removed. returns the wrapped size (no null character unless
15493 included in source message). If dest is NULL, only calculate the size required
15494 for the dest buffer. lp argument indicats line position upon entry, and it's
15495 passed back upon exit.
15497 int wrap(char *dest, char *src, int count, int width, int *lp)
15499 int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
15501 cseq_len = strlen(cseq);
15502 old_line = line = *lp;
15503 ansi = len = clen = 0;
15505 for (i=0; i < count; i++)
15507 if (src[i] == '\033')
15510 // if we hit the width, back up
15511 if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
15513 // store i & len in case the word is too long
15514 old_i = i, old_len = len;
15516 // find the end of the last word
15517 while (i && src[i] != ' ' && src[i] != '\n')
15523 // word too long? restore i & len before splitting it
15524 if ((old_i-i+clen) >= width)
15531 if (i && src[i-1] == ' ')
15534 if (src[i] != ' ' && src[i] != '\n')
15541 // now append the newline and continuation sequence
15546 strncpy(dest+len, cseq, cseq_len);
15554 dest[len] = src[i];
15558 if (src[i] == '\n')
15563 if (dest && appData.debugMode)
15565 fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
15566 count, width, line, len, *lp);
15567 show_bytes(debugFP, src, count);
15568 fprintf(debugFP, "\ndest: ");
15569 show_bytes(debugFP, dest, len);
15570 fprintf(debugFP, "\n");
15572 *lp = dest ? line : old_line;
15577 // [HGM] vari: routines for shelving variations
15580 PushTail(int firstMove, int lastMove)
15582 int i, j, nrMoves = lastMove - firstMove;
15584 if(appData.icsActive) { // only in local mode
15585 forwardMostMove = currentMove; // mimic old ICS behavior
15588 if(storedGames >= MAX_VARIATIONS-1) return;
15590 // push current tail of game on stack
15591 savedResult[storedGames] = gameInfo.result;
15592 savedDetails[storedGames] = gameInfo.resultDetails;
15593 gameInfo.resultDetails = NULL;
15594 savedFirst[storedGames] = firstMove;
15595 savedLast [storedGames] = lastMove;
15596 savedFramePtr[storedGames] = framePtr;
15597 framePtr -= nrMoves; // reserve space for the boards
15598 for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
15599 CopyBoard(boards[framePtr+i], boards[firstMove+i]);
15600 for(j=0; j<MOVE_LEN; j++)
15601 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
15602 for(j=0; j<2*MOVE_LEN; j++)
15603 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
15604 timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
15605 timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
15606 pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
15607 pvInfoList[firstMove+i-1].depth = 0;
15608 commentList[framePtr+i] = commentList[firstMove+i];
15609 commentList[firstMove+i] = NULL;
15613 forwardMostMove = firstMove; // truncate game so we can start variation
15614 if(storedGames == 1) GreyRevert(FALSE);
15618 PopTail(Boolean annotate)
15621 char buf[8000], moveBuf[20];
15623 if(appData.icsActive) return FALSE; // only in local mode
15624 if(!storedGames) return FALSE; // sanity
15625 CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
15628 ToNrEvent(savedFirst[storedGames]); // sets currentMove
15629 nrMoves = savedLast[storedGames] - currentMove;
15632 if(!WhiteOnMove(currentMove))
15633 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
15634 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
15635 for(i=currentMove; i<forwardMostMove; i++) {
15637 snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
15638 else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
15639 strcat(buf, moveBuf);
15640 if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
15641 if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
15645 for(i=1; i<=nrMoves; i++) { // copy last variation back
15646 CopyBoard(boards[currentMove+i], boards[framePtr+i]);
15647 for(j=0; j<MOVE_LEN; j++)
15648 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
15649 for(j=0; j<2*MOVE_LEN; j++)
15650 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
15651 timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
15652 timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
15653 pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
15654 if(commentList[currentMove+i]) free(commentList[currentMove+i]);
15655 commentList[currentMove+i] = commentList[framePtr+i];
15656 commentList[framePtr+i] = NULL;
15658 if(annotate) AppendComment(currentMove+1, buf, FALSE);
15659 framePtr = savedFramePtr[storedGames];
15660 gameInfo.result = savedResult[storedGames];
15661 if(gameInfo.resultDetails != NULL) {
15662 free(gameInfo.resultDetails);
15664 gameInfo.resultDetails = savedDetails[storedGames];
15665 forwardMostMove = currentMove + nrMoves;
15666 if(storedGames == 0) GreyRevert(TRUE);
15672 { // remove all shelved variations
15674 for(i=0; i<storedGames; i++) {
15675 if(savedDetails[i])
15676 free(savedDetails[i]);
15677 savedDetails[i] = NULL;
15679 for(i=framePtr; i<MAX_MOVES; i++) {
15680 if(commentList[i]) free(commentList[i]);
15681 commentList[i] = NULL;
15683 framePtr = MAX_MOVES-1;
15688 LoadVariation(int index, char *text)
15689 { // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
15690 char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
15691 int level = 0, move;
15693 if(gameMode != EditGame && gameMode != AnalyzeMode) return;
15694 // first find outermost bracketing variation
15695 while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
15696 if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
15697 if(*p == '{') wait = '}'; else
15698 if(*p == '[') wait = ']'; else
15699 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
15700 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
15702 if(*p == wait) wait = NULLCHAR; // closing ]} found
15705 if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
15706 if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
15707 end[1] = NULLCHAR; // clip off comment beyond variation
15708 ToNrEvent(currentMove-1);
15709 PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
15710 // kludge: use ParsePV() to append variation to game
15711 move = currentMove;
15712 ParsePV(start, TRUE);
15713 forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
15714 ClearPremoveHighlights();
15716 ToNrEvent(currentMove+1);