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 UnloadEngine(ChessProgramState *cps)
698 /* Kill off first chess program */
699 if (cps->isr != NULL)
700 RemoveInputSource(cps->isr);
703 if (cps->pr != NoProc) {
705 DoSleep( appData.delayBeforeQuit );
706 SendToProgram("quit\n", cps);
707 DoSleep( appData.delayAfterQuit );
708 DestroyChildProcess(cps->pr, cps->useSigterm);
714 ClearOptions(ChessProgramState *cps)
717 cps->nrOptions = cps->comboCnt = 0;
718 for(i=0; i<MAX_OPTIONS; i++) {
719 cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
720 cps->option[i].textValue = 0;
724 char *engineNames[] = {
729 InitEngine(ChessProgramState *cps, int n)
730 { // [HGM] all engine initialiation put in a function that does one engine
734 cps->which = engineNames[n];
735 cps->maybeThinking = FALSE;
739 cps->sendDrawOffers = 1;
741 cps->program = appData.chessProgram[n];
742 cps->host = appData.host[n];
743 cps->dir = appData.directory[n];
744 cps->initString = appData.engInitString[n];
745 cps->computerString = appData.computerString[n];
746 cps->useSigint = TRUE;
747 cps->useSigterm = TRUE;
748 cps->reuse = appData.reuse[n];
749 cps->nps = appData.NPS[n]; // [HGM] nps: copy nodes per second
750 cps->useSetboard = FALSE;
752 cps->usePing = FALSE;
755 cps->usePlayother = FALSE;
756 cps->useColors = TRUE;
757 cps->useUsermove = FALSE;
758 cps->sendICS = FALSE;
759 cps->sendName = appData.icsActive;
760 cps->sdKludge = FALSE;
761 cps->stKludge = FALSE;
762 TidyProgramName(cps->program, cps->host, cps->tidy);
764 safeStrCpy(cps->variants, appData.variant, MSG_SIZ);
765 cps->analysisSupport = 2; /* detect */
766 cps->analyzing = FALSE;
767 cps->initDone = FALSE;
769 /* New features added by Tord: */
770 cps->useFEN960 = FALSE;
771 cps->useOOCastle = TRUE;
772 /* End of new features added by Tord. */
773 cps->fenOverride = appData.fenOverride[n];
775 /* [HGM] time odds: set factor for each machine */
776 cps->timeOdds = appData.timeOdds[n];
778 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
779 cps->accumulateTC = appData.accumulateTC[n];
780 cps->maxNrOfSessions = 1;
784 cps->supportsNPS = UNKNOWN;
787 cps->optionSettings = appData.engOptions[n];
789 cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
790 cps->isUCI = appData.isUCI[n]; /* [AS] */
791 cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
793 if (appData.protocolVersion[n] > PROTOVER
794 || appData.protocolVersion[n] < 1)
799 len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
800 appData.protocolVersion[n]);
801 if( (len > MSG_SIZ) && appData.debugMode )
802 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
804 DisplayFatalError(buf, 0, 2);
808 cps->protocolVersion = appData.protocolVersion[n];
811 InitEngineUCI( installDir, cps ); // [HGM] moved here from winboard.c, to make available in xboard
817 int matched, min, sec;
819 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
820 startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
822 GetTimeMark(&programStartTime);
823 srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
826 programStats.ok_to_send = 1;
827 programStats.seen_stat = 0;
830 * Initialize game list
836 * Internet chess server status
838 if (appData.icsActive) {
839 appData.matchMode = FALSE;
840 appData.matchGames = 0;
842 appData.noChessProgram = !appData.zippyPlay;
844 appData.zippyPlay = FALSE;
845 appData.zippyTalk = FALSE;
846 appData.noChessProgram = TRUE;
848 if (*appData.icsHelper != NULLCHAR) {
849 appData.useTelnet = TRUE;
850 appData.telnetProgram = appData.icsHelper;
853 appData.zippyTalk = appData.zippyPlay = FALSE;
856 /* [AS] Initialize pv info list [HGM] and game state */
860 for( i=0; i<=framePtr; i++ ) {
861 pvInfoList[i].depth = -1;
862 boards[i][EP_STATUS] = EP_NONE;
863 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
868 * Parse timeControl resource
870 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
871 appData.movesPerSession)) {
873 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
874 DisplayFatalError(buf, 0, 2);
878 * Parse searchTime resource
880 if (*appData.searchTime != NULLCHAR) {
881 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
883 searchTime = min * 60;
884 } else if (matched == 2) {
885 searchTime = min * 60 + sec;
888 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
889 DisplayFatalError(buf, 0, 2);
893 /* [AS] Adjudication threshold */
894 adjudicateLossThreshold = appData.adjudicateLossThreshold;
896 InitEngine(&first, 0);
897 InitEngine(&second, 1);
900 if (appData.icsActive) {
901 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
902 } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
903 appData.clockMode = FALSE;
904 first.sendTime = second.sendTime = 0;
908 /* Override some settings from environment variables, for backward
909 compatibility. Unfortunately it's not feasible to have the env
910 vars just set defaults, at least in xboard. Ugh.
912 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
917 if (!appData.icsActive) {
921 /* Check for variants that are supported only in ICS mode,
922 or not at all. Some that are accepted here nevertheless
923 have bugs; see comments below.
925 VariantClass variant = StringToVariant(appData.variant);
927 case VariantBughouse: /* need four players and two boards */
928 case VariantKriegspiel: /* need to hide pieces and move details */
929 /* case VariantFischeRandom: (Fabien: moved below) */
930 len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
931 if( (len > MSG_SIZ) && appData.debugMode )
932 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
934 DisplayFatalError(buf, 0, 2);
938 case VariantLoadable:
948 len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
949 if( (len > MSG_SIZ) && appData.debugMode )
950 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
952 DisplayFatalError(buf, 0, 2);
955 case VariantXiangqi: /* [HGM] repetition rules not implemented */
956 case VariantFairy: /* [HGM] TestLegality definitely off! */
957 case VariantGothic: /* [HGM] should work */
958 case VariantCapablanca: /* [HGM] should work */
959 case VariantCourier: /* [HGM] initial forced moves not implemented */
960 case VariantShogi: /* [HGM] could still mate with pawn drop */
961 case VariantKnightmate: /* [HGM] should work */
962 case VariantCylinder: /* [HGM] untested */
963 case VariantFalcon: /* [HGM] untested */
964 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
965 offboard interposition not understood */
966 case VariantNormal: /* definitely works! */
967 case VariantWildCastle: /* pieces not automatically shuffled */
968 case VariantNoCastle: /* pieces not automatically shuffled */
969 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
970 case VariantLosers: /* should work except for win condition,
971 and doesn't know captures are mandatory */
972 case VariantSuicide: /* should work except for win condition,
973 and doesn't know captures are mandatory */
974 case VariantGiveaway: /* should work except for win condition,
975 and doesn't know captures are mandatory */
976 case VariantTwoKings: /* should work */
977 case VariantAtomic: /* should work except for win condition */
978 case Variant3Check: /* should work except for win condition */
979 case VariantShatranj: /* should work except for all win conditions */
980 case VariantMakruk: /* should work except for daw countdown */
981 case VariantBerolina: /* might work if TestLegality is off */
982 case VariantCapaRandom: /* should work */
983 case VariantJanus: /* should work */
984 case VariantSuper: /* experimental */
985 case VariantGreat: /* experimental, requires legality testing to be off */
986 case VariantSChess: /* S-Chess, should work */
987 case VariantSpartan: /* should work */
994 int NextIntegerFromString( char ** str, long * value )
999 while( *s == ' ' || *s == '\t' ) {
1005 if( *s >= '0' && *s <= '9' ) {
1006 while( *s >= '0' && *s <= '9' ) {
1007 *value = *value * 10 + (*s - '0');
1019 int NextTimeControlFromString( char ** str, long * value )
1022 int result = NextIntegerFromString( str, &temp );
1025 *value = temp * 60; /* Minutes */
1026 if( **str == ':' ) {
1028 result = NextIntegerFromString( str, &temp );
1029 *value += temp; /* Seconds */
1036 int NextSessionFromString( char ** str, int *moves, long * tc, long *inc, int *incType)
1037 { /* [HGM] routine added to read '+moves/time' for secondary time control. */
1038 int result = -1, type = 0; long temp, temp2;
1040 if(**str != ':') return -1; // old params remain in force!
1042 if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
1043 if( NextIntegerFromString( str, &temp ) ) return -1;
1044 if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
1047 /* time only: incremental or sudden-death time control */
1048 if(**str == '+') { /* increment follows; read it */
1050 if(**str == '!') type = *(*str)++; // Bronstein TC
1051 if(result = NextIntegerFromString( str, &temp2)) return -1;
1052 *inc = temp2 * 1000;
1053 if(**str == '.') { // read fraction of increment
1054 char *start = ++(*str);
1055 if(result = NextIntegerFromString( str, &temp2)) return -1;
1057 while(start++ < *str) temp2 /= 10;
1061 *moves = 0; *tc = temp * 1000; *incType = type;
1065 (*str)++; /* classical time control */
1066 result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
1077 int GetTimeQuota(int movenr, int lastUsed, char *tcString)
1078 { /* [HGM] get time to add from the multi-session time-control string */
1079 int incType, moves=1; /* kludge to force reading of first session */
1080 long time, increment;
1083 if(!*s) return 0; // empty TC string means we ran out of the last sudden-death version
1084 if(appData.debugMode) fprintf(debugFP, "TC string = '%s'\n", tcString);
1086 if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
1087 nextSession = s; suddenDeath = moves == 0 && increment == 0;
1088 if(appData.debugMode) fprintf(debugFP, "mps=%d tc=%d inc=%d\n", moves, (int) time, (int) increment);
1089 if(movenr == -1) return time; /* last move before new session */
1090 if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
1091 if(incType == '!' && lastUsed < increment) increment = lastUsed;
1092 if(!moves) return increment; /* current session is incremental */
1093 if(movenr >= 0) movenr -= moves; /* we already finished this session */
1094 } while(movenr >= -1); /* try again for next session */
1096 return 0; // no new time quota on this move
1100 ParseTimeControl(tc, ti, mps)
1107 char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
1110 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1111 if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
1112 sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
1116 snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
1118 snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
1121 snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
1123 snprintf(buf, MSG_SIZ, ":%s", mytc);
1125 fullTimeControlString = StrSave(buf); // this should now be in PGN format
1127 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1132 /* Parse second time control */
1135 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1143 timeControl_2 = tc2 * 1000;
1153 timeControl = tc1 * 1000;
1156 timeIncrement = ti * 1000; /* convert to ms */
1157 movesPerSession = 0;
1160 movesPerSession = mps;
1168 if (appData.debugMode) {
1169 fprintf(debugFP, "%s\n", programVersion);
1172 set_cont_sequence(appData.wrapContSeq);
1173 if (appData.matchGames > 0) {
1174 appData.matchMode = TRUE;
1175 } else if (appData.matchMode) {
1176 appData.matchGames = 1;
1178 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1179 appData.matchGames = appData.sameColorGames;
1180 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1181 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1182 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1185 if (appData.noChessProgram || first.protocolVersion == 1) {
1188 /* kludge: allow timeout for initial "feature" commands */
1190 DisplayMessage("", _("Starting chess program"));
1191 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1196 MatchEvent(int mode)
1197 { // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
1198 /* Set up machine vs. machine match */
1199 if (appData.noChessProgram) {
1200 DisplayFatalError(_("Can't have a match with no chess programs"),
1206 if (*appData.loadGameFile != NULLCHAR) {
1207 int index = appData.loadGameIndex; // [HGM] autoinc
1208 if(index<0) lastIndex = index = 1;
1209 if (!LoadGameFromFile(appData.loadGameFile,
1211 appData.loadGameFile, FALSE)) {
1212 DisplayFatalError(_("Bad game file"), 0, 1);
1215 } else if (*appData.loadPositionFile != NULLCHAR) {
1216 int index = appData.loadPositionIndex; // [HGM] autoinc
1217 if(index<0) lastIndex = index = 1;
1218 if (!LoadPositionFromFile(appData.loadPositionFile,
1220 appData.loadPositionFile)) {
1221 DisplayFatalError(_("Bad position file"), 0, 1);
1225 first.matchWins = second.matchWins = 0; // [HGM] match: needed in later matches
\r
1230 InitBackEnd3 P((void))
1232 GameMode initialMode;
1236 InitChessProgram(&first, startedFromSetupPosition);
1238 if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
1239 free(programVersion);
1240 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1241 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1244 if (appData.icsActive) {
1246 /* [DM] Make a console window if needed [HGM] merged ifs */
1252 if (*appData.icsCommPort != NULLCHAR)
1253 len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1254 appData.icsCommPort);
1256 len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1257 appData.icsHost, appData.icsPort);
1259 if( (len > MSG_SIZ) && appData.debugMode )
1260 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1262 DisplayFatalError(buf, err, 1);
1267 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1269 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1270 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1271 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1272 } else if (appData.noChessProgram) {
1278 if (*appData.cmailGameName != NULLCHAR) {
1280 OpenLoopback(&cmailPR);
1282 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1286 DisplayMessage("", "");
1287 if (StrCaseCmp(appData.initialMode, "") == 0) {
1288 initialMode = BeginningOfGame;
1289 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1290 initialMode = TwoMachinesPlay;
1291 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1292 initialMode = AnalyzeFile;
1293 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1294 initialMode = AnalyzeMode;
1295 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1296 initialMode = MachinePlaysWhite;
1297 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1298 initialMode = MachinePlaysBlack;
1299 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1300 initialMode = EditGame;
1301 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1302 initialMode = EditPosition;
1303 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1304 initialMode = Training;
1306 len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1307 if( (len > MSG_SIZ) && appData.debugMode )
1308 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1310 DisplayFatalError(buf, 0, 2);
1314 if (appData.matchMode) {
1316 } else if (*appData.cmailGameName != NULLCHAR) {
1317 /* Set up cmail mode */
1318 ReloadCmailMsgEvent(TRUE);
1320 /* Set up other modes */
1321 if (initialMode == AnalyzeFile) {
1322 if (*appData.loadGameFile == NULLCHAR) {
1323 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1327 if (*appData.loadGameFile != NULLCHAR) {
1328 (void) LoadGameFromFile(appData.loadGameFile,
1329 appData.loadGameIndex,
1330 appData.loadGameFile, TRUE);
1331 } else if (*appData.loadPositionFile != NULLCHAR) {
1332 (void) LoadPositionFromFile(appData.loadPositionFile,
1333 appData.loadPositionIndex,
1334 appData.loadPositionFile);
1335 /* [HGM] try to make self-starting even after FEN load */
1336 /* to allow automatic setup of fairy variants with wtm */
1337 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1338 gameMode = BeginningOfGame;
1339 setboardSpoiledMachineBlack = 1;
1341 /* [HGM] loadPos: make that every new game uses the setup */
1342 /* from file as long as we do not switch variant */
1343 if(!blackPlaysFirst) {
1344 startedFromPositionFile = TRUE;
1345 CopyBoard(filePosition, boards[0]);
1348 if (initialMode == AnalyzeMode) {
1349 if (appData.noChessProgram) {
1350 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1353 if (appData.icsActive) {
1354 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1358 } else if (initialMode == AnalyzeFile) {
1359 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1360 ShowThinkingEvent();
1362 AnalysisPeriodicEvent(1);
1363 } else if (initialMode == MachinePlaysWhite) {
1364 if (appData.noChessProgram) {
1365 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1369 if (appData.icsActive) {
1370 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1374 MachineWhiteEvent();
1375 } else if (initialMode == MachinePlaysBlack) {
1376 if (appData.noChessProgram) {
1377 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1381 if (appData.icsActive) {
1382 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1386 MachineBlackEvent();
1387 } else if (initialMode == TwoMachinesPlay) {
1388 if (appData.noChessProgram) {
1389 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1393 if (appData.icsActive) {
1394 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1399 } else if (initialMode == EditGame) {
1401 } else if (initialMode == EditPosition) {
1402 EditPositionEvent();
1403 } else if (initialMode == Training) {
1404 if (*appData.loadGameFile == NULLCHAR) {
1405 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1414 * Establish will establish a contact to a remote host.port.
1415 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1416 * used to talk to the host.
1417 * Returns 0 if okay, error code if not.
1424 if (*appData.icsCommPort != NULLCHAR) {
1425 /* Talk to the host through a serial comm port */
1426 return OpenCommPort(appData.icsCommPort, &icsPR);
1428 } else if (*appData.gateway != NULLCHAR) {
1429 if (*appData.remoteShell == NULLCHAR) {
1430 /* Use the rcmd protocol to run telnet program on a gateway host */
1431 snprintf(buf, sizeof(buf), "%s %s %s",
1432 appData.telnetProgram, appData.icsHost, appData.icsPort);
1433 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1436 /* Use the rsh program to run telnet program on a gateway host */
1437 if (*appData.remoteUser == NULLCHAR) {
1438 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1439 appData.gateway, appData.telnetProgram,
1440 appData.icsHost, appData.icsPort);
1442 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1443 appData.remoteShell, appData.gateway,
1444 appData.remoteUser, appData.telnetProgram,
1445 appData.icsHost, appData.icsPort);
1447 return StartChildProcess(buf, "", &icsPR);
1450 } else if (appData.useTelnet) {
1451 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1454 /* TCP socket interface differs somewhat between
1455 Unix and NT; handle details in the front end.
1457 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1461 void EscapeExpand(char *p, char *q)
1462 { // [HGM] initstring: routine to shape up string arguments
1463 while(*p++ = *q++) if(p[-1] == '\\')
1465 case 'n': p[-1] = '\n'; break;
1466 case 'r': p[-1] = '\r'; break;
1467 case 't': p[-1] = '\t'; break;
1468 case '\\': p[-1] = '\\'; break;
1469 case 0: *p = 0; return;
1470 default: p[-1] = q[-1]; break;
1475 show_bytes(fp, buf, count)
1481 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1482 fprintf(fp, "\\%03o", *buf & 0xff);
1491 /* Returns an errno value */
1493 OutputMaybeTelnet(pr, message, count, outError)
1499 char buf[8192], *p, *q, *buflim;
1500 int left, newcount, outcount;
1502 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1503 *appData.gateway != NULLCHAR) {
1504 if (appData.debugMode) {
1505 fprintf(debugFP, ">ICS: ");
1506 show_bytes(debugFP, message, count);
1507 fprintf(debugFP, "\n");
1509 return OutputToProcess(pr, message, count, outError);
1512 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1519 if (appData.debugMode) {
1520 fprintf(debugFP, ">ICS: ");
1521 show_bytes(debugFP, buf, newcount);
1522 fprintf(debugFP, "\n");
1524 outcount = OutputToProcess(pr, buf, newcount, outError);
1525 if (outcount < newcount) return -1; /* to be sure */
1532 } else if (((unsigned char) *p) == TN_IAC) {
1533 *q++ = (char) TN_IAC;
1540 if (appData.debugMode) {
1541 fprintf(debugFP, ">ICS: ");
1542 show_bytes(debugFP, buf, newcount);
1543 fprintf(debugFP, "\n");
1545 outcount = OutputToProcess(pr, buf, newcount, outError);
1546 if (outcount < newcount) return -1; /* to be sure */
1551 read_from_player(isr, closure, message, count, error)
1558 int outError, outCount;
1559 static int gotEof = 0;
1561 /* Pass data read from player on to ICS */
1564 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1565 if (outCount < count) {
1566 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1568 } else if (count < 0) {
1569 RemoveInputSource(isr);
1570 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1571 } else if (gotEof++ > 0) {
1572 RemoveInputSource(isr);
1573 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1579 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1580 if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
1581 connectionAlive = FALSE; // only sticks if no response to 'date' command.
1582 SendToICS("date\n");
1583 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1586 /* added routine for printf style output to ics */
1587 void ics_printf(char *format, ...)
1589 char buffer[MSG_SIZ];
1592 va_start(args, format);
1593 vsnprintf(buffer, sizeof(buffer), format, args);
1594 buffer[sizeof(buffer)-1] = '\0';
1603 int count, outCount, outError;
1605 if (icsPR == NULL) return;
1608 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1609 if (outCount < count) {
1610 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1614 /* This is used for sending logon scripts to the ICS. Sending
1615 without a delay causes problems when using timestamp on ICC
1616 (at least on my machine). */
1618 SendToICSDelayed(s,msdelay)
1622 int count, outCount, outError;
1624 if (icsPR == NULL) return;
1627 if (appData.debugMode) {
1628 fprintf(debugFP, ">ICS: ");
1629 show_bytes(debugFP, s, count);
1630 fprintf(debugFP, "\n");
1632 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1634 if (outCount < count) {
1635 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1640 /* Remove all highlighting escape sequences in s
1641 Also deletes any suffix starting with '('
1644 StripHighlightAndTitle(s)
1647 static char retbuf[MSG_SIZ];
1650 while (*s != NULLCHAR) {
1651 while (*s == '\033') {
1652 while (*s != NULLCHAR && !isalpha(*s)) s++;
1653 if (*s != NULLCHAR) s++;
1655 while (*s != NULLCHAR && *s != '\033') {
1656 if (*s == '(' || *s == '[') {
1667 /* Remove all highlighting escape sequences in s */
1672 static char retbuf[MSG_SIZ];
1675 while (*s != NULLCHAR) {
1676 while (*s == '\033') {
1677 while (*s != NULLCHAR && !isalpha(*s)) s++;
1678 if (*s != NULLCHAR) s++;
1680 while (*s != NULLCHAR && *s != '\033') {
1688 char *variantNames[] = VARIANT_NAMES;
1693 return variantNames[v];
1697 /* Identify a variant from the strings the chess servers use or the
1698 PGN Variant tag names we use. */
1705 VariantClass v = VariantNormal;
1706 int i, found = FALSE;
1712 /* [HGM] skip over optional board-size prefixes */
1713 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
1714 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
1715 while( *e++ != '_');
1718 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
1722 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
1723 if (StrCaseStr(e, variantNames[i])) {
1724 v = (VariantClass) i;
1731 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
1732 || StrCaseStr(e, "wild/fr")
1733 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
1734 v = VariantFischeRandom;
1735 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
1736 (i = 1, p = StrCaseStr(e, "w"))) {
1738 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
1745 case 0: /* FICS only, actually */
1747 /* Castling legal even if K starts on d-file */
1748 v = VariantWildCastle;
1753 /* Castling illegal even if K & R happen to start in
1754 normal positions. */
1755 v = VariantNoCastle;
1768 /* Castling legal iff K & R start in normal positions */
1774 /* Special wilds for position setup; unclear what to do here */
1775 v = VariantLoadable;
1778 /* Bizarre ICC game */
1779 v = VariantTwoKings;
1782 v = VariantKriegspiel;
1788 v = VariantFischeRandom;
1791 v = VariantCrazyhouse;
1794 v = VariantBughouse;
1800 /* Not quite the same as FICS suicide! */
1801 v = VariantGiveaway;
1807 v = VariantShatranj;
1810 /* Temporary names for future ICC types. The name *will* change in
1811 the next xboard/WinBoard release after ICC defines it. */
1849 v = VariantCapablanca;
1852 v = VariantKnightmate;
1858 v = VariantCylinder;
1864 v = VariantCapaRandom;
1867 v = VariantBerolina;
1879 /* Found "wild" or "w" in the string but no number;
1880 must assume it's normal chess. */
1884 len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
1885 if( (len > MSG_SIZ) && appData.debugMode )
1886 fprintf(debugFP, "StringToVariant: buffer truncated.\n");
1888 DisplayError(buf, 0);
1894 if (appData.debugMode) {
1895 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
1896 e, wnum, VariantName(v));
1901 static int leftover_start = 0, leftover_len = 0;
1902 char star_match[STAR_MATCH_N][MSG_SIZ];
1904 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
1905 advance *index beyond it, and set leftover_start to the new value of
1906 *index; else return FALSE. If pattern contains the character '*', it
1907 matches any sequence of characters not containing '\r', '\n', or the
1908 character following the '*' (if any), and the matched sequence(s) are
1909 copied into star_match.
1912 looking_at(buf, index, pattern)
1917 char *bufp = &buf[*index], *patternp = pattern;
1919 char *matchp = star_match[0];
1922 if (*patternp == NULLCHAR) {
1923 *index = leftover_start = bufp - buf;
1927 if (*bufp == NULLCHAR) return FALSE;
1928 if (*patternp == '*') {
1929 if (*bufp == *(patternp + 1)) {
1931 matchp = star_match[++star_count];
1935 } else if (*bufp == '\n' || *bufp == '\r') {
1937 if (*patternp == NULLCHAR)
1942 *matchp++ = *bufp++;
1946 if (*patternp != *bufp) return FALSE;
1953 SendToPlayer(data, length)
1957 int error, outCount;
1958 outCount = OutputToProcess(NoProc, data, length, &error);
1959 if (outCount < length) {
1960 DisplayFatalError(_("Error writing to display"), error, 1);
1965 PackHolding(packed, holding)
1977 switch (runlength) {
1988 sprintf(q, "%d", runlength);
2000 /* Telnet protocol requests from the front end */
2002 TelnetRequest(ddww, option)
2003 unsigned char ddww, option;
2005 unsigned char msg[3];
2006 int outCount, outError;
2008 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
2010 if (appData.debugMode) {
2011 char buf1[8], buf2[8], *ddwwStr, *optionStr;
2027 snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2036 snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2039 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2044 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2046 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2053 if (!appData.icsActive) return;
2054 TelnetRequest(TN_DO, TN_ECHO);
2060 if (!appData.icsActive) return;
2061 TelnetRequest(TN_DONT, TN_ECHO);
2065 CopyHoldings(Board board, char *holdings, ChessSquare lowestPiece)
2067 /* put the holdings sent to us by the server on the board holdings area */
2068 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2072 if(gameInfo.holdingsWidth < 2) return;
2073 if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2074 return; // prevent overwriting by pre-board holdings
2076 if( (int)lowestPiece >= BlackPawn ) {
2079 holdingsStartRow = BOARD_HEIGHT-1;
2082 holdingsColumn = BOARD_WIDTH-1;
2083 countsColumn = BOARD_WIDTH-2;
2084 holdingsStartRow = 0;
2088 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
2089 board[i][holdingsColumn] = EmptySquare;
2090 board[i][countsColumn] = (ChessSquare) 0;
2092 while( (p=*holdings++) != NULLCHAR ) {
2093 piece = CharToPiece( ToUpper(p) );
2094 if(piece == EmptySquare) continue;
2095 /*j = (int) piece - (int) WhitePawn;*/
2096 j = PieceToNumber(piece);
2097 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2098 if(j < 0) continue; /* should not happen */
2099 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2100 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2101 board[holdingsStartRow+j*direction][countsColumn]++;
2107 VariantSwitch(Board board, VariantClass newVariant)
2109 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2110 static Board oldBoard;
2112 startedFromPositionFile = FALSE;
2113 if(gameInfo.variant == newVariant) return;
2115 /* [HGM] This routine is called each time an assignment is made to
2116 * gameInfo.variant during a game, to make sure the board sizes
2117 * are set to match the new variant. If that means adding or deleting
2118 * holdings, we shift the playing board accordingly
2119 * This kludge is needed because in ICS observe mode, we get boards
2120 * of an ongoing game without knowing the variant, and learn about the
2121 * latter only later. This can be because of the move list we requested,
2122 * in which case the game history is refilled from the beginning anyway,
2123 * but also when receiving holdings of a crazyhouse game. In the latter
2124 * case we want to add those holdings to the already received position.
2128 if (appData.debugMode) {
2129 fprintf(debugFP, "Switch board from %s to %s\n",
2130 VariantName(gameInfo.variant), VariantName(newVariant));
2131 setbuf(debugFP, NULL);
2133 shuffleOpenings = 0; /* [HGM] shuffle */
2134 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2138 newWidth = 9; newHeight = 9;
2139 gameInfo.holdingsSize = 7;
2140 case VariantBughouse:
2141 case VariantCrazyhouse:
2142 newHoldingsWidth = 2; break;
2146 newHoldingsWidth = 2;
2147 gameInfo.holdingsSize = 8;
2150 case VariantCapablanca:
2151 case VariantCapaRandom:
2154 newHoldingsWidth = gameInfo.holdingsSize = 0;
2157 if(newWidth != gameInfo.boardWidth ||
2158 newHeight != gameInfo.boardHeight ||
2159 newHoldingsWidth != gameInfo.holdingsWidth ) {
2161 /* shift position to new playing area, if needed */
2162 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2163 for(i=0; i<BOARD_HEIGHT; i++)
2164 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2165 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2167 for(i=0; i<newHeight; i++) {
2168 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2169 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2171 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2172 for(i=0; i<BOARD_HEIGHT; i++)
2173 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2174 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2177 gameInfo.boardWidth = newWidth;
2178 gameInfo.boardHeight = newHeight;
2179 gameInfo.holdingsWidth = newHoldingsWidth;
2180 gameInfo.variant = newVariant;
2181 InitDrawingSizes(-2, 0);
2182 } else gameInfo.variant = newVariant;
2183 CopyBoard(oldBoard, board); // remember correctly formatted board
2184 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2185 DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2188 static int loggedOn = FALSE;
2190 /*-- Game start info cache: --*/
2192 char gs_kind[MSG_SIZ];
2193 static char player1Name[128] = "";
2194 static char player2Name[128] = "";
2195 static char cont_seq[] = "\n\\ ";
2196 static int player1Rating = -1;
2197 static int player2Rating = -1;
2198 /*----------------------------*/
2200 ColorClass curColor = ColorNormal;
2201 int suppressKibitz = 0;
2204 Boolean soughtPending = FALSE;
2205 Boolean seekGraphUp;
2206 #define MAX_SEEK_ADS 200
2208 char *seekAdList[MAX_SEEK_ADS];
2209 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2210 float tcList[MAX_SEEK_ADS];
2211 char colorList[MAX_SEEK_ADS];
2212 int nrOfSeekAds = 0;
2213 int minRating = 1010, maxRating = 2800;
2214 int hMargin = 10, vMargin = 20, h, w;
2215 extern int squareSize, lineGap;
2220 int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2221 xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2222 if(r < minRating+100 && r >=0 ) r = minRating+100;
2223 if(r > maxRating) r = maxRating;
2224 if(tc < 1.) tc = 1.;
2225 if(tc > 95.) tc = 95.;
2226 x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2227 y = ((double)r - minRating)/(maxRating - minRating)
2228 * (h-vMargin-squareSize/8-1) + vMargin;
2229 if(ratingList[i] < 0) y = vMargin + squareSize/4;
2230 if(strstr(seekAdList[i], " u ")) color = 1;
2231 if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2232 !strstr(seekAdList[i], "bullet") &&
2233 !strstr(seekAdList[i], "blitz") &&
2234 !strstr(seekAdList[i], "standard") ) color = 2;
2235 if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2236 DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2240 AddAd(char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
2242 char buf[MSG_SIZ], *ext = "";
2243 VariantClass v = StringToVariant(type);
2244 if(strstr(type, "wild")) {
2245 ext = type + 4; // append wild number
2246 if(v == VariantFischeRandom) type = "chess960"; else
2247 if(v == VariantLoadable) type = "setup"; else
2248 type = VariantName(v);
2250 snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2251 if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2252 if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2253 ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2254 sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2255 tcList[nrOfSeekAds] = base + (2./3.)*inc;
2256 seekNrList[nrOfSeekAds] = nr;
2257 zList[nrOfSeekAds] = 0;
2258 seekAdList[nrOfSeekAds++] = StrSave(buf);
2259 if(plot) PlotSeekAd(nrOfSeekAds-1);
2266 int x = xList[i], y = yList[i], d=squareSize/4, k;
2267 DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2268 if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2269 // now replot every dot that overlapped
2270 for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2271 int xx = xList[k], yy = yList[k];
2272 if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2273 DrawSeekDot(xx, yy, colorList[k]);
2278 RemoveSeekAd(int nr)
2281 for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2283 if(seekAdList[i]) free(seekAdList[i]);
2284 seekAdList[i] = seekAdList[--nrOfSeekAds];
2285 seekNrList[i] = seekNrList[nrOfSeekAds];
2286 ratingList[i] = ratingList[nrOfSeekAds];
2287 colorList[i] = colorList[nrOfSeekAds];
2288 tcList[i] = tcList[nrOfSeekAds];
2289 xList[i] = xList[nrOfSeekAds];
2290 yList[i] = yList[nrOfSeekAds];
2291 zList[i] = zList[nrOfSeekAds];
2292 seekAdList[nrOfSeekAds] = NULL;
2298 MatchSoughtLine(char *line)
2300 char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2301 int nr, base, inc, u=0; char dummy;
2303 if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2304 sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2306 (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2307 sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
2308 // match: compact and save the line
2309 AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2319 if(!seekGraphUp) return FALSE;
2320 h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap;
2321 w = BOARD_WIDTH * (squareSize + lineGap) + lineGap;
2323 DrawSeekBackground(0, 0, w, h);
2324 DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2325 DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2326 for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2327 int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2329 DrawSeekAxis(hMargin+5*(i%500==0), yy, hMargin-5, yy); // rating ticks
2332 snprintf(buf, MSG_SIZ, "%d", i);
2333 DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2336 DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2337 for(i=1; i<100; i+=(i<10?1:5)) {
2338 int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2339 DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2340 if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2342 snprintf(buf, MSG_SIZ, "%d", i);
2343 DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2346 for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2350 int SeekGraphClick(ClickType click, int x, int y, int moving)
2352 static int lastDown = 0, displayed = 0, lastSecond;
2353 if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2354 if(click == Release || moving) return FALSE;
2356 soughtPending = TRUE;
2357 SendToICS(ics_prefix);
2358 SendToICS("sought\n"); // should this be "sought all"?
2359 } else { // issue challenge based on clicked ad
2360 int dist = 10000; int i, closest = 0, second = 0;
2361 for(i=0; i<nrOfSeekAds; i++) {
2362 int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
2363 if(d < dist) { dist = d; closest = i; }
2364 second += (d - zList[i] < 120); // count in-range ads
2365 if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2369 second = (second > 1);
2370 if(displayed != closest || second != lastSecond) {
2371 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2372 lastSecond = second; displayed = closest;
2374 if(click == Press) {
2375 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2378 } // on press 'hit', only show info
2379 if(moving == 2) return TRUE; // ignore right up-clicks on dot
2380 snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2381 SendToICS(ics_prefix);
2383 return TRUE; // let incoming board of started game pop down the graph
2384 } else if(click == Release) { // release 'miss' is ignored
2385 zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2386 if(moving == 2) { // right up-click
2387 nrOfSeekAds = 0; // refresh graph
2388 soughtPending = TRUE;
2389 SendToICS(ics_prefix);
2390 SendToICS("sought\n"); // should this be "sought all"?
2393 } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2394 // press miss or release hit 'pop down' seek graph
2395 seekGraphUp = FALSE;
2396 DrawPosition(TRUE, NULL);
2402 read_from_ics(isr, closure, data, count, error)
2409 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2410 #define STARTED_NONE 0
2411 #define STARTED_MOVES 1
2412 #define STARTED_BOARD 2
2413 #define STARTED_OBSERVE 3
2414 #define STARTED_HOLDINGS 4
2415 #define STARTED_CHATTER 5
2416 #define STARTED_COMMENT 6
2417 #define STARTED_MOVES_NOHIDE 7
2419 static int started = STARTED_NONE;
2420 static char parse[20000];
2421 static int parse_pos = 0;
2422 static char buf[BUF_SIZE + 1];
2423 static int firstTime = TRUE, intfSet = FALSE;
2424 static ColorClass prevColor = ColorNormal;
2425 static int savingComment = FALSE;
2426 static int cmatch = 0; // continuation sequence match
2433 int backup; /* [DM] For zippy color lines */
2435 char talker[MSG_SIZ]; // [HGM] chat
2438 connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2440 if (appData.debugMode) {
2442 fprintf(debugFP, "<ICS: ");
2443 show_bytes(debugFP, data, count);
2444 fprintf(debugFP, "\n");
2448 if (appData.debugMode) { int f = forwardMostMove;
2449 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2450 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2451 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2454 /* If last read ended with a partial line that we couldn't parse,
2455 prepend it to the new read and try again. */
2456 if (leftover_len > 0) {
2457 for (i=0; i<leftover_len; i++)
2458 buf[i] = buf[leftover_start + i];
2461 /* copy new characters into the buffer */
2462 bp = buf + leftover_len;
2463 buf_len=leftover_len;
2464 for (i=0; i<count; i++)
2467 if (data[i] == '\r')
2470 // join lines split by ICS?
2471 if (!appData.noJoin)
2474 Joining just consists of finding matches against the
2475 continuation sequence, and discarding that sequence
2476 if found instead of copying it. So, until a match
2477 fails, there's nothing to do since it might be the
2478 complete sequence, and thus, something we don't want
2481 if (data[i] == cont_seq[cmatch])
2484 if (cmatch == strlen(cont_seq))
2486 cmatch = 0; // complete match. just reset the counter
2489 it's possible for the ICS to not include the space
2490 at the end of the last word, making our [correct]
2491 join operation fuse two separate words. the server
2492 does this when the space occurs at the width setting.
2494 if (!buf_len || buf[buf_len-1] != ' ')
2505 match failed, so we have to copy what matched before
2506 falling through and copying this character. In reality,
2507 this will only ever be just the newline character, but
2508 it doesn't hurt to be precise.
2510 strncpy(bp, cont_seq, cmatch);
2522 buf[buf_len] = NULLCHAR;
2523 // next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2528 while (i < buf_len) {
2529 /* Deal with part of the TELNET option negotiation
2530 protocol. We refuse to do anything beyond the
2531 defaults, except that we allow the WILL ECHO option,
2532 which ICS uses to turn off password echoing when we are
2533 directly connected to it. We reject this option
2534 if localLineEditing mode is on (always on in xboard)
2535 and we are talking to port 23, which might be a real
2536 telnet server that will try to keep WILL ECHO on permanently.
2538 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2539 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2540 unsigned char option;
2542 switch ((unsigned char) buf[++i]) {
2544 if (appData.debugMode)
2545 fprintf(debugFP, "\n<WILL ");
2546 switch (option = (unsigned char) buf[++i]) {
2548 if (appData.debugMode)
2549 fprintf(debugFP, "ECHO ");
2550 /* Reply only if this is a change, according
2551 to the protocol rules. */
2552 if (remoteEchoOption) break;
2553 if (appData.localLineEditing &&
2554 atoi(appData.icsPort) == TN_PORT) {
2555 TelnetRequest(TN_DONT, TN_ECHO);
2558 TelnetRequest(TN_DO, TN_ECHO);
2559 remoteEchoOption = TRUE;
2563 if (appData.debugMode)
2564 fprintf(debugFP, "%d ", option);
2565 /* Whatever this is, we don't want it. */
2566 TelnetRequest(TN_DONT, option);
2571 if (appData.debugMode)
2572 fprintf(debugFP, "\n<WONT ");
2573 switch (option = (unsigned char) buf[++i]) {
2575 if (appData.debugMode)
2576 fprintf(debugFP, "ECHO ");
2577 /* Reply only if this is a change, according
2578 to the protocol rules. */
2579 if (!remoteEchoOption) break;
2581 TelnetRequest(TN_DONT, TN_ECHO);
2582 remoteEchoOption = FALSE;
2585 if (appData.debugMode)
2586 fprintf(debugFP, "%d ", (unsigned char) option);
2587 /* Whatever this is, it must already be turned
2588 off, because we never agree to turn on
2589 anything non-default, so according to the
2590 protocol rules, we don't reply. */
2595 if (appData.debugMode)
2596 fprintf(debugFP, "\n<DO ");
2597 switch (option = (unsigned char) buf[++i]) {
2599 /* Whatever this is, we refuse to do it. */
2600 if (appData.debugMode)
2601 fprintf(debugFP, "%d ", option);
2602 TelnetRequest(TN_WONT, option);
2607 if (appData.debugMode)
2608 fprintf(debugFP, "\n<DONT ");
2609 switch (option = (unsigned char) buf[++i]) {
2611 if (appData.debugMode)
2612 fprintf(debugFP, "%d ", option);
2613 /* Whatever this is, we are already not doing
2614 it, because we never agree to do anything
2615 non-default, so according to the protocol
2616 rules, we don't reply. */
2621 if (appData.debugMode)
2622 fprintf(debugFP, "\n<IAC ");
2623 /* Doubled IAC; pass it through */
2627 if (appData.debugMode)
2628 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2629 /* Drop all other telnet commands on the floor */
2632 if (oldi > next_out)
2633 SendToPlayer(&buf[next_out], oldi - next_out);
2639 /* OK, this at least will *usually* work */
2640 if (!loggedOn && looking_at(buf, &i, "ics%")) {
2644 if (loggedOn && !intfSet) {
2645 if (ics_type == ICS_ICC) {
2646 snprintf(str, MSG_SIZ,
2647 "/set-quietly interface %s\n/set-quietly style 12\n",
2649 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2650 strcat(str, "/set-2 51 1\n/set seek 1\n");
2651 } else if (ics_type == ICS_CHESSNET) {
2652 snprintf(str, MSG_SIZ, "/style 12\n");
2654 safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
2655 strcat(str, programVersion);
2656 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2657 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2658 strcat(str, "$iset seekremove 1\n$set seek 1\n");
2660 strcat(str, "$iset nohighlight 1\n");
2662 strcat(str, "$iset lock 1\n$style 12\n");
2665 NotifyFrontendLogin();
2669 if (started == STARTED_COMMENT) {
2670 /* Accumulate characters in comment */
2671 parse[parse_pos++] = buf[i];
2672 if (buf[i] == '\n') {
2673 parse[parse_pos] = NULLCHAR;
2674 if(chattingPartner>=0) {
2676 snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
2677 OutputChatMessage(chattingPartner, mess);
2678 chattingPartner = -1;
2679 next_out = i+1; // [HGM] suppress printing in ICS window
2681 if(!suppressKibitz) // [HGM] kibitz
2682 AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
2683 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2684 int nrDigit = 0, nrAlph = 0, j;
2685 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2686 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2687 parse[parse_pos] = NULLCHAR;
2688 // try to be smart: if it does not look like search info, it should go to
2689 // ICS interaction window after all, not to engine-output window.
2690 for(j=0; j<parse_pos; j++) { // count letters and digits
2691 nrDigit += (parse[j] >= '0' && parse[j] <= '9');
2692 nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
2693 nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
2695 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
2696 int depth=0; float score;
2697 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
2698 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
2699 pvInfoList[forwardMostMove-1].depth = depth;
2700 pvInfoList[forwardMostMove-1].score = 100*score;
2702 OutputKibitz(suppressKibitz, parse);
2705 snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
2706 SendToPlayer(tmp, strlen(tmp));
2708 next_out = i+1; // [HGM] suppress printing in ICS window
2710 started = STARTED_NONE;
2712 /* Don't match patterns against characters in comment */
2717 if (started == STARTED_CHATTER) {
2718 if (buf[i] != '\n') {
2719 /* Don't match patterns against characters in chatter */
2723 started = STARTED_NONE;
2724 if(suppressKibitz) next_out = i+1;
2727 /* Kludge to deal with rcmd protocol */
2728 if (firstTime && looking_at(buf, &i, "\001*")) {
2729 DisplayFatalError(&buf[1], 0, 1);
2735 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
2738 if (appData.debugMode)
2739 fprintf(debugFP, "ics_type %d\n", ics_type);
2742 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
2743 ics_type = ICS_FICS;
2745 if (appData.debugMode)
2746 fprintf(debugFP, "ics_type %d\n", ics_type);
2749 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
2750 ics_type = ICS_CHESSNET;
2752 if (appData.debugMode)
2753 fprintf(debugFP, "ics_type %d\n", ics_type);
2758 (looking_at(buf, &i, "\"*\" is *a registered name") ||
2759 looking_at(buf, &i, "Logging you in as \"*\"") ||
2760 looking_at(buf, &i, "will be \"*\""))) {
2761 safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
2765 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
2767 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
2768 DisplayIcsInteractionTitle(buf);
2769 have_set_title = TRUE;
2772 /* skip finger notes */
2773 if (started == STARTED_NONE &&
2774 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
2775 (buf[i] == '1' && buf[i+1] == '0')) &&
2776 buf[i+2] == ':' && buf[i+3] == ' ') {
2777 started = STARTED_CHATTER;
2783 // [HGM] seekgraph: recognize sought lines and end-of-sought message
2784 if(appData.seekGraph) {
2785 if(soughtPending && MatchSoughtLine(buf+i)) {
2786 i = strstr(buf+i, "rated") - buf;
2787 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2788 next_out = leftover_start = i;
2789 started = STARTED_CHATTER;
2790 suppressKibitz = TRUE;
2793 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
2794 && looking_at(buf, &i, "* ads displayed")) {
2795 soughtPending = FALSE;
2800 if(appData.autoRefresh) {
2801 if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
2802 int s = (ics_type == ICS_ICC); // ICC format differs
2804 AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
2805 star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
2806 looking_at(buf, &i, "*% "); // eat prompt
2807 if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
2808 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2809 next_out = i; // suppress
2812 if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
2813 char *p = star_match[0];
2815 if(seekGraphUp) RemoveSeekAd(atoi(p));
2816 while(*p && *p++ != ' '); // next
2818 looking_at(buf, &i, "*% "); // eat prompt
2819 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2826 /* skip formula vars */
2827 if (started == STARTED_NONE &&
2828 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
2829 started = STARTED_CHATTER;
2834 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
2835 if (appData.autoKibitz && started == STARTED_NONE &&
2836 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
2837 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
2838 if((looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
2839 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
2840 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
2841 suppressKibitz = TRUE;
2842 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2844 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
2845 && (gameMode == IcsPlayingWhite)) ||
2846 (StrStr(star_match[0], gameInfo.black) == star_match[0]
2847 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
2848 started = STARTED_CHATTER; // own kibitz we simply discard
2850 started = STARTED_COMMENT; // make sure it will be collected in parse[]
2851 parse_pos = 0; parse[0] = NULLCHAR;
2852 savingComment = TRUE;
2853 suppressKibitz = gameMode != IcsObserving ? 2 :
2854 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
2858 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
2859 looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
2860 && atoi(star_match[0])) {
2861 // suppress the acknowledgements of our own autoKibitz
2863 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2864 if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
2865 SendToPlayer(star_match[0], strlen(star_match[0]));
2866 if(looking_at(buf, &i, "*% ")) // eat prompt
2867 suppressKibitz = FALSE;
2871 } // [HGM] kibitz: end of patch
2873 // [HGM] chat: intercept tells by users for which we have an open chat window
2875 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
2876 looking_at(buf, &i, "* whispers:") ||
2877 looking_at(buf, &i, "* kibitzes:") ||
2878 looking_at(buf, &i, "* shouts:") ||
2879 looking_at(buf, &i, "* c-shouts:") ||
2880 looking_at(buf, &i, "--> * ") ||
2881 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
2882 looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
2883 looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
2884 looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
2886 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
2887 chattingPartner = -1;
2889 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
2890 for(p=0; p<MAX_CHAT; p++) {
2891 if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
2892 talker[0] = '['; strcat(talker, "] ");
2893 Colorize(channel == 1 ? ColorChannel1 : ColorChannel, FALSE);
2894 chattingPartner = p; break;
2897 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
2898 for(p=0; p<MAX_CHAT; p++) {
2899 if(!strcmp("kibitzes", chatPartner[p])) {
2900 talker[0] = '['; strcat(talker, "] ");
2901 chattingPartner = p; break;
2904 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
2905 for(p=0; p<MAX_CHAT; p++) {
2906 if(!strcmp("whispers", chatPartner[p])) {
2907 talker[0] = '['; strcat(talker, "] ");
2908 chattingPartner = p; break;
2911 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
2912 if(buf[i-8] == '-' && buf[i-3] == 't')
2913 for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
2914 if(!strcmp("c-shouts", chatPartner[p])) {
2915 talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
2916 chattingPartner = p; break;
2919 if(chattingPartner < 0)
2920 for(p=0; p<MAX_CHAT; p++) {
2921 if(!strcmp("shouts", chatPartner[p])) {
2922 if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
2923 else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
2924 else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
2925 chattingPartner = p; break;
2929 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
2930 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
2931 talker[0] = 0; Colorize(ColorTell, FALSE);
2932 chattingPartner = p; break;
2934 if(chattingPartner<0) i = oldi; else {
2935 Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
2936 if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
2937 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
2938 started = STARTED_COMMENT;
2939 parse_pos = 0; parse[0] = NULLCHAR;
2940 savingComment = 3 + chattingPartner; // counts as TRUE
2941 suppressKibitz = TRUE;
2944 } // [HGM] chat: end of patch
2946 if (appData.zippyTalk || appData.zippyPlay) {
2947 /* [DM] Backup address for color zippy lines */
2950 if (loggedOn == TRUE)
2951 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
2952 (appData.zippyPlay && ZippyMatch(buf, &backup)));
2954 } // [DM] 'else { ' deleted
2956 /* Regular tells and says */
2957 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
2958 looking_at(buf, &i, "* (your partner) tells you: ") ||
2959 looking_at(buf, &i, "* says: ") ||
2960 /* Don't color "message" or "messages" output */
2961 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
2962 looking_at(buf, &i, "*. * at *:*: ") ||
2963 looking_at(buf, &i, "--* (*:*): ") ||
2964 /* Message notifications (same color as tells) */
2965 looking_at(buf, &i, "* has left a message ") ||
2966 looking_at(buf, &i, "* just sent you a message:\n") ||
2967 /* Whispers and kibitzes */
2968 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
2969 looking_at(buf, &i, "* kibitzes: ") ||
2971 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
2973 if (tkind == 1 && strchr(star_match[0], ':')) {
2974 /* Avoid "tells you:" spoofs in channels */
2977 if (star_match[0][0] == NULLCHAR ||
2978 strchr(star_match[0], ' ') ||
2979 (tkind == 3 && strchr(star_match[1], ' '))) {
2980 /* Reject bogus matches */
2983 if (appData.colorize) {
2984 if (oldi > next_out) {
2985 SendToPlayer(&buf[next_out], oldi - next_out);
2990 Colorize(ColorTell, FALSE);
2991 curColor = ColorTell;
2994 Colorize(ColorKibitz, FALSE);
2995 curColor = ColorKibitz;
2998 p = strrchr(star_match[1], '(');
3005 Colorize(ColorChannel1, FALSE);
3006 curColor = ColorChannel1;
3008 Colorize(ColorChannel, FALSE);
3009 curColor = ColorChannel;
3013 curColor = ColorNormal;
3017 if (started == STARTED_NONE && appData.autoComment &&
3018 (gameMode == IcsObserving ||
3019 gameMode == IcsPlayingWhite ||
3020 gameMode == IcsPlayingBlack)) {
3021 parse_pos = i - oldi;
3022 memcpy(parse, &buf[oldi], parse_pos);
3023 parse[parse_pos] = NULLCHAR;
3024 started = STARTED_COMMENT;
3025 savingComment = TRUE;
3027 started = STARTED_CHATTER;
3028 savingComment = FALSE;
3035 if (looking_at(buf, &i, "* s-shouts: ") ||
3036 looking_at(buf, &i, "* c-shouts: ")) {
3037 if (appData.colorize) {
3038 if (oldi > next_out) {
3039 SendToPlayer(&buf[next_out], oldi - next_out);
3042 Colorize(ColorSShout, FALSE);
3043 curColor = ColorSShout;
3046 started = STARTED_CHATTER;
3050 if (looking_at(buf, &i, "--->")) {
3055 if (looking_at(buf, &i, "* shouts: ") ||
3056 looking_at(buf, &i, "--> ")) {
3057 if (appData.colorize) {
3058 if (oldi > next_out) {
3059 SendToPlayer(&buf[next_out], oldi - next_out);
3062 Colorize(ColorShout, FALSE);
3063 curColor = ColorShout;
3066 started = STARTED_CHATTER;
3070 if (looking_at( buf, &i, "Challenge:")) {
3071 if (appData.colorize) {
3072 if (oldi > next_out) {
3073 SendToPlayer(&buf[next_out], oldi - next_out);
3076 Colorize(ColorChallenge, FALSE);
3077 curColor = ColorChallenge;
3083 if (looking_at(buf, &i, "* offers you") ||
3084 looking_at(buf, &i, "* offers to be") ||
3085 looking_at(buf, &i, "* would like to") ||
3086 looking_at(buf, &i, "* requests to") ||
3087 looking_at(buf, &i, "Your opponent offers") ||
3088 looking_at(buf, &i, "Your opponent requests")) {
3090 if (appData.colorize) {
3091 if (oldi > next_out) {
3092 SendToPlayer(&buf[next_out], oldi - next_out);
3095 Colorize(ColorRequest, FALSE);
3096 curColor = ColorRequest;
3101 if (looking_at(buf, &i, "* (*) seeking")) {
3102 if (appData.colorize) {
3103 if (oldi > next_out) {
3104 SendToPlayer(&buf[next_out], oldi - next_out);
3107 Colorize(ColorSeek, FALSE);
3108 curColor = ColorSeek;
3113 if (looking_at(buf, &i, "\\ ")) {
3114 if (prevColor != ColorNormal) {
3115 if (oldi > next_out) {
3116 SendToPlayer(&buf[next_out], oldi - next_out);
3119 Colorize(prevColor, TRUE);
3120 curColor = prevColor;
3122 if (savingComment) {
3123 parse_pos = i - oldi;
3124 memcpy(parse, &buf[oldi], parse_pos);
3125 parse[parse_pos] = NULLCHAR;
3126 started = STARTED_COMMENT;
3127 if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3128 chattingPartner = savingComment - 3; // kludge to remember the box
3130 started = STARTED_CHATTER;
3135 if (looking_at(buf, &i, "Black Strength :") ||
3136 looking_at(buf, &i, "<<< style 10 board >>>") ||
3137 looking_at(buf, &i, "<10>") ||
3138 looking_at(buf, &i, "#@#")) {
3139 /* Wrong board style */
3141 SendToICS(ics_prefix);
3142 SendToICS("set style 12\n");
3143 SendToICS(ics_prefix);
3144 SendToICS("refresh\n");
3148 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
3150 have_sent_ICS_logon = 1;
3154 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3155 (looking_at(buf, &i, "\n<12> ") ||
3156 looking_at(buf, &i, "<12> "))) {
3158 if (oldi > next_out) {
3159 SendToPlayer(&buf[next_out], oldi - next_out);
3162 started = STARTED_BOARD;
3167 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3168 looking_at(buf, &i, "<b1> ")) {
3169 if (oldi > next_out) {
3170 SendToPlayer(&buf[next_out], oldi - next_out);
3173 started = STARTED_HOLDINGS;
3178 if (looking_at(buf, &i, "* *vs. * *--- *")) {
3180 /* Header for a move list -- first line */
3182 switch (ics_getting_history) {
3186 case BeginningOfGame:
3187 /* User typed "moves" or "oldmoves" while we
3188 were idle. Pretend we asked for these
3189 moves and soak them up so user can step
3190 through them and/or save them.
3193 gameMode = IcsObserving;
3196 ics_getting_history = H_GOT_UNREQ_HEADER;
3198 case EditGame: /*?*/
3199 case EditPosition: /*?*/
3200 /* Should above feature work in these modes too? */
3201 /* For now it doesn't */
3202 ics_getting_history = H_GOT_UNWANTED_HEADER;
3205 ics_getting_history = H_GOT_UNWANTED_HEADER;
3210 /* Is this the right one? */
3211 if (gameInfo.white && gameInfo.black &&
3212 strcmp(gameInfo.white, star_match[0]) == 0 &&
3213 strcmp(gameInfo.black, star_match[2]) == 0) {
3215 ics_getting_history = H_GOT_REQ_HEADER;
3218 case H_GOT_REQ_HEADER:
3219 case H_GOT_UNREQ_HEADER:
3220 case H_GOT_UNWANTED_HEADER:
3221 case H_GETTING_MOVES:
3222 /* Should not happen */
3223 DisplayError(_("Error gathering move list: two headers"), 0);
3224 ics_getting_history = H_FALSE;
3228 /* Save player ratings into gameInfo if needed */
3229 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3230 ics_getting_history == H_GOT_UNREQ_HEADER) &&
3231 (gameInfo.whiteRating == -1 ||
3232 gameInfo.blackRating == -1)) {
3234 gameInfo.whiteRating = string_to_rating(star_match[1]);
3235 gameInfo.blackRating = string_to_rating(star_match[3]);
3236 if (appData.debugMode)
3237 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
3238 gameInfo.whiteRating, gameInfo.blackRating);
3243 if (looking_at(buf, &i,
3244 "* * match, initial time: * minute*, increment: * second")) {
3245 /* Header for a move list -- second line */
3246 /* Initial board will follow if this is a wild game */
3247 if (gameInfo.event != NULL) free(gameInfo.event);
3248 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3249 gameInfo.event = StrSave(str);
3250 /* [HGM] we switched variant. Translate boards if needed. */
3251 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3255 if (looking_at(buf, &i, "Move ")) {
3256 /* Beginning of a move list */
3257 switch (ics_getting_history) {
3259 /* Normally should not happen */
3260 /* Maybe user hit reset while we were parsing */
3263 /* Happens if we are ignoring a move list that is not
3264 * the one we just requested. Common if the user
3265 * tries to observe two games without turning off
3268 case H_GETTING_MOVES:
3269 /* Should not happen */
3270 DisplayError(_("Error gathering move list: nested"), 0);
3271 ics_getting_history = H_FALSE;
3273 case H_GOT_REQ_HEADER:
3274 ics_getting_history = H_GETTING_MOVES;
3275 started = STARTED_MOVES;
3277 if (oldi > next_out) {
3278 SendToPlayer(&buf[next_out], oldi - next_out);
3281 case H_GOT_UNREQ_HEADER:
3282 ics_getting_history = H_GETTING_MOVES;
3283 started = STARTED_MOVES_NOHIDE;
3286 case H_GOT_UNWANTED_HEADER:
3287 ics_getting_history = H_FALSE;
3293 if (looking_at(buf, &i, "% ") ||
3294 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3295 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3296 if(ics_type == ICS_ICC && soughtPending) { // [HGM] seekgraph: on ICC sought-list has no termination line
3297 soughtPending = FALSE;
3301 if(suppressKibitz) next_out = i;
3302 savingComment = FALSE;
3306 case STARTED_MOVES_NOHIDE:
3307 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3308 parse[parse_pos + i - oldi] = NULLCHAR;
3309 ParseGameHistory(parse);
3311 if (appData.zippyPlay && first.initDone) {
3312 FeedMovesToProgram(&first, forwardMostMove);
3313 if (gameMode == IcsPlayingWhite) {
3314 if (WhiteOnMove(forwardMostMove)) {
3315 if (first.sendTime) {
3316 if (first.useColors) {
3317 SendToProgram("black\n", &first);
3319 SendTimeRemaining(&first, TRUE);
3321 if (first.useColors) {
3322 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3324 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3325 first.maybeThinking = TRUE;
3327 if (first.usePlayother) {
3328 if (first.sendTime) {
3329 SendTimeRemaining(&first, TRUE);
3331 SendToProgram("playother\n", &first);
3337 } else if (gameMode == IcsPlayingBlack) {
3338 if (!WhiteOnMove(forwardMostMove)) {
3339 if (first.sendTime) {
3340 if (first.useColors) {
3341 SendToProgram("white\n", &first);
3343 SendTimeRemaining(&first, FALSE);
3345 if (first.useColors) {
3346 SendToProgram("black\n", &first);
3348 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3349 first.maybeThinking = TRUE;
3351 if (first.usePlayother) {
3352 if (first.sendTime) {
3353 SendTimeRemaining(&first, FALSE);
3355 SendToProgram("playother\n", &first);
3364 if (gameMode == IcsObserving && ics_gamenum == -1) {
3365 /* Moves came from oldmoves or moves command
3366 while we weren't doing anything else.
3368 currentMove = forwardMostMove;
3369 ClearHighlights();/*!!could figure this out*/
3370 flipView = appData.flipView;
3371 DrawPosition(TRUE, boards[currentMove]);
3372 DisplayBothClocks();
3373 snprintf(str, MSG_SIZ, "%s vs. %s",
3374 gameInfo.white, gameInfo.black);
3378 /* Moves were history of an active game */
3379 if (gameInfo.resultDetails != NULL) {
3380 free(gameInfo.resultDetails);
3381 gameInfo.resultDetails = NULL;
3384 HistorySet(parseList, backwardMostMove,
3385 forwardMostMove, currentMove-1);
3386 DisplayMove(currentMove - 1);
3387 if (started == STARTED_MOVES) next_out = i;
3388 started = STARTED_NONE;
3389 ics_getting_history = H_FALSE;
3392 case STARTED_OBSERVE:
3393 started = STARTED_NONE;
3394 SendToICS(ics_prefix);
3395 SendToICS("refresh\n");
3401 if(bookHit) { // [HGM] book: simulate book reply
3402 static char bookMove[MSG_SIZ]; // a bit generous?
3404 programStats.nodes = programStats.depth = programStats.time =
3405 programStats.score = programStats.got_only_move = 0;
3406 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3408 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3409 strcat(bookMove, bookHit);
3410 HandleMachineMove(bookMove, &first);
3415 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3416 started == STARTED_HOLDINGS ||
3417 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3418 /* Accumulate characters in move list or board */
3419 parse[parse_pos++] = buf[i];
3422 /* Start of game messages. Mostly we detect start of game
3423 when the first board image arrives. On some versions
3424 of the ICS, though, we need to do a "refresh" after starting
3425 to observe in order to get the current board right away. */
3426 if (looking_at(buf, &i, "Adding game * to observation list")) {
3427 started = STARTED_OBSERVE;
3431 /* Handle auto-observe */
3432 if (appData.autoObserve &&
3433 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3434 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3436 /* Choose the player that was highlighted, if any. */
3437 if (star_match[0][0] == '\033' ||
3438 star_match[1][0] != '\033') {
3439 player = star_match[0];
3441 player = star_match[2];
3443 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3444 ics_prefix, StripHighlightAndTitle(player));
3447 /* Save ratings from notify string */
3448 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3449 player1Rating = string_to_rating(star_match[1]);
3450 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3451 player2Rating = string_to_rating(star_match[3]);
3453 if (appData.debugMode)
3455 "Ratings from 'Game notification:' %s %d, %s %d\n",
3456 player1Name, player1Rating,
3457 player2Name, player2Rating);
3462 /* Deal with automatic examine mode after a game,
3463 and with IcsObserving -> IcsExamining transition */
3464 if (looking_at(buf, &i, "Entering examine mode for game *") ||
3465 looking_at(buf, &i, "has made you an examiner of game *")) {
3467 int gamenum = atoi(star_match[0]);
3468 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3469 gamenum == ics_gamenum) {
3470 /* We were already playing or observing this game;
3471 no need to refetch history */
3472 gameMode = IcsExamining;
3474 pauseExamForwardMostMove = forwardMostMove;
3475 } else if (currentMove < forwardMostMove) {
3476 ForwardInner(forwardMostMove);
3479 /* I don't think this case really can happen */
3480 SendToICS(ics_prefix);
3481 SendToICS("refresh\n");
3486 /* Error messages */
3487 // if (ics_user_moved) {
3488 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3489 if (looking_at(buf, &i, "Illegal move") ||
3490 looking_at(buf, &i, "Not a legal move") ||
3491 looking_at(buf, &i, "Your king is in check") ||
3492 looking_at(buf, &i, "It isn't your turn") ||
3493 looking_at(buf, &i, "It is not your move")) {
3495 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3496 currentMove = forwardMostMove-1;
3497 DisplayMove(currentMove - 1); /* before DMError */
3498 DrawPosition(FALSE, boards[currentMove]);
3499 SwitchClocks(forwardMostMove-1); // [HGM] race
3500 DisplayBothClocks();
3502 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3508 if (looking_at(buf, &i, "still have time") ||
3509 looking_at(buf, &i, "not out of time") ||
3510 looking_at(buf, &i, "either player is out of time") ||
3511 looking_at(buf, &i, "has timeseal; checking")) {
3512 /* We must have called his flag a little too soon */
3513 whiteFlag = blackFlag = FALSE;
3517 if (looking_at(buf, &i, "added * seconds to") ||
3518 looking_at(buf, &i, "seconds were added to")) {
3519 /* Update the clocks */
3520 SendToICS(ics_prefix);
3521 SendToICS("refresh\n");
3525 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3526 ics_clock_paused = TRUE;
3531 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3532 ics_clock_paused = FALSE;
3537 /* Grab player ratings from the Creating: message.
3538 Note we have to check for the special case when
3539 the ICS inserts things like [white] or [black]. */
3540 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3541 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3543 0 player 1 name (not necessarily white)
3545 2 empty, white, or black (IGNORED)
3546 3 player 2 name (not necessarily black)
3549 The names/ratings are sorted out when the game
3550 actually starts (below).
3552 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
3553 player1Rating = string_to_rating(star_match[1]);
3554 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
3555 player2Rating = string_to_rating(star_match[4]);
3557 if (appData.debugMode)
3559 "Ratings from 'Creating:' %s %d, %s %d\n",
3560 player1Name, player1Rating,
3561 player2Name, player2Rating);
3566 /* Improved generic start/end-of-game messages */
3567 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3568 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3569 /* If tkind == 0: */
3570 /* star_match[0] is the game number */
3571 /* [1] is the white player's name */
3572 /* [2] is the black player's name */
3573 /* For end-of-game: */
3574 /* [3] is the reason for the game end */
3575 /* [4] is a PGN end game-token, preceded by " " */
3576 /* For start-of-game: */
3577 /* [3] begins with "Creating" or "Continuing" */
3578 /* [4] is " *" or empty (don't care). */
3579 int gamenum = atoi(star_match[0]);
3580 char *whitename, *blackname, *why, *endtoken;
3581 ChessMove endtype = EndOfFile;
3584 whitename = star_match[1];
3585 blackname = star_match[2];
3586 why = star_match[3];
3587 endtoken = star_match[4];
3589 whitename = star_match[1];
3590 blackname = star_match[3];
3591 why = star_match[5];
3592 endtoken = star_match[6];
3595 /* Game start messages */
3596 if (strncmp(why, "Creating ", 9) == 0 ||
3597 strncmp(why, "Continuing ", 11) == 0) {
3598 gs_gamenum = gamenum;
3599 safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
3600 VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
3602 if (appData.zippyPlay) {
3603 ZippyGameStart(whitename, blackname);
3606 partnerBoardValid = FALSE; // [HGM] bughouse
3610 /* Game end messages */
3611 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3612 ics_gamenum != gamenum) {
3615 while (endtoken[0] == ' ') endtoken++;
3616 switch (endtoken[0]) {
3619 endtype = GameUnfinished;
3622 endtype = BlackWins;
3625 if (endtoken[1] == '/')
3626 endtype = GameIsDrawn;
3628 endtype = WhiteWins;
3631 GameEnds(endtype, why, GE_ICS);
3633 if (appData.zippyPlay && first.initDone) {
3634 ZippyGameEnd(endtype, why);
3635 if (first.pr == NULL) {
3636 /* Start the next process early so that we'll
3637 be ready for the next challenge */
3638 StartChessProgram(&first);
3640 /* Send "new" early, in case this command takes
3641 a long time to finish, so that we'll be ready
3642 for the next challenge. */
3643 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3647 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
3651 if (looking_at(buf, &i, "Removing game * from observation") ||
3652 looking_at(buf, &i, "no longer observing game *") ||
3653 looking_at(buf, &i, "Game * (*) has no examiners")) {
3654 if (gameMode == IcsObserving &&
3655 atoi(star_match[0]) == ics_gamenum)
3657 /* icsEngineAnalyze */
3658 if (appData.icsEngineAnalyze) {
3665 ics_user_moved = FALSE;
3670 if (looking_at(buf, &i, "no longer examining game *")) {
3671 if (gameMode == IcsExamining &&
3672 atoi(star_match[0]) == ics_gamenum)
3676 ics_user_moved = FALSE;
3681 /* Advance leftover_start past any newlines we find,
3682 so only partial lines can get reparsed */
3683 if (looking_at(buf, &i, "\n")) {
3684 prevColor = curColor;
3685 if (curColor != ColorNormal) {
3686 if (oldi > next_out) {
3687 SendToPlayer(&buf[next_out], oldi - next_out);
3690 Colorize(ColorNormal, FALSE);
3691 curColor = ColorNormal;
3693 if (started == STARTED_BOARD) {
3694 started = STARTED_NONE;
3695 parse[parse_pos] = NULLCHAR;
3696 ParseBoard12(parse);
3699 /* Send premove here */
3700 if (appData.premove) {
3702 if (currentMove == 0 &&
3703 gameMode == IcsPlayingWhite &&
3704 appData.premoveWhite) {
3705 snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
3706 if (appData.debugMode)
3707 fprintf(debugFP, "Sending premove:\n");
3709 } else if (currentMove == 1 &&
3710 gameMode == IcsPlayingBlack &&
3711 appData.premoveBlack) {
3712 snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
3713 if (appData.debugMode)
3714 fprintf(debugFP, "Sending premove:\n");
3716 } else if (gotPremove) {
3718 ClearPremoveHighlights();
3719 if (appData.debugMode)
3720 fprintf(debugFP, "Sending premove:\n");
3721 UserMoveEvent(premoveFromX, premoveFromY,
3722 premoveToX, premoveToY,
3727 /* Usually suppress following prompt */
3728 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
3729 while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
3730 if (looking_at(buf, &i, "*% ")) {
3731 savingComment = FALSE;
3736 } else if (started == STARTED_HOLDINGS) {
3738 char new_piece[MSG_SIZ];
3739 started = STARTED_NONE;
3740 parse[parse_pos] = NULLCHAR;
3741 if (appData.debugMode)
3742 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
3743 parse, currentMove);
3744 if (sscanf(parse, " game %d", &gamenum) == 1) {
3745 if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
3746 if (gameInfo.variant == VariantNormal) {
3747 /* [HGM] We seem to switch variant during a game!
3748 * Presumably no holdings were displayed, so we have
3749 * to move the position two files to the right to
3750 * create room for them!
3752 VariantClass newVariant;
3753 switch(gameInfo.boardWidth) { // base guess on board width
3754 case 9: newVariant = VariantShogi; break;
3755 case 10: newVariant = VariantGreat; break;
3756 default: newVariant = VariantCrazyhouse; break;
3758 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
3759 /* Get a move list just to see the header, which
3760 will tell us whether this is really bug or zh */
3761 if (ics_getting_history == H_FALSE) {
3762 ics_getting_history = H_REQUESTED;
3763 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
3767 new_piece[0] = NULLCHAR;
3768 sscanf(parse, "game %d white [%s black [%s <- %s",
3769 &gamenum, white_holding, black_holding,
3771 white_holding[strlen(white_holding)-1] = NULLCHAR;
3772 black_holding[strlen(black_holding)-1] = NULLCHAR;
3773 /* [HGM] copy holdings to board holdings area */
3774 CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
3775 CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
3776 boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
3778 if (appData.zippyPlay && first.initDone) {
3779 ZippyHoldings(white_holding, black_holding,
3783 if (tinyLayout || smallLayout) {
3784 char wh[16], bh[16];
3785 PackHolding(wh, white_holding);
3786 PackHolding(bh, black_holding);
3787 snprintf(str, MSG_SIZ,"[%s-%s] %s-%s", wh, bh,
3788 gameInfo.white, gameInfo.black);
3790 snprintf(str, MSG_SIZ, "%s [%s] vs. %s [%s]",
3791 gameInfo.white, white_holding,
3792 gameInfo.black, black_holding);
3794 if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
3795 DrawPosition(FALSE, boards[currentMove]);
3797 } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
3798 sscanf(parse, "game %d white [%s black [%s <- %s",
3799 &gamenum, white_holding, black_holding,
3801 white_holding[strlen(white_holding)-1] = NULLCHAR;
3802 black_holding[strlen(black_holding)-1] = NULLCHAR;
3803 /* [HGM] copy holdings to partner-board holdings area */
3804 CopyHoldings(partnerBoard, white_holding, WhitePawn);
3805 CopyHoldings(partnerBoard, black_holding, BlackPawn);
3806 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
3807 if(partnerUp) DrawPosition(FALSE, partnerBoard);
3808 if(twoBoards) { partnerUp = 0; flipView = !flipView; }
3811 /* Suppress following prompt */
3812 if (looking_at(buf, &i, "*% ")) {
3813 if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
3814 savingComment = FALSE;
3822 i++; /* skip unparsed character and loop back */
3825 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
3826 // started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
3827 // SendToPlayer(&buf[next_out], i - next_out);
3828 started != STARTED_HOLDINGS && leftover_start > next_out) {
3829 SendToPlayer(&buf[next_out], leftover_start - next_out);
3833 leftover_len = buf_len - leftover_start;
3834 /* if buffer ends with something we couldn't parse,
3835 reparse it after appending the next read */
3837 } else if (count == 0) {
3838 RemoveInputSource(isr);
3839 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
3841 DisplayFatalError(_("Error reading from ICS"), error, 1);
3846 /* Board style 12 looks like this:
3848 <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
3850 * The "<12> " is stripped before it gets to this routine. The two
3851 * trailing 0's (flip state and clock ticking) are later addition, and
3852 * some chess servers may not have them, or may have only the first.
3853 * Additional trailing fields may be added in the future.
3856 #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"
3858 #define RELATION_OBSERVING_PLAYED 0
3859 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
3860 #define RELATION_PLAYING_MYMOVE 1
3861 #define RELATION_PLAYING_NOTMYMOVE -1
3862 #define RELATION_EXAMINING 2
3863 #define RELATION_ISOLATED_BOARD -3
3864 #define RELATION_STARTING_POSITION -4 /* FICS only */
3867 ParseBoard12(string)
3870 GameMode newGameMode;
3871 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0, i;
3872 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time, takeback;
3873 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
3874 char to_play, board_chars[200];
3875 char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
3876 char black[32], white[32];
3878 int prevMove = currentMove;
3881 int fromX, fromY, toX, toY;
3883 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
3884 char *bookHit = NULL; // [HGM] book
3885 Boolean weird = FALSE, reqFlag = FALSE;
3887 fromX = fromY = toX = toY = -1;
3891 if (appData.debugMode)
3892 fprintf(debugFP, _("Parsing board: %s\n"), string);
3894 move_str[0] = NULLCHAR;
3895 elapsed_time[0] = NULLCHAR;
3896 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
3898 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
3899 if(string[i] == ' ') { ranks++; files = 0; }
3901 if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
3904 for(j = 0; j <i; j++) board_chars[j] = string[j];
3905 board_chars[i] = '\0';
3908 n = sscanf(string, PATTERN, &to_play, &double_push,
3909 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
3910 &gamenum, white, black, &relation, &basetime, &increment,
3911 &white_stren, &black_stren, &white_time, &black_time,
3912 &moveNum, str, elapsed_time, move_str, &ics_flip,
3916 snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
3917 DisplayError(str, 0);
3921 /* Convert the move number to internal form */
3922 moveNum = (moveNum - 1) * 2;
3923 if (to_play == 'B') moveNum++;
3924 if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
3925 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
3931 case RELATION_OBSERVING_PLAYED:
3932 case RELATION_OBSERVING_STATIC:
3933 if (gamenum == -1) {
3934 /* Old ICC buglet */
3935 relation = RELATION_OBSERVING_STATIC;
3937 newGameMode = IcsObserving;
3939 case RELATION_PLAYING_MYMOVE:
3940 case RELATION_PLAYING_NOTMYMOVE:
3942 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
3943 IcsPlayingWhite : IcsPlayingBlack;
3945 case RELATION_EXAMINING:
3946 newGameMode = IcsExamining;
3948 case RELATION_ISOLATED_BOARD:
3950 /* Just display this board. If user was doing something else,
3951 we will forget about it until the next board comes. */
3952 newGameMode = IcsIdle;
3954 case RELATION_STARTING_POSITION:
3955 newGameMode = gameMode;
3959 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
3960 && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
3961 // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
3963 for (k = 0; k < ranks; k++) {
3964 for (j = 0; j < files; j++)
3965 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
3966 if(gameInfo.holdingsWidth > 1) {
3967 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
3968 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
3971 CopyBoard(partnerBoard, board);
3972 if(toSqr = strchr(str, '/')) { // extract highlights from long move
3973 partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
3974 partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
3975 } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
3976 if(toSqr = strchr(str, '-')) {
3977 partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
3978 partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
3979 } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
3980 if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
3981 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
3982 if(partnerUp) DrawPosition(FALSE, partnerBoard);
3983 if(twoBoards) { partnerUp = 0; flipView = !flipView; } // [HGM] dual
3984 snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time/60000, (white_time%60000)/1000,
3985 (black_time/60000), (black_time%60000)/1000, white_stren, black_stren, to_play);
3986 DisplayMessage(partnerStatus, "");
3987 partnerBoardValid = TRUE;
3991 /* Modify behavior for initial board display on move listing
3994 switch (ics_getting_history) {
3998 case H_GOT_REQ_HEADER:
3999 case H_GOT_UNREQ_HEADER:
4000 /* This is the initial position of the current game */
4001 gamenum = ics_gamenum;
4002 moveNum = 0; /* old ICS bug workaround */
4003 if (to_play == 'B') {
4004 startedFromSetupPosition = TRUE;
4005 blackPlaysFirst = TRUE;
4007 if (forwardMostMove == 0) forwardMostMove = 1;
4008 if (backwardMostMove == 0) backwardMostMove = 1;
4009 if (currentMove == 0) currentMove = 1;
4011 newGameMode = gameMode;
4012 relation = RELATION_STARTING_POSITION; /* ICC needs this */
4014 case H_GOT_UNWANTED_HEADER:
4015 /* This is an initial board that we don't want */
4017 case H_GETTING_MOVES:
4018 /* Should not happen */
4019 DisplayError(_("Error gathering move list: extra board"), 0);
4020 ics_getting_history = H_FALSE;
4024 if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4025 weird && (int)gameInfo.variant < (int)VariantShogi) {
4026 /* [HGM] We seem to have switched variant unexpectedly
4027 * Try to guess new variant from board size
4029 VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4030 if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4031 if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4032 if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4033 if(ranks == 9 && files == 9) newVariant = VariantShogi; else
4034 if(!weird) newVariant = VariantNormal;
4035 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4036 /* Get a move list just to see the header, which
4037 will tell us whether this is really bug or zh */
4038 if (ics_getting_history == H_FALSE) {
4039 ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4040 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4045 /* Take action if this is the first board of a new game, or of a
4046 different game than is currently being displayed. */
4047 if (gamenum != ics_gamenum || newGameMode != gameMode ||
4048 relation == RELATION_ISOLATED_BOARD) {
4050 /* Forget the old game and get the history (if any) of the new one */
4051 if (gameMode != BeginningOfGame) {
4055 if (appData.autoRaiseBoard) BoardToTop();
4057 if (gamenum == -1) {
4058 newGameMode = IcsIdle;
4059 } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4060 appData.getMoveList && !reqFlag) {
4061 /* Need to get game history */
4062 ics_getting_history = H_REQUESTED;
4063 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4067 /* Initially flip the board to have black on the bottom if playing
4068 black or if the ICS flip flag is set, but let the user change
4069 it with the Flip View button. */
4070 flipView = appData.autoFlipView ?
4071 (newGameMode == IcsPlayingBlack) || ics_flip :
4074 /* Done with values from previous mode; copy in new ones */
4075 gameMode = newGameMode;
4077 ics_gamenum = gamenum;
4078 if (gamenum == gs_gamenum) {
4079 int klen = strlen(gs_kind);
4080 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4081 snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4082 gameInfo.event = StrSave(str);
4084 gameInfo.event = StrSave("ICS game");
4086 gameInfo.site = StrSave(appData.icsHost);
4087 gameInfo.date = PGNDate();
4088 gameInfo.round = StrSave("-");
4089 gameInfo.white = StrSave(white);
4090 gameInfo.black = StrSave(black);
4091 timeControl = basetime * 60 * 1000;
4093 timeIncrement = increment * 1000;
4094 movesPerSession = 0;
4095 gameInfo.timeControl = TimeControlTagValue();
4096 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4097 if (appData.debugMode) {
4098 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4099 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4100 setbuf(debugFP, NULL);
4103 gameInfo.outOfBook = NULL;
4105 /* Do we have the ratings? */
4106 if (strcmp(player1Name, white) == 0 &&
4107 strcmp(player2Name, black) == 0) {
4108 if (appData.debugMode)
4109 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4110 player1Rating, player2Rating);
4111 gameInfo.whiteRating = player1Rating;
4112 gameInfo.blackRating = player2Rating;
4113 } else if (strcmp(player2Name, white) == 0 &&
4114 strcmp(player1Name, black) == 0) {
4115 if (appData.debugMode)
4116 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4117 player2Rating, player1Rating);
4118 gameInfo.whiteRating = player2Rating;
4119 gameInfo.blackRating = player1Rating;
4121 player1Name[0] = player2Name[0] = NULLCHAR;
4123 /* Silence shouts if requested */
4124 if (appData.quietPlay &&
4125 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4126 SendToICS(ics_prefix);
4127 SendToICS("set shout 0\n");
4131 /* Deal with midgame name changes */
4133 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4134 if (gameInfo.white) free(gameInfo.white);
4135 gameInfo.white = StrSave(white);
4137 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4138 if (gameInfo.black) free(gameInfo.black);
4139 gameInfo.black = StrSave(black);
4143 /* Throw away game result if anything actually changes in examine mode */
4144 if (gameMode == IcsExamining && !newGame) {
4145 gameInfo.result = GameUnfinished;
4146 if (gameInfo.resultDetails != NULL) {
4147 free(gameInfo.resultDetails);
4148 gameInfo.resultDetails = NULL;
4152 /* In pausing && IcsExamining mode, we ignore boards coming
4153 in if they are in a different variation than we are. */
4154 if (pauseExamInvalid) return;
4155 if (pausing && gameMode == IcsExamining) {
4156 if (moveNum <= pauseExamForwardMostMove) {
4157 pauseExamInvalid = TRUE;
4158 forwardMostMove = pauseExamForwardMostMove;
4163 if (appData.debugMode) {
4164 fprintf(debugFP, "load %dx%d board\n", files, ranks);
4166 /* Parse the board */
4167 for (k = 0; k < ranks; k++) {
4168 for (j = 0; j < files; j++)
4169 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4170 if(gameInfo.holdingsWidth > 1) {
4171 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4172 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4175 CopyBoard(boards[moveNum], board);
4176 boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4178 startedFromSetupPosition =
4179 !CompareBoards(board, initialPosition);
4180 if(startedFromSetupPosition)
4181 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4184 /* [HGM] Set castling rights. Take the outermost Rooks,
4185 to make it also work for FRC opening positions. Note that board12
4186 is really defective for later FRC positions, as it has no way to
4187 indicate which Rook can castle if they are on the same side of King.
4188 For the initial position we grant rights to the outermost Rooks,
4189 and remember thos rights, and we then copy them on positions
4190 later in an FRC game. This means WB might not recognize castlings with
4191 Rooks that have moved back to their original position as illegal,
4192 but in ICS mode that is not its job anyway.
4194 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4195 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4197 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4198 if(board[0][i] == WhiteRook) j = i;
4199 initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4200 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4201 if(board[0][i] == WhiteRook) j = i;
4202 initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4203 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4204 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4205 initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4206 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4207 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4208 initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4210 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4211 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4212 if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4213 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4214 if(board[BOARD_HEIGHT-1][k] == bKing)
4215 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4216 if(gameInfo.variant == VariantTwoKings) {
4217 // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4218 if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4219 if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4222 r = boards[moveNum][CASTLING][0] = initialRights[0];
4223 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4224 r = boards[moveNum][CASTLING][1] = initialRights[1];
4225 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4226 r = boards[moveNum][CASTLING][3] = initialRights[3];
4227 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4228 r = boards[moveNum][CASTLING][4] = initialRights[4];
4229 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4230 /* wildcastle kludge: always assume King has rights */
4231 r = boards[moveNum][CASTLING][2] = initialRights[2];
4232 r = boards[moveNum][CASTLING][5] = initialRights[5];
4234 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4235 boards[moveNum][EP_STATUS] = double_push == -1 ? EP_NONE : double_push + BOARD_LEFT;
4238 if (ics_getting_history == H_GOT_REQ_HEADER ||
4239 ics_getting_history == H_GOT_UNREQ_HEADER) {
4240 /* This was an initial position from a move list, not
4241 the current position */
4245 /* Update currentMove and known move number limits */
4246 newMove = newGame || moveNum > forwardMostMove;
4249 forwardMostMove = backwardMostMove = currentMove = moveNum;
4250 if (gameMode == IcsExamining && moveNum == 0) {
4251 /* Workaround for ICS limitation: we are not told the wild
4252 type when starting to examine a game. But if we ask for
4253 the move list, the move list header will tell us */
4254 ics_getting_history = H_REQUESTED;
4255 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4258 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4259 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4261 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4262 /* [HGM] applied this also to an engine that is silently watching */
4263 if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4264 (gameMode == IcsObserving || gameMode == IcsExamining) &&
4265 gameInfo.variant == currentlyInitializedVariant) {
4266 takeback = forwardMostMove - moveNum;
4267 for (i = 0; i < takeback; i++) {
4268 if (appData.debugMode) fprintf(debugFP, "take back move\n");
4269 SendToProgram("undo\n", &first);
4274 forwardMostMove = moveNum;
4275 if (!pausing || currentMove > forwardMostMove)
4276 currentMove = forwardMostMove;
4278 /* New part of history that is not contiguous with old part */
4279 if (pausing && gameMode == IcsExamining) {
4280 pauseExamInvalid = TRUE;
4281 forwardMostMove = pauseExamForwardMostMove;
4284 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4286 if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4287 // [HGM] when we will receive the move list we now request, it will be
4288 // fed to the engine from the first move on. So if the engine is not
4289 // in the initial position now, bring it there.
4290 InitChessProgram(&first, 0);
4293 ics_getting_history = H_REQUESTED;
4294 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4297 forwardMostMove = backwardMostMove = currentMove = moveNum;
4300 /* Update the clocks */
4301 if (strchr(elapsed_time, '.')) {
4303 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4304 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4306 /* Time is in seconds */
4307 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4308 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4313 if (appData.zippyPlay && newGame &&
4314 gameMode != IcsObserving && gameMode != IcsIdle &&
4315 gameMode != IcsExamining)
4316 ZippyFirstBoard(moveNum, basetime, increment);
4319 /* Put the move on the move list, first converting
4320 to canonical algebraic form. */
4322 if (appData.debugMode) {
4323 if (appData.debugMode) { int f = forwardMostMove;
4324 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4325 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4326 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4328 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4329 fprintf(debugFP, "moveNum = %d\n", moveNum);
4330 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4331 setbuf(debugFP, NULL);
4333 if (moveNum <= backwardMostMove) {
4334 /* We don't know what the board looked like before
4336 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4337 strcat(parseList[moveNum - 1], " ");
4338 strcat(parseList[moveNum - 1], elapsed_time);
4339 moveList[moveNum - 1][0] = NULLCHAR;
4340 } else if (strcmp(move_str, "none") == 0) {
4341 // [HGM] long SAN: swapped order; test for 'none' before parsing move
4342 /* Again, we don't know what the board looked like;
4343 this is really the start of the game. */
4344 parseList[moveNum - 1][0] = NULLCHAR;
4345 moveList[moveNum - 1][0] = NULLCHAR;
4346 backwardMostMove = moveNum;
4347 startedFromSetupPosition = TRUE;
4348 fromX = fromY = toX = toY = -1;
4350 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4351 // So we parse the long-algebraic move string in stead of the SAN move
4352 int valid; char buf[MSG_SIZ], *prom;
4354 if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4355 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4356 // str looks something like "Q/a1-a2"; kill the slash
4358 snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4359 else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4360 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4361 strcat(buf, prom); // long move lacks promo specification!
4362 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4363 if(appData.debugMode)
4364 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4365 safeStrCpy(move_str, buf, MSG_SIZ);
4367 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4368 &fromX, &fromY, &toX, &toY, &promoChar)
4369 || ParseOneMove(buf, moveNum - 1, &moveType,
4370 &fromX, &fromY, &toX, &toY, &promoChar);
4371 // end of long SAN patch
4373 (void) CoordsToAlgebraic(boards[moveNum - 1],
4374 PosFlags(moveNum - 1),
4375 fromY, fromX, toY, toX, promoChar,
4376 parseList[moveNum-1]);
4377 switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4383 if(gameInfo.variant != VariantShogi)
4384 strcat(parseList[moveNum - 1], "+");
4387 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4388 strcat(parseList[moveNum - 1], "#");
4391 strcat(parseList[moveNum - 1], " ");
4392 strcat(parseList[moveNum - 1], elapsed_time);
4393 /* currentMoveString is set as a side-effect of ParseOneMove */
4394 if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4395 safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4396 strcat(moveList[moveNum - 1], "\n");
4398 if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper
4399 && gameInfo.variant != VariantGreat) // inherit info that ICS does not give from previous board
4400 for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4401 ChessSquare old, new = boards[moveNum][k][j];
4402 if(fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4403 old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4404 if(old == new) continue;
4405 if(old == PROMOTED new) boards[moveNum][k][j] = old; // prevent promoted pieces to revert to primordial ones
4406 else if(new == WhiteWazir || new == BlackWazir) {
4407 if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4408 boards[moveNum][k][j] = PROMOTED old; // choose correct type of Gold in promotion
4409 else boards[moveNum][k][j] = old; // preserve type of Gold
4410 } else if((old == WhitePawn || old == BlackPawn) && new != EmptySquare) // Pawn promotions (but not e.p.capture!)
4411 boards[moveNum][k][j] = PROMOTED new; // use non-primordial representation of chosen piece
4414 /* Move from ICS was illegal!? Punt. */
4415 if (appData.debugMode) {
4416 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4417 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4419 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4420 strcat(parseList[moveNum - 1], " ");
4421 strcat(parseList[moveNum - 1], elapsed_time);
4422 moveList[moveNum - 1][0] = NULLCHAR;
4423 fromX = fromY = toX = toY = -1;
4426 if (appData.debugMode) {
4427 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4428 setbuf(debugFP, NULL);
4432 /* Send move to chess program (BEFORE animating it). */
4433 if (appData.zippyPlay && !newGame && newMove &&
4434 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4436 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4437 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4438 if (moveList[moveNum - 1][0] == NULLCHAR) {
4439 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4441 DisplayError(str, 0);
4443 if (first.sendTime) {
4444 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4446 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4447 if (firstMove && !bookHit) {
4449 if (first.useColors) {
4450 SendToProgram(gameMode == IcsPlayingWhite ?
4452 "black\ngo\n", &first);
4454 SendToProgram("go\n", &first);
4456 first.maybeThinking = TRUE;
4459 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4460 if (moveList[moveNum - 1][0] == NULLCHAR) {
4461 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4462 DisplayError(str, 0);
4464 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4465 SendMoveToProgram(moveNum - 1, &first);
4472 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
4473 /* If move comes from a remote source, animate it. If it
4474 isn't remote, it will have already been animated. */
4475 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
4476 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
4478 if (!pausing && appData.highlightLastMove) {
4479 SetHighlights(fromX, fromY, toX, toY);
4483 /* Start the clocks */
4484 whiteFlag = blackFlag = FALSE;
4485 appData.clockMode = !(basetime == 0 && increment == 0);
4487 ics_clock_paused = TRUE;
4489 } else if (ticking == 1) {
4490 ics_clock_paused = FALSE;
4492 if (gameMode == IcsIdle ||
4493 relation == RELATION_OBSERVING_STATIC ||
4494 relation == RELATION_EXAMINING ||
4496 DisplayBothClocks();
4500 /* Display opponents and material strengths */
4501 if (gameInfo.variant != VariantBughouse &&
4502 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
4503 if (tinyLayout || smallLayout) {
4504 if(gameInfo.variant == VariantNormal)
4505 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
4506 gameInfo.white, white_stren, gameInfo.black, black_stren,
4507 basetime, increment);
4509 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
4510 gameInfo.white, white_stren, gameInfo.black, black_stren,
4511 basetime, increment, (int) gameInfo.variant);
4513 if(gameInfo.variant == VariantNormal)
4514 snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d}",
4515 gameInfo.white, white_stren, gameInfo.black, black_stren,
4516 basetime, increment);
4518 snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d %s}",
4519 gameInfo.white, white_stren, gameInfo.black, black_stren,
4520 basetime, increment, VariantName(gameInfo.variant));
4523 if (appData.debugMode) {
4524 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
4529 /* Display the board */
4530 if (!pausing && !appData.noGUI) {
4532 if (appData.premove)
4534 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
4535 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
4536 ClearPremoveHighlights();
4538 j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
4539 if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
4540 DrawPosition(j, boards[currentMove]);
4542 DisplayMove(moveNum - 1);
4543 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
4544 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
4545 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
4546 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
4550 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
4552 if(bookHit) { // [HGM] book: simulate book reply
4553 static char bookMove[MSG_SIZ]; // a bit generous?
4555 programStats.nodes = programStats.depth = programStats.time =
4556 programStats.score = programStats.got_only_move = 0;
4557 sprintf(programStats.movelist, "%s (xbook)", bookHit);
4559 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
4560 strcat(bookMove, bookHit);
4561 HandleMachineMove(bookMove, &first);
4570 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
4571 ics_getting_history = H_REQUESTED;
4572 snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
4578 AnalysisPeriodicEvent(force)
4581 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
4582 && !force) || !appData.periodicUpdates)
4585 /* Send . command to Crafty to collect stats */
4586 SendToProgram(".\n", &first);
4588 /* Don't send another until we get a response (this makes
4589 us stop sending to old Crafty's which don't understand
4590 the "." command (sending illegal cmds resets node count & time,
4591 which looks bad)) */
4592 programStats.ok_to_send = 0;
4595 void ics_update_width(new_width)
4598 ics_printf("set width %d\n", new_width);
4602 SendMoveToProgram(moveNum, cps)
4604 ChessProgramState *cps;
4608 if (cps->useUsermove) {
4609 SendToProgram("usermove ", cps);
4613 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
4614 int len = space - parseList[moveNum];
4615 memcpy(buf, parseList[moveNum], len);
4617 buf[len] = NULLCHAR;
4619 snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
4621 SendToProgram(buf, cps);
4623 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
4624 AlphaRank(moveList[moveNum], 4);
4625 SendToProgram(moveList[moveNum], cps);
4626 AlphaRank(moveList[moveNum], 4); // and back
4628 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
4629 * the engine. It would be nice to have a better way to identify castle
4631 if((gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom)
4632 && cps->useOOCastle) {
4633 int fromX = moveList[moveNum][0] - AAA;
4634 int fromY = moveList[moveNum][1] - ONE;
4635 int toX = moveList[moveNum][2] - AAA;
4636 int toY = moveList[moveNum][3] - ONE;
4637 if((boards[moveNum][fromY][fromX] == WhiteKing
4638 && boards[moveNum][toY][toX] == WhiteRook)
4639 || (boards[moveNum][fromY][fromX] == BlackKing
4640 && boards[moveNum][toY][toX] == BlackRook)) {
4641 if(toX > fromX) SendToProgram("O-O\n", cps);
4642 else SendToProgram("O-O-O\n", cps);
4644 else SendToProgram(moveList[moveNum], cps);
4646 else SendToProgram(moveList[moveNum], cps);
4647 /* End of additions by Tord */
4650 /* [HGM] setting up the opening has brought engine in force mode! */
4651 /* Send 'go' if we are in a mode where machine should play. */
4652 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
4653 (gameMode == TwoMachinesPlay ||
4655 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
4657 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
4658 SendToProgram("go\n", cps);
4659 if (appData.debugMode) {
4660 fprintf(debugFP, "(extra)\n");
4663 setboardSpoiledMachineBlack = 0;
4667 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar)
4669 int fromX, fromY, toX, toY;
4672 char user_move[MSG_SIZ];
4676 snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
4677 (int)moveType, fromX, fromY, toX, toY);
4678 DisplayError(user_move + strlen("say "), 0);
4680 case WhiteKingSideCastle:
4681 case BlackKingSideCastle:
4682 case WhiteQueenSideCastleWild:
4683 case BlackQueenSideCastleWild:
4685 case WhiteHSideCastleFR:
4686 case BlackHSideCastleFR:
4688 snprintf(user_move, MSG_SIZ, "o-o\n");
4690 case WhiteQueenSideCastle:
4691 case BlackQueenSideCastle:
4692 case WhiteKingSideCastleWild:
4693 case BlackKingSideCastleWild:
4695 case WhiteASideCastleFR:
4696 case BlackASideCastleFR:
4698 snprintf(user_move, MSG_SIZ, "o-o-o\n");
4700 case WhiteNonPromotion:
4701 case BlackNonPromotion:
4702 sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4704 case WhitePromotion:
4705 case BlackPromotion:
4706 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
4707 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
4708 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4709 PieceToChar(WhiteFerz));
4710 else if(gameInfo.variant == VariantGreat)
4711 snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
4712 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4713 PieceToChar(WhiteMan));
4715 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
4716 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
4722 snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
4723 ToUpper(PieceToChar((ChessSquare) fromX)),
4724 AAA + toX, ONE + toY);
4726 case IllegalMove: /* could be a variant we don't quite understand */
4727 if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
4729 case WhiteCapturesEnPassant:
4730 case BlackCapturesEnPassant:
4731 snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
4732 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
4735 SendToICS(user_move);
4736 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
4737 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
4742 { // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
4743 int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
4744 static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
4745 if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
4746 DisplayError("You cannot do this while you are playing or observing", 0);
4749 if(gameMode != IcsExamining) { // is this ever not the case?
4750 char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
4752 if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
4753 snprintf(command,MSG_SIZ, "match %s", ics_handle);
4754 } else { // on FICS we must first go to general examine mode
4755 safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
4757 if(gameInfo.variant != VariantNormal) {
4758 // try figure out wild number, as xboard names are not always valid on ICS
4759 for(i=1; i<=36; i++) {
4760 snprintf(buf, MSG_SIZ, "wild/%d", i);
4761 if(StringToVariant(buf) == gameInfo.variant) break;
4763 if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
4764 else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
4765 else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
4766 } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
4767 SendToICS(ics_prefix);
4769 if(startedFromSetupPosition || backwardMostMove != 0) {
4770 fen = PositionToFEN(backwardMostMove, NULL);
4771 if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
4772 snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
4774 } else { // FICS: everything has to set by separate bsetup commands
4775 p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
4776 snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
4778 if(!WhiteOnMove(backwardMostMove)) {
4779 SendToICS("bsetup tomove black\n");
4781 i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
4782 snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
4784 i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
4785 snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
4787 i = boards[backwardMostMove][EP_STATUS];
4788 if(i >= 0) { // set e.p.
4789 snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
4795 if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
4796 SendToICS("bsetup done\n"); // switch to normal examining.
4798 for(i = backwardMostMove; i<last; i++) {
4800 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
4803 SendToICS(ics_prefix);
4804 SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
4808 CoordsToComputerAlgebraic(rf, ff, rt, ft, promoChar, move)
4813 if (rf == DROP_RANK) {
4814 sprintf(move, "%c@%c%c\n",
4815 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
4817 if (promoChar == 'x' || promoChar == NULLCHAR) {
4818 sprintf(move, "%c%c%c%c\n",
4819 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
4821 sprintf(move, "%c%c%c%c%c\n",
4822 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
4828 ProcessICSInitScript(f)
4833 while (fgets(buf, MSG_SIZ, f)) {
4834 SendToICSDelayed(buf,(long)appData.msLoginDelay);
4841 static int lastX, lastY, selectFlag, dragging;
4846 ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
4847 if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
4848 if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
4849 if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
4850 if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
4851 if(fromY != BOARD_HEIGHT-2 && fromY != 1) pawn = EmptySquare;
4854 if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
4855 else if((int)promoSweep == -1) promoSweep = WhiteKing;
4856 else if(promoSweep == BlackPawn && step < 0) promoSweep = WhitePawn;
4857 else if(promoSweep == WhiteKing && step > 0) promoSweep = BlackKing;
4859 } while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' || promoSweep == pawn ||
4860 appData.testLegality && (promoSweep == king ||
4861 gameInfo.variant == VariantShogi && promoSweep != PROMOTED last && last != PROMOTED promoSweep && last != promoSweep));
4862 ChangeDragPiece(promoSweep);
4865 int PromoScroll(int x, int y)
4869 if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
4870 if(abs(x - lastX) < 15 && abs(y - lastY) < 15) return FALSE;
4871 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
4872 if(!step) return FALSE;
4873 lastX = x; lastY = y;
4874 if((promoSweep < BlackPawn) == flipView) step = -step;
4875 if(step > 0) selectFlag = 1;
4876 if(!selectFlag) Sweep(step);
4883 ChessSquare piece = boards[currentMove][toY][toX];
4886 if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
4887 if((int)pieceSweep == -1) pieceSweep = BlackKing;
4888 if(!step) step = -1;
4889 } while(PieceToChar(pieceSweep) == '.');
4890 boards[currentMove][toY][toX] = pieceSweep;
4891 DrawPosition(FALSE, boards[currentMove]);
4892 boards[currentMove][toY][toX] = piece;
4894 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
4896 AlphaRank(char *move, int n)
4898 // char *p = move, c; int x, y;
4900 if (appData.debugMode) {
4901 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
4905 move[2]>='0' && move[2]<='9' &&
4906 move[3]>='a' && move[3]<='x' ) {
4908 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4909 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4911 if(move[0]>='0' && move[0]<='9' &&
4912 move[1]>='a' && move[1]<='x' &&
4913 move[2]>='0' && move[2]<='9' &&
4914 move[3]>='a' && move[3]<='x' ) {
4915 /* input move, Shogi -> normal */
4916 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
4917 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
4918 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
4919 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
4922 move[3]>='0' && move[3]<='9' &&
4923 move[2]>='a' && move[2]<='x' ) {
4925 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4926 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4929 move[0]>='a' && move[0]<='x' &&
4930 move[3]>='0' && move[3]<='9' &&
4931 move[2]>='a' && move[2]<='x' ) {
4932 /* output move, normal -> Shogi */
4933 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
4934 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
4935 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
4936 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
4937 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
4939 if (appData.debugMode) {
4940 fprintf(debugFP, " out = '%s'\n", move);
4944 char yy_textstr[8000];
4946 /* Parser for moves from gnuchess, ICS, or user typein box */
4948 ParseOneMove(move, moveNum, moveType, fromX, fromY, toX, toY, promoChar)
4951 ChessMove *moveType;
4952 int *fromX, *fromY, *toX, *toY;
4955 *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
4957 switch (*moveType) {
4958 case WhitePromotion:
4959 case BlackPromotion:
4960 case WhiteNonPromotion:
4961 case BlackNonPromotion:
4963 case WhiteCapturesEnPassant:
4964 case BlackCapturesEnPassant:
4965 case WhiteKingSideCastle:
4966 case WhiteQueenSideCastle:
4967 case BlackKingSideCastle:
4968 case BlackQueenSideCastle:
4969 case WhiteKingSideCastleWild:
4970 case WhiteQueenSideCastleWild:
4971 case BlackKingSideCastleWild:
4972 case BlackQueenSideCastleWild:
4973 /* Code added by Tord: */
4974 case WhiteHSideCastleFR:
4975 case WhiteASideCastleFR:
4976 case BlackHSideCastleFR:
4977 case BlackASideCastleFR:
4978 /* End of code added by Tord */
4979 case IllegalMove: /* bug or odd chess variant */
4980 *fromX = currentMoveString[0] - AAA;
4981 *fromY = currentMoveString[1] - ONE;
4982 *toX = currentMoveString[2] - AAA;
4983 *toY = currentMoveString[3] - ONE;
4984 *promoChar = currentMoveString[4];
4985 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
4986 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
4987 if (appData.debugMode) {
4988 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
4990 *fromX = *fromY = *toX = *toY = 0;
4993 if (appData.testLegality) {
4994 return (*moveType != IllegalMove);
4996 return !(*fromX == *toX && *fromY == *toY) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
4997 WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
5002 *fromX = *moveType == WhiteDrop ?
5003 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5004 (int) CharToPiece(ToLower(currentMoveString[0]));
5006 *toX = currentMoveString[2] - AAA;
5007 *toY = currentMoveString[3] - ONE;
5008 *promoChar = NULLCHAR;
5012 case ImpossibleMove:
5022 if (appData.debugMode) {
5023 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
5026 *fromX = *fromY = *toX = *toY = 0;
5027 *promoChar = NULLCHAR;
5034 ParsePV(char *pv, Boolean storeComments)
5035 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
5036 int fromX, fromY, toX, toY; char promoChar;
5041 endPV = forwardMostMove;
5043 while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
5044 if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
5045 valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
5046 if(appData.debugMode){
5047 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);
5049 if(!valid && nr == 0 &&
5050 ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
5051 nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
5052 // Hande case where played move is different from leading PV move
5053 CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
5054 CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
5055 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
5056 if(!CompareBoards(boards[endPV], boards[endPV+2])) {
5057 endPV += 2; // if position different, keep this
5058 moveList[endPV-1][0] = fromX + AAA;
5059 moveList[endPV-1][1] = fromY + ONE;
5060 moveList[endPV-1][2] = toX + AAA;
5061 moveList[endPV-1][3] = toY + ONE;
5062 parseList[endPV-1][0] = NULLCHAR;
5063 safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
5066 pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
5067 if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5068 if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5069 if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5070 valid++; // allow comments in PV
5074 if(endPV+1 > framePtr) break; // no space, truncate
5077 CopyBoard(boards[endPV], boards[endPV-1]);
5078 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5079 moveList[endPV-1][0] = fromX + AAA;
5080 moveList[endPV-1][1] = fromY + ONE;
5081 moveList[endPV-1][2] = toX + AAA;
5082 moveList[endPV-1][3] = toY + ONE;
5083 moveList[endPV-1][4] = promoChar;
5084 moveList[endPV-1][5] = NULLCHAR;
5085 strncat(moveList[endPV-1], "\n", MOVE_LEN);
5087 CoordsToAlgebraic(boards[endPV - 1],
5088 PosFlags(endPV - 1),
5089 fromY, fromX, toY, toX, promoChar,
5090 parseList[endPV - 1]);
5092 parseList[endPV-1][0] = NULLCHAR;
5094 currentMove = endPV;
5095 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5096 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5097 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5098 DrawPosition(TRUE, boards[currentMove]);
5102 LoadMultiPV(int x, int y, char *buf, int index, int *start, int *end)
5107 if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5108 lastX = x; lastY = y;
5109 while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5111 while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5112 if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5114 do{ while(buf[index] && buf[index] != '\n') index++;
5115 } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5117 ParsePV(buf+startPV, FALSE);
5118 *start = startPV; *end = index-1;
5123 LoadPV(int x, int y)
5124 { // called on right mouse click to load PV
5125 int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5126 lastX = x; lastY = y;
5127 ParsePV(lastPV[which], FALSE); // load the PV of the thinking engine in the boards array.
5134 if(endPV < 0) return;
5136 currentMove = forwardMostMove;
5137 ClearPremoveHighlights();
5138 DrawPosition(TRUE, boards[currentMove]);
5142 MovePV(int x, int y, int h)
5143 { // step through PV based on mouse coordinates (called on mouse move)
5144 int margin = h>>3, step = 0;
5146 // we must somehow check if right button is still down (might be released off board!)
5147 if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
5148 if(abs(x - lastX) < 7 && abs(y - lastY) < 7) return;
5149 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5151 lastX = x; lastY = y;
5153 if(pieceSweep != EmptySquare) { NextPiece(step); return; }
5154 if(endPV < 0) return;
5155 if(y < margin) step = 1; else
5156 if(y > h - margin) step = -1;
5157 if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5158 currentMove += step;
5159 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5160 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5161 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5162 DrawPosition(FALSE, boards[currentMove]);
5166 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5167 // All positions will have equal probability, but the current method will not provide a unique
5168 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5174 int piecesLeft[(int)BlackPawn];
5175 int seed, nrOfShuffles;
5177 void GetPositionNumber()
5178 { // sets global variable seed
5181 seed = appData.defaultFrcPosition;
5182 if(seed < 0) { // randomize based on time for negative FRC position numbers
5183 for(i=0; i<50; i++) seed += random();
5184 seed = random() ^ random() >> 8 ^ random() << 8;
5185 if(seed<0) seed = -seed;
5189 int put(Board board, int pieceType, int rank, int n, int shade)
5190 // put the piece on the (n-1)-th empty squares of the given shade
5194 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5195 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5196 board[rank][i] = (ChessSquare) pieceType;
5197 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5199 piecesLeft[pieceType]--;
5207 void AddOnePiece(Board board, int pieceType, int rank, int shade)
5208 // calculate where the next piece goes, (any empty square), and put it there
5212 i = seed % squaresLeft[shade];
5213 nrOfShuffles *= squaresLeft[shade];
5214 seed /= squaresLeft[shade];
5215 put(board, pieceType, rank, i, shade);
5218 void AddTwoPieces(Board board, int pieceType, int rank)
5219 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5221 int i, n=squaresLeft[ANY], j=n-1, k;
5223 k = n*(n-1)/2; // nr of possibilities, not counting permutations
5224 i = seed % k; // pick one
5227 while(i >= j) i -= j--;
5228 j = n - 1 - j; i += j;
5229 put(board, pieceType, rank, j, ANY);
5230 put(board, pieceType, rank, i, ANY);
5233 void SetUpShuffle(Board board, int number)
5237 GetPositionNumber(); nrOfShuffles = 1;
5239 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5240 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
5241 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5243 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5245 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5246 p = (int) board[0][i];
5247 if(p < (int) BlackPawn) piecesLeft[p] ++;
5248 board[0][i] = EmptySquare;
5251 if(PosFlags(0) & F_ALL_CASTLE_OK) {
5252 // shuffles restricted to allow normal castling put KRR first
5253 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5254 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5255 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5256 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5257 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5258 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5259 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
5260 put(board, WhiteRook, 0, 0, ANY);
5261 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
5264 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
5265 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
5266 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
5267 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
5268 while(piecesLeft[p] >= 2) {
5269 AddOnePiece(board, p, 0, LITE);
5270 AddOnePiece(board, p, 0, DARK);
5272 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
5275 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
5276 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
5277 // but we leave King and Rooks for last, to possibly obey FRC restriction
5278 if(p == (int)WhiteRook) continue;
5279 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
5280 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
5283 // now everything is placed, except perhaps King (Unicorn) and Rooks
5285 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
5286 // Last King gets castling rights
5287 while(piecesLeft[(int)WhiteUnicorn]) {
5288 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5289 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5292 while(piecesLeft[(int)WhiteKing]) {
5293 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5294 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5299 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
5300 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
5303 // Only Rooks can be left; simply place them all
5304 while(piecesLeft[(int)WhiteRook]) {
5305 i = put(board, WhiteRook, 0, 0, ANY);
5306 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
5309 initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
5311 initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
5314 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
5315 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
5318 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
5321 int SetCharTable( char *table, const char * map )
5322 /* [HGM] moved here from winboard.c because of its general usefulness */
5323 /* Basically a safe strcpy that uses the last character as King */
5325 int result = FALSE; int NrPieces;
5327 if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
5328 && NrPieces >= 12 && !(NrPieces&1)) {
5329 int i; /* [HGM] Accept even length from 12 to 34 */
5331 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
5332 for( i=0; i<NrPieces/2-1; i++ ) {
5334 table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
5336 table[(int) WhiteKing] = map[NrPieces/2-1];
5337 table[(int) BlackKing] = map[NrPieces-1];
5345 void Prelude(Board board)
5346 { // [HGM] superchess: random selection of exo-pieces
5347 int i, j, k; ChessSquare p;
5348 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
5350 GetPositionNumber(); // use FRC position number
5352 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
5353 SetCharTable(pieceToChar, appData.pieceToCharTable);
5354 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
5355 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
5358 j = seed%4; seed /= 4;
5359 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5360 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5361 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5362 j = seed%3 + (seed%3 >= j); seed /= 3;
5363 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5364 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5365 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5366 j = seed%3; seed /= 3;
5367 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5368 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5369 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5370 j = seed%2 + (seed%2 >= j); seed /= 2;
5371 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5372 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5373 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5374 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
5375 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
5376 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
5377 put(board, exoPieces[0], 0, 0, ANY);
5378 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
5382 InitPosition(redraw)
5385 ChessSquare (* pieces)[BOARD_FILES];
5386 int i, j, pawnRow, overrule,
5387 oldx = gameInfo.boardWidth,
5388 oldy = gameInfo.boardHeight,
5389 oldh = gameInfo.holdingsWidth;
5392 if(appData.icsActive) shuffleOpenings = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
5394 /* [AS] Initialize pv info list [HGM] and game status */
5396 for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
5397 pvInfoList[i].depth = 0;
5398 boards[i][EP_STATUS] = EP_NONE;
5399 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
5402 initialRulePlies = 0; /* 50-move counter start */
5404 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
5405 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
5409 /* [HGM] logic here is completely changed. In stead of full positions */
5410 /* the initialized data only consist of the two backranks. The switch */
5411 /* selects which one we will use, which is than copied to the Board */
5412 /* initialPosition, which for the rest is initialized by Pawns and */
5413 /* empty squares. This initial position is then copied to boards[0], */
5414 /* possibly after shuffling, so that it remains available. */
5416 gameInfo.holdingsWidth = 0; /* default board sizes */
5417 gameInfo.boardWidth = 8;
5418 gameInfo.boardHeight = 8;
5419 gameInfo.holdingsSize = 0;
5420 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
5421 for(i=0; i<BOARD_FILES-2; i++)
5422 initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
5423 initialPosition[EP_STATUS] = EP_NONE;
5424 SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
5425 if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
5426 SetCharTable(pieceNickName, appData.pieceNickNames);
5427 else SetCharTable(pieceNickName, "............");
5430 switch (gameInfo.variant) {
5431 case VariantFischeRandom:
5432 shuffleOpenings = TRUE;
5435 case VariantShatranj:
5436 pieces = ShatranjArray;
5437 nrCastlingRights = 0;
5438 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
5441 pieces = makrukArray;
5442 nrCastlingRights = 0;
5443 startedFromSetupPosition = TRUE;
5444 SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
5446 case VariantTwoKings:
5447 pieces = twoKingsArray;
5449 case VariantCapaRandom:
5450 shuffleOpenings = TRUE;
5451 case VariantCapablanca:
5452 pieces = CapablancaArray;
5453 gameInfo.boardWidth = 10;
5454 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5457 pieces = GothicArray;
5458 gameInfo.boardWidth = 10;
5459 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5462 SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
5463 gameInfo.holdingsSize = 7;
5466 pieces = JanusArray;
5467 gameInfo.boardWidth = 10;
5468 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
5469 nrCastlingRights = 6;
5470 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5471 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5472 initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
5473 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5474 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5475 initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
5478 pieces = FalconArray;
5479 gameInfo.boardWidth = 10;
5480 SetCharTable(pieceToChar, "PNBRQ.............FKpnbrq.............fk");
5482 case VariantXiangqi:
5483 pieces = XiangqiArray;
5484 gameInfo.boardWidth = 9;
5485 gameInfo.boardHeight = 10;
5486 nrCastlingRights = 0;
5487 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
5490 pieces = ShogiArray;
5491 gameInfo.boardWidth = 9;
5492 gameInfo.boardHeight = 9;
5493 gameInfo.holdingsSize = 7;
5494 nrCastlingRights = 0;
5495 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
5497 case VariantCourier:
5498 pieces = CourierArray;
5499 gameInfo.boardWidth = 12;
5500 nrCastlingRights = 0;
5501 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
5503 case VariantKnightmate:
5504 pieces = KnightmateArray;
5505 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
5507 case VariantSpartan:
5508 pieces = SpartanArray;
5509 SetCharTable(pieceToChar, "PNBRQ................K......lwg.....c...h..k");
5512 pieces = fairyArray;
5513 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
5516 pieces = GreatArray;
5517 gameInfo.boardWidth = 10;
5518 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
5519 gameInfo.holdingsSize = 8;
5523 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
5524 gameInfo.holdingsSize = 8;
5525 startedFromSetupPosition = TRUE;
5527 case VariantCrazyhouse:
5528 case VariantBughouse:
5530 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
5531 gameInfo.holdingsSize = 5;
5533 case VariantWildCastle:
5535 /* !!?shuffle with kings guaranteed to be on d or e file */
5536 shuffleOpenings = 1;
5538 case VariantNoCastle:
5540 nrCastlingRights = 0;
5541 /* !!?unconstrained back-rank shuffle */
5542 shuffleOpenings = 1;
5547 if(appData.NrFiles >= 0) {
5548 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
5549 gameInfo.boardWidth = appData.NrFiles;
5551 if(appData.NrRanks >= 0) {
5552 gameInfo.boardHeight = appData.NrRanks;
5554 if(appData.holdingsSize >= 0) {
5555 i = appData.holdingsSize;
5556 if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
5557 gameInfo.holdingsSize = i;
5559 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
5560 if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
5561 DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
5563 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
5564 if(pawnRow < 1) pawnRow = 1;
5565 if(gameInfo.variant == VariantMakruk) pawnRow = 2;
5567 /* User pieceToChar list overrules defaults */
5568 if(appData.pieceToCharTable != NULL)
5569 SetCharTable(pieceToChar, appData.pieceToCharTable);
5571 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
5573 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
5574 s = (ChessSquare) 0; /* account holding counts in guard band */
5575 for( i=0; i<BOARD_HEIGHT; i++ )
5576 initialPosition[i][j] = s;
5578 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
5579 initialPosition[0][j] = pieces[0][j-gameInfo.holdingsWidth];
5580 initialPosition[pawnRow][j] = WhitePawn;
5581 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
5582 if(gameInfo.variant == VariantXiangqi) {
5584 initialPosition[pawnRow][j] =
5585 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
5586 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
5587 initialPosition[2][j] = WhiteCannon;
5588 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
5592 initialPosition[BOARD_HEIGHT-1][j] = pieces[1][j-gameInfo.holdingsWidth];
5594 if( (gameInfo.variant == VariantShogi) && !overrule ) {
5597 initialPosition[1][j] = WhiteBishop;
5598 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
5600 initialPosition[1][j] = WhiteRook;
5601 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
5604 if( nrCastlingRights == -1) {
5605 /* [HGM] Build normal castling rights (must be done after board sizing!) */
5606 /* This sets default castling rights from none to normal corners */
5607 /* Variants with other castling rights must set them themselves above */
5608 nrCastlingRights = 6;
5610 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5611 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5612 initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
5613 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5614 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5615 initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
5618 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
5619 if(gameInfo.variant == VariantGreat) { // promotion commoners
5620 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
5621 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
5622 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
5623 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
5625 if( gameInfo.variant == VariantSChess ) {
5626 initialPosition[1][0] = BlackMarshall;
5627 initialPosition[2][0] = BlackAngel;
5628 initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
5629 initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
5630 initialPosition[1][1] = initialPosition[2][1] =
5631 initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
5633 if (appData.debugMode) {
5634 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
5636 if(shuffleOpenings) {
5637 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
5638 startedFromSetupPosition = TRUE;
5640 if(startedFromPositionFile) {
5641 /* [HGM] loadPos: use PositionFile for every new game */
5642 CopyBoard(initialPosition, filePosition);
5643 for(i=0; i<nrCastlingRights; i++)
5644 initialRights[i] = filePosition[CASTLING][i];
5645 startedFromSetupPosition = TRUE;
5648 CopyBoard(boards[0], initialPosition);
5650 if(oldx != gameInfo.boardWidth ||
5651 oldy != gameInfo.boardHeight ||
5652 oldv != gameInfo.variant ||
5653 oldh != gameInfo.holdingsWidth
5655 InitDrawingSizes(-2 ,0);
5657 oldv = gameInfo.variant;
5659 DrawPosition(TRUE, boards[currentMove]);
5663 SendBoard(cps, moveNum)
5664 ChessProgramState *cps;
5667 char message[MSG_SIZ];
5669 if (cps->useSetboard) {
5670 char* fen = PositionToFEN(moveNum, cps->fenOverride);
5671 snprintf(message, MSG_SIZ,"setboard %s\n", fen);
5672 SendToProgram(message, cps);
5678 /* Kludge to set black to move, avoiding the troublesome and now
5679 * deprecated "black" command.
5681 if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
5682 SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn ? "a2a3\n" : "black\n", cps);
5684 SendToProgram("edit\n", cps);
5685 SendToProgram("#\n", cps);
5686 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
5687 bp = &boards[moveNum][i][BOARD_LEFT];
5688 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
5689 if ((int) *bp < (int) BlackPawn) {
5690 snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp),
5692 if(message[0] == '+' || message[0] == '~') {
5693 snprintf(message, MSG_SIZ,"%c%c%c+\n",
5694 PieceToChar((ChessSquare)(DEMOTED *bp)),
5697 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
5698 message[1] = BOARD_RGHT - 1 - j + '1';
5699 message[2] = BOARD_HEIGHT - 1 - i + 'a';
5701 SendToProgram(message, cps);
5706 SendToProgram("c\n", cps);
5707 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
5708 bp = &boards[moveNum][i][BOARD_LEFT];
5709 for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) {
5710 if (((int) *bp != (int) EmptySquare)
5711 && ((int) *bp >= (int) BlackPawn)) {
5712 snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
5714 if(message[0] == '+' || message[0] == '~') {
5715 snprintf(message, MSG_SIZ,"%c%c%c+\n",
5716 PieceToChar((ChessSquare)(DEMOTED *bp)),
5719 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
5720 message[1] = BOARD_RGHT - 1 - j + '1';
5721 message[2] = BOARD_HEIGHT - 1 - i + 'a';
5723 SendToProgram(message, cps);
5728 SendToProgram(".\n", cps);
5730 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
5734 DefaultPromoChoice(int white)
5737 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
5738 result = WhiteFerz; // no choice
5739 else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
5740 result= WhiteKing; // in Suicide Q is the last thing we want
5741 else if(gameInfo.variant == VariantSpartan)
5742 result = white ? WhiteQueen : WhiteAngel;
5743 else result = WhiteQueen;
5744 if(!white) result = WHITE_TO_BLACK result;
5748 static int autoQueen; // [HGM] oneclick
5751 HasPromotionChoice(int fromX, int fromY, int toX, int toY, char *promoChoice)
5753 /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
5754 /* [HGM] add Shogi promotions */
5755 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
5760 if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
5761 if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
5763 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
5764 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
5767 piece = boards[currentMove][fromY][fromX];
5768 if(gameInfo.variant == VariantShogi) {
5769 promotionZoneSize = BOARD_HEIGHT/3;
5770 highestPromotingPiece = (int)WhiteFerz;
5771 } else if(gameInfo.variant == VariantMakruk) {
5772 promotionZoneSize = 3;
5775 // Treat Lance as Pawn when it is not representing Amazon
5776 if(gameInfo.variant != VariantSuper) {
5777 if(piece == WhiteLance) piece = WhitePawn; else
5778 if(piece == BlackLance) piece = BlackPawn;
5781 // next weed out all moves that do not touch the promotion zone at all
5782 if((int)piece >= BlackPawn) {
5783 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
5785 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
5787 if( toY < BOARD_HEIGHT - promotionZoneSize &&
5788 fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
5791 if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
5793 // weed out mandatory Shogi promotions
5794 if(gameInfo.variant == VariantShogi) {
5795 if(piece >= BlackPawn) {
5796 if(toY == 0 && piece == BlackPawn ||
5797 toY == 0 && piece == BlackQueen ||
5798 toY <= 1 && piece == BlackKnight) {
5803 if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
5804 toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
5805 toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
5812 // weed out obviously illegal Pawn moves
5813 if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
5814 if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
5815 if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
5816 if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
5817 if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
5818 // note we are not allowed to test for valid (non-)capture, due to premove
5821 // we either have a choice what to promote to, or (in Shogi) whether to promote
5822 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk) {
5823 *promoChoice = PieceToChar(BlackFerz); // no choice
5826 // no sense asking what we must promote to if it is going to explode...
5827 if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
5828 *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
5831 // give caller the default choice even if we will not make it
5832 *promoChoice = ToLower(PieceToChar(defaultPromoChoice));
5833 if(gameInfo.variant == VariantShogi) *promoChoice = '+';
5834 if(appData.sweepSelect && gameInfo.variant != VariantGreat
5835 && gameInfo.variant != VariantShogi
5836 && gameInfo.variant != VariantSuper) return FALSE;
5837 if(autoQueen) return FALSE; // predetermined
5839 // suppress promotion popup on illegal moves that are not premoves
5840 premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
5841 gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
5842 if(appData.testLegality && !premove) {
5843 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
5844 fromY, fromX, toY, toX, gameInfo.variant == VariantShogi ? '+' : NULLCHAR);
5845 if(moveType != WhitePromotion && moveType != BlackPromotion)
5853 InPalace(row, column)
5855 { /* [HGM] for Xiangqi */
5856 if( (row < 3 || row > BOARD_HEIGHT-4) &&
5857 column < (BOARD_WIDTH + 4)/2 &&
5858 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
5863 PieceForSquare (x, y)
5867 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
5870 return boards[currentMove][y][x];
5874 OKToStartUserMove(x, y)
5877 ChessSquare from_piece;
5880 if (matchMode) return FALSE;
5881 if (gameMode == EditPosition) return TRUE;
5883 if (x >= 0 && y >= 0)
5884 from_piece = boards[currentMove][y][x];
5886 from_piece = EmptySquare;
5888 if (from_piece == EmptySquare) return FALSE;
5890 white_piece = (int)from_piece >= (int)WhitePawn &&
5891 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
5894 case PlayFromGameFile:
5896 case TwoMachinesPlay:
5904 case MachinePlaysWhite:
5905 case IcsPlayingBlack:
5906 if (appData.zippyPlay) return FALSE;
5908 DisplayMoveError(_("You are playing Black"));
5913 case MachinePlaysBlack:
5914 case IcsPlayingWhite:
5915 if (appData.zippyPlay) return FALSE;
5917 DisplayMoveError(_("You are playing White"));
5923 if (!white_piece && WhiteOnMove(currentMove)) {
5924 DisplayMoveError(_("It is White's turn"));
5927 if (white_piece && !WhiteOnMove(currentMove)) {
5928 DisplayMoveError(_("It is Black's turn"));
5931 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
5932 /* Editing correspondence game history */
5933 /* Could disallow this or prompt for confirmation */
5938 case BeginningOfGame:
5939 if (appData.icsActive) return FALSE;
5940 if (!appData.noChessProgram) {
5942 DisplayMoveError(_("You are playing White"));
5949 if (!white_piece && WhiteOnMove(currentMove)) {
5950 DisplayMoveError(_("It is White's turn"));
5953 if (white_piece && !WhiteOnMove(currentMove)) {
5954 DisplayMoveError(_("It is Black's turn"));
5963 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
5964 && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
5965 && gameMode != AnalyzeFile && gameMode != Training) {
5966 DisplayMoveError(_("Displayed position is not current"));
5973 OnlyMove(int *x, int *y, Boolean captures) {
5974 DisambiguateClosure cl;
5975 if (appData.zippyPlay) return FALSE;
5977 case MachinePlaysBlack:
5978 case IcsPlayingWhite:
5979 case BeginningOfGame:
5980 if(!WhiteOnMove(currentMove)) return FALSE;
5982 case MachinePlaysWhite:
5983 case IcsPlayingBlack:
5984 if(WhiteOnMove(currentMove)) 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) {
6008 if(cl.kind != ImpossibleMove) return FALSE;
6009 cl.pieceIn = EmptySquare;
6014 cl.promoCharIn = NULLCHAR;
6015 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6016 if( cl.kind == NormalMove ||
6017 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6018 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6019 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6024 autoQueen = TRUE; // act as if autoQueen on when we click to-square
6030 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
6031 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
6032 int lastLoadGameUseList = FALSE;
6033 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
6034 ChessMove lastLoadGameStart = EndOfFile;
6037 UserMoveEvent(fromX, fromY, toX, toY, promoChar)
6038 int fromX, fromY, toX, toY;
6042 ChessSquare pdown, pup;
6044 /* Check if the user is playing in turn. This is complicated because we
6045 let the user "pick up" a piece before it is his turn. So the piece he
6046 tried to pick up may have been captured by the time he puts it down!
6047 Therefore we use the color the user is supposed to be playing in this
6048 test, not the color of the piece that is currently on the starting
6049 square---except in EditGame mode, where the user is playing both
6050 sides; fortunately there the capture race can't happen. (It can
6051 now happen in IcsExamining mode, but that's just too bad. The user
6052 will get a somewhat confusing message in that case.)
6056 case PlayFromGameFile:
6058 case TwoMachinesPlay:
6062 /* We switched into a game mode where moves are not accepted,
6063 perhaps while the mouse button was down. */
6066 case MachinePlaysWhite:
6067 /* User is moving for Black */
6068 if (WhiteOnMove(currentMove)) {
6069 DisplayMoveError(_("It is White's turn"));
6074 case MachinePlaysBlack:
6075 /* User is moving for White */
6076 if (!WhiteOnMove(currentMove)) {
6077 DisplayMoveError(_("It is Black's turn"));
6084 case BeginningOfGame:
6087 if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
6088 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
6089 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
6090 /* User is moving for Black */
6091 if (WhiteOnMove(currentMove)) {
6092 DisplayMoveError(_("It is White's turn"));
6096 /* User is moving for White */
6097 if (!WhiteOnMove(currentMove)) {
6098 DisplayMoveError(_("It is Black's turn"));
6104 case IcsPlayingBlack:
6105 /* User is moving for Black */
6106 if (WhiteOnMove(currentMove)) {
6107 if (!appData.premove) {
6108 DisplayMoveError(_("It is White's turn"));
6109 } else if (toX >= 0 && toY >= 0) {
6112 premoveFromX = fromX;
6113 premoveFromY = fromY;
6114 premovePromoChar = promoChar;
6116 if (appData.debugMode)
6117 fprintf(debugFP, "Got premove: fromX %d,"
6118 "fromY %d, toX %d, toY %d\n",
6119 fromX, fromY, toX, toY);
6125 case IcsPlayingWhite:
6126 /* User is moving for White */
6127 if (!WhiteOnMove(currentMove)) {
6128 if (!appData.premove) {
6129 DisplayMoveError(_("It is Black's turn"));
6130 } else if (toX >= 0 && toY >= 0) {
6133 premoveFromX = fromX;
6134 premoveFromY = fromY;
6135 premovePromoChar = promoChar;
6137 if (appData.debugMode)
6138 fprintf(debugFP, "Got premove: fromX %d,"
6139 "fromY %d, toX %d, toY %d\n",
6140 fromX, fromY, toX, toY);
6150 /* EditPosition, empty square, or different color piece;
6151 click-click move is possible */
6152 if (toX == -2 || toY == -2) {
6153 boards[0][fromY][fromX] = EmptySquare;
6154 DrawPosition(FALSE, boards[currentMove]);
6156 } else if (toX >= 0 && toY >= 0) {
6157 boards[0][toY][toX] = boards[0][fromY][fromX];
6158 if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
6159 if(boards[0][fromY][0] != EmptySquare) {
6160 if(boards[0][fromY][1]) boards[0][fromY][1]--;
6161 if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
6164 if(fromX == BOARD_RGHT+1) {
6165 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
6166 if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
6167 if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
6170 boards[0][fromY][fromX] = EmptySquare;
6171 DrawPosition(FALSE, boards[currentMove]);
6177 if(toX < 0 || toY < 0) return;
6178 pdown = boards[currentMove][fromY][fromX];
6179 pup = boards[currentMove][toY][toX];
6181 /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
6182 if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
6183 if( pup != EmptySquare ) return;
6184 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
6185 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
6186 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
6187 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
6188 if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
6189 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
6190 while(PieceToChar(fromX) == '.' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
6194 /* [HGM] always test for legality, to get promotion info */
6195 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6196 fromY, fromX, toY, toX, promoChar);
6197 /* [HGM] but possibly ignore an IllegalMove result */
6198 if (appData.testLegality) {
6199 if (moveType == IllegalMove || moveType == ImpossibleMove) {
6200 DisplayMoveError(_("Illegal move"));
6205 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
6208 /* Common tail of UserMoveEvent and DropMenuEvent */
6210 FinishMove(moveType, fromX, fromY, toX, toY, promoChar)
6212 int fromX, fromY, toX, toY;
6213 /*char*/int promoChar;
6217 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) && promoChar != NULLCHAR) {
6218 // [HGM] superchess: suppress promotions to non-available piece
6219 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
6220 if(WhiteOnMove(currentMove)) {
6221 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
6223 if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
6227 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
6228 move type in caller when we know the move is a legal promotion */
6229 if(moveType == NormalMove && promoChar)
6230 moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
6232 /* [HGM] <popupFix> The following if has been moved here from
6233 UserMoveEvent(). Because it seemed to belong here (why not allow
6234 piece drops in training games?), and because it can only be
6235 performed after it is known to what we promote. */
6236 if (gameMode == Training) {
6237 /* compare the move played on the board to the next move in the
6238 * game. If they match, display the move and the opponent's response.
6239 * If they don't match, display an error message.
6243 CopyBoard(testBoard, boards[currentMove]);
6244 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
6246 if (CompareBoards(testBoard, boards[currentMove+1])) {
6247 ForwardInner(currentMove+1);
6249 /* Autoplay the opponent's response.
6250 * if appData.animate was TRUE when Training mode was entered,
6251 * the response will be animated.
6253 saveAnimate = appData.animate;
6254 appData.animate = animateTraining;
6255 ForwardInner(currentMove+1);
6256 appData.animate = saveAnimate;
6258 /* check for the end of the game */
6259 if (currentMove >= forwardMostMove) {
6260 gameMode = PlayFromGameFile;
6262 SetTrainingModeOff();
6263 DisplayInformation(_("End of game"));
6266 DisplayError(_("Incorrect move"), 0);
6271 /* Ok, now we know that the move is good, so we can kill
6272 the previous line in Analysis Mode */
6273 if ((gameMode == AnalyzeMode || gameMode == EditGame)
6274 && currentMove < forwardMostMove) {
6275 if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
6276 else forwardMostMove = currentMove;
6279 /* If we need the chess program but it's dead, restart it */
6280 ResurrectChessProgram();
6282 /* A user move restarts a paused game*/
6286 thinkOutput[0] = NULLCHAR;
6288 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
6290 if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
6291 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6295 if (gameMode == BeginningOfGame) {
6296 if (appData.noChessProgram) {
6297 gameMode = EditGame;
6301 gameMode = MachinePlaysBlack;
6304 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
6306 if (first.sendName) {
6307 snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
6308 SendToProgram(buf, &first);
6315 /* Relay move to ICS or chess engine */
6316 if (appData.icsActive) {
6317 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
6318 gameMode == IcsExamining) {
6319 if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
6320 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
6322 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6324 // also send plain move, in case ICS does not understand atomic claims
6325 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6329 if (first.sendTime && (gameMode == BeginningOfGame ||
6330 gameMode == MachinePlaysWhite ||
6331 gameMode == MachinePlaysBlack)) {
6332 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
6334 if (gameMode != EditGame && gameMode != PlayFromGameFile) {
6335 // [HGM] book: if program might be playing, let it use book
6336 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
6337 first.maybeThinking = TRUE;
6338 } else SendMoveToProgram(forwardMostMove-1, &first);
6339 if (currentMove == cmailOldMove + 1) {
6340 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
6344 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6348 if(appData.testLegality)
6349 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
6355 if (WhiteOnMove(currentMove)) {
6356 GameEnds(BlackWins, "Black mates", GE_PLAYER);
6358 GameEnds(WhiteWins, "White mates", GE_PLAYER);
6362 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
6367 case MachinePlaysBlack:
6368 case MachinePlaysWhite:
6369 /* disable certain menu options while machine is thinking */
6370 SetMachineThinkingEnables();
6377 userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
6378 promoDefaultAltered = FALSE; // [HGM] fall back on default choice
6380 if(bookHit) { // [HGM] book: simulate book reply
6381 static char bookMove[MSG_SIZ]; // a bit generous?
6383 programStats.nodes = programStats.depth = programStats.time =
6384 programStats.score = programStats.got_only_move = 0;
6385 sprintf(programStats.movelist, "%s (xbook)", bookHit);
6387 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
6388 strcat(bookMove, bookHit);
6389 HandleMachineMove(bookMove, &first);
6395 Mark(board, flags, kind, rf, ff, rt, ft, closure)
6402 typedef char Markers[BOARD_RANKS][BOARD_FILES];
6403 Markers *m = (Markers *) closure;
6404 if(rf == fromY && ff == fromX)
6405 (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
6406 || kind == WhiteCapturesEnPassant
6407 || kind == BlackCapturesEnPassant);
6408 else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3;
6412 MarkTargetSquares(int clear)
6415 if(!appData.markers || !appData.highlightDragging ||
6416 !appData.testLegality || gameMode == EditPosition) return;
6418 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) marker[y][x] = 0;
6421 GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker);
6422 if(PosFlags(0) & F_MANDATORY_CAPTURE) {
6423 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
6425 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
6428 DrawPosition(TRUE, NULL);
6432 Explode(Board board, int fromX, int fromY, int toX, int toY)
6434 if(gameInfo.variant == VariantAtomic &&
6435 (board[toY][toX] != EmptySquare || // capture?
6436 toX != fromX && (board[fromY][fromX] == WhitePawn || // e.p. ?
6437 board[fromY][fromX] == BlackPawn )
6439 AnimateAtomicCapture(board, fromX, fromY, toX, toY);
6445 ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
6447 int CanPromote(ChessSquare piece, int y)
6449 if(gameMode == EditPosition) return FALSE; // no promotions when editing position
6450 // some variants have fixed promotion piece, no promotion at all, or another selection mechanism
6451 if(gameInfo.variant == VariantShogi || gameInfo.variant == VariantXiangqi ||
6452 gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat ||
6453 gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6454 gameInfo.variant == VariantMakruk) return FALSE;
6455 return (piece == BlackPawn && y == 1 ||
6456 piece == WhitePawn && y == BOARD_HEIGHT-2 ||
6457 piece == BlackLance && y == 1 ||
6458 piece == WhiteLance && y == BOARD_HEIGHT-2 );
6461 void LeftClick(ClickType clickType, int xPix, int yPix)
6464 Boolean saveAnimate;
6465 static int second = 0, promotionChoice = 0, clearFlag = 0;
6466 char promoChoice = NULLCHAR;
6469 if(appData.seekGraph && appData.icsActive && loggedOn &&
6470 (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
6471 SeekGraphClick(clickType, xPix, yPix, 0);
6475 if (clickType == Press) ErrorPopDown();
6476 MarkTargetSquares(1);
6478 x = EventToSquare(xPix, BOARD_WIDTH);
6479 y = EventToSquare(yPix, BOARD_HEIGHT);
6480 if (!flipView && y >= 0) {
6481 y = BOARD_HEIGHT - 1 - y;
6483 if (flipView && x >= 0) {
6484 x = BOARD_WIDTH - 1 - x;
6487 if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
6488 defaultPromoChoice = promoSweep;
6489 promoSweep = EmptySquare; // terminate sweep
6490 promoDefaultAltered = TRUE;
6491 if(!selectFlag) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
6494 if(promotionChoice) { // we are waiting for a click to indicate promotion piece
6495 if(clickType == Release) return; // ignore upclick of click-click destination
6496 promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
6497 if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
6498 if(gameInfo.holdingsWidth &&
6499 (WhiteOnMove(currentMove)
6500 ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y > 0
6501 : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT-1) ) {
6502 // click in right holdings, for determining promotion piece
6503 ChessSquare p = boards[currentMove][y][x];
6504 if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
6505 if(p != EmptySquare) {
6506 FinishMove(NormalMove, fromX, fromY, toX, toY, ToLower(PieceToChar(p)));
6511 DrawPosition(FALSE, boards[currentMove]);
6515 /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
6516 if(clickType == Press
6517 && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
6518 || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
6519 || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
6522 if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered)
6523 fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
6525 if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
6526 int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
6527 gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
6528 defaultPromoChoice = DefaultPromoChoice(side);
6531 autoQueen = appData.alwaysPromoteToQueen;
6535 gatingPiece = EmptySquare;
6536 if (clickType != Press) {
6537 if(dragging) { // [HGM] from-square must have been reset due to game end since last press
6538 DragPieceEnd(xPix, yPix); dragging = 0;
6539 DrawPosition(FALSE, NULL);
6543 fromX = x; fromY = y;
6544 if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
6545 // even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
6546 appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
6548 if (OKToStartUserMove(fromX, fromY)) {
6550 MarkTargetSquares(0);
6551 DragPieceBegin(xPix, yPix); dragging = 1;
6552 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
6553 promoSweep = defaultPromoChoice;
6554 selectFlag = 0; lastX = xPix; lastY = yPix;
6555 Sweep(0); // Pawn that is going to promote: preview promotion piece
6556 DisplayMessage("", _("Pull pawn backwards to under-promote"));
6558 if (appData.highlightDragging) {
6559 SetHighlights(fromX, fromY, -1, -1);
6561 } else fromX = fromY = -1;
6567 if (clickType == Press && gameMode != EditPosition) {
6572 // ignore off-board to clicks
6573 if(y < 0 || x < 0) return;
6575 /* Check if clicking again on the same color piece */
6576 fromP = boards[currentMove][fromY][fromX];
6577 toP = boards[currentMove][y][x];
6578 frc = gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom || gameInfo.variant == VariantSChess;
6579 if ((WhitePawn <= fromP && fromP <= WhiteKing &&
6580 WhitePawn <= toP && toP <= WhiteKing &&
6581 !(fromP == WhiteKing && toP == WhiteRook && frc) &&
6582 !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
6583 (BlackPawn <= fromP && fromP <= BlackKing &&
6584 BlackPawn <= toP && toP <= BlackKing &&
6585 !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
6586 !(fromP == BlackKing && toP == BlackRook && frc))) {
6587 /* Clicked again on same color piece -- changed his mind */
6588 second = (x == fromX && y == fromY);
6589 promoDefaultAltered = FALSE;
6590 if(!second || appData.oneClick && !OnlyMove(&x, &y, TRUE)) {
6591 if (appData.highlightDragging) {
6592 SetHighlights(x, y, -1, -1);
6596 if (OKToStartUserMove(x, y)) {
6597 if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
6598 (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
6599 y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
6600 gatingPiece = boards[currentMove][fromY][fromX];
6601 else gatingPiece = EmptySquare;
6603 fromY = y; dragging = 1;
6604 MarkTargetSquares(0);
6605 DragPieceBegin(xPix, yPix);
6606 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
6607 promoSweep = defaultPromoChoice;
6608 selectFlag = 0; lastX = xPix; lastY = yPix;
6609 Sweep(0); // Pawn that is going to promote: preview promotion piece
6613 if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
6616 // ignore clicks on holdings
6617 if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
6620 if (clickType == Release && x == fromX && y == fromY) {
6621 DragPieceEnd(xPix, yPix); dragging = 0;
6623 // a deferred attempt to click-click move an empty square on top of a piece
6624 boards[currentMove][y][x] = EmptySquare;
6626 DrawPosition(FALSE, boards[currentMove]);
6627 fromX = fromY = -1; clearFlag = 0;
6630 if (appData.animateDragging) {
6631 /* Undo animation damage if any */
6632 DrawPosition(FALSE, NULL);
6635 /* Second up/down in same square; just abort move */
6638 gatingPiece = EmptySquare;
6641 ClearPremoveHighlights();
6643 /* First upclick in same square; start click-click mode */
6644 SetHighlights(x, y, -1, -1);
6651 /* we now have a different from- and (possibly off-board) to-square */
6652 /* Completed move */
6655 saveAnimate = appData.animate;
6656 if (clickType == Press) {
6657 if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
6658 // must be Edit Position mode with empty-square selected
6659 fromX = x; fromY = y; DragPieceBegin(xPix, yPix); dragging = 1; // consider this a new attempt to drag
6660 if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
6663 /* Finish clickclick move */
6664 if (appData.animate || appData.highlightLastMove) {
6665 SetHighlights(fromX, fromY, toX, toY);
6670 /* Finish drag move */
6671 if (appData.highlightLastMove) {
6672 SetHighlights(fromX, fromY, toX, toY);
6676 DragPieceEnd(xPix, yPix); dragging = 0;
6677 /* Don't animate move and drag both */
6678 appData.animate = FALSE;
6681 // moves into holding are invalid for now (except in EditPosition, adapting to-square)
6682 if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
6683 ChessSquare piece = boards[currentMove][fromY][fromX];
6684 if(gameMode == EditPosition && piece != EmptySquare &&
6685 fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
6688 if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
6689 n = PieceToNumber(piece - (int)BlackPawn);
6690 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
6691 boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
6692 boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
6694 if(x == BOARD_RGHT+1 && piece < BlackPawn) {
6695 n = PieceToNumber(piece);
6696 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
6697 boards[currentMove][n][BOARD_WIDTH-1] = piece;
6698 boards[currentMove][n][BOARD_WIDTH-2]++;
6700 boards[currentMove][fromY][fromX] = EmptySquare;
6704 DrawPosition(TRUE, boards[currentMove]);
6708 // off-board moves should not be highlighted
6709 if(x < 0 || y < 0) ClearHighlights();
6711 if(gatingPiece != EmptySquare) promoChoice = ToLower(PieceToChar(gatingPiece));
6713 if (HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice)) {
6714 SetHighlights(fromX, fromY, toX, toY);
6715 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
6716 // [HGM] super: promotion to captured piece selected from holdings
6717 ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
6718 promotionChoice = TRUE;
6719 // kludge follows to temporarily execute move on display, without promoting yet
6720 boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
6721 boards[currentMove][toY][toX] = p;
6722 DrawPosition(FALSE, boards[currentMove]);
6723 boards[currentMove][fromY][fromX] = p; // take back, but display stays
6724 boards[currentMove][toY][toX] = q;
6725 DisplayMessage("Click in holdings to choose piece", "");
6730 int oldMove = currentMove;
6731 UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
6732 if (!appData.highlightLastMove || gotPremove) ClearHighlights();
6733 if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
6734 if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
6735 Explode(boards[currentMove-1], fromX, fromY, toX, toY))
6736 DrawPosition(TRUE, boards[currentMove]);
6739 appData.animate = saveAnimate;
6740 if (appData.animate || appData.animateDragging) {
6741 /* Undo animation damage if needed */
6742 DrawPosition(FALSE, NULL);
6746 int RightClick(ClickType action, int x, int y, int *fromX, int *fromY)
6747 { // front-end-free part taken out of PieceMenuPopup
6748 int whichMenu; int xSqr, ySqr;
6750 if(seekGraphUp) { // [HGM] seekgraph
6751 if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
6752 if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
6756 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
6757 && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
6758 if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
6759 if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
6760 if(action == Press) {
6761 originalFlip = flipView;
6762 flipView = !flipView; // temporarily flip board to see game from partners perspective
6763 DrawPosition(TRUE, partnerBoard);
6764 DisplayMessage(partnerStatus, "");
6766 } else if(action == Release) {
6767 flipView = originalFlip;
6768 DrawPosition(TRUE, boards[currentMove]);
6774 xSqr = EventToSquare(x, BOARD_WIDTH);
6775 ySqr = EventToSquare(y, BOARD_HEIGHT);
6776 if (action == Release) {
6777 if(pieceSweep != EmptySquare) {
6778 EditPositionMenuEvent(pieceSweep, toX, toY);
6779 pieceSweep = EmptySquare;
6780 } else UnLoadPV(); // [HGM] pv
6782 if (action != Press) return -2; // return code to be ignored
6785 if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
\r
6787 if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
\r
6788 if (xSqr < 0 || ySqr < 0) return -1;
6789 if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
6790 pieceSweep = shiftKey ? BlackPawn : WhitePawn; // [HGM] sweep: prepare selecting piece by mouse sweep
6791 toX = xSqr; toY = ySqr; lastX = x, lastY = y;
6792 if(flipView) toX = BOARD_WIDTH - 1 - toX; else toY = BOARD_HEIGHT - 1 - toY;
6796 if(!appData.icsEngineAnalyze) return -1;
6797 case IcsPlayingWhite:
6798 case IcsPlayingBlack:
6799 if(!appData.zippyPlay) goto noZip;
6802 case MachinePlaysWhite:
6803 case MachinePlaysBlack:
6804 case TwoMachinesPlay: // [HGM] pv: use for showing PV
6805 if (!appData.dropMenu) {
6807 return 2; // flag front-end to grab mouse events
6809 if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
6810 gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
6813 if (xSqr < 0 || ySqr < 0) return -1;
6814 if (!appData.dropMenu || appData.testLegality &&
6815 gameInfo.variant != VariantBughouse &&
6816 gameInfo.variant != VariantCrazyhouse) return -1;
6817 whichMenu = 1; // drop menu
6823 if (((*fromX = xSqr) < 0) ||
6824 ((*fromY = ySqr) < 0)) {
6825 *fromX = *fromY = -1;
6829 *fromX = BOARD_WIDTH - 1 - *fromX;
6831 *fromY = BOARD_HEIGHT - 1 - *fromY;
6836 void SendProgramStatsToFrontend( ChessProgramState * cps, ChessProgramStats * cpstats )
6838 // char * hint = lastHint;
6839 FrontEndProgramStats stats;
6841 stats.which = cps == &first ? 0 : 1;
6842 stats.depth = cpstats->depth;
6843 stats.nodes = cpstats->nodes;
6844 stats.score = cpstats->score;
6845 stats.time = cpstats->time;
6846 stats.pv = cpstats->movelist;
6847 stats.hint = lastHint;
6848 stats.an_move_index = 0;
6849 stats.an_move_count = 0;
6851 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
6852 stats.hint = cpstats->move_name;
6853 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
6854 stats.an_move_count = cpstats->nr_moves;
6857 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
6859 SetProgramStats( &stats );
6863 Count(Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
6864 { // count all piece types
6866 *nB = *nW = *wStale = *bStale = *bishopColor = 0;
6867 for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
6868 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
6871 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
6872 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
6873 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
6874 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
6875 p == BlackBishop || p == BlackFerz || p == BlackAlfil )
6876 *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
6881 SufficientDefence(int pCnt[], int side, int nMine, int nHis)
6883 int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
6884 int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
6886 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
6887 if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
6888 if(myPawns == 2 && nMine == 3) // KPP
6889 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
6890 if(myPawns == 1 && nMine == 2) // KP
6891 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
6892 if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
6893 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
6894 if(myPawns) return FALSE;
6895 if(pCnt[WhiteRook+side])
6896 return pCnt[BlackRook-side] ||
6897 pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
6898 pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
6899 pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
6900 if(pCnt[WhiteCannon+side]) {
6901 if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
6902 return majorDefense || pCnt[BlackAlfil-side] >= 2;
6904 if(pCnt[WhiteKnight+side])
6905 return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
6910 MatingPotential(int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
6912 VariantClass v = gameInfo.variant;
6914 if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
6915 if(v == VariantShatranj) return TRUE; // always winnable through baring
6916 if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
6917 if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
6919 if(v == VariantXiangqi) {
6920 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
6922 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
6923 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
6924 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
6925 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
6926 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
6927 if(stale) // we have at least one last-rank P plus perhaps C
6928 return majors // KPKX
6929 || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
6931 return pCnt[WhiteFerz+side] // KCAK
6932 || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
6933 || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
6934 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
6936 } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
6937 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
6939 if(nMine == 1) return FALSE; // bare King
6940 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
6941 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
6942 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
6943 // by now we have King + 1 piece (or multiple Bishops on the same color)
6944 if(pCnt[WhiteKnight+side])
6945 return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
6946 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
6947 || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
6949 return (pCnt[BlackKnight-side]); // KBKN, KFKN
6950 if(pCnt[WhiteAlfil+side])
6951 return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
6952 if(pCnt[WhiteWazir+side])
6953 return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
6960 Adjudicate(ChessProgramState *cps)
6961 { // [HGM] some adjudications useful with buggy engines
6962 // [HGM] adjudicate: made into separate routine, which now can be called after every move
6963 // In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
6964 // Actually ending the game is now based on the additional internal condition canAdjudicate.
6965 // Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
6966 int k, count = 0; static int bare = 1;
6967 ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
6968 Boolean canAdjudicate = !appData.icsActive;
6970 // most tests only when we understand the game, i.e. legality-checking on
6971 if( appData.testLegality )
6972 { /* [HGM] Some more adjudications for obstinate engines */
6973 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+1], i;
6974 static int moveCount = 6;
6976 char *reason = NULL;
6978 /* Count what is on board. */
6979 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
6981 /* Some material-based adjudications that have to be made before stalemate test */
6982 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
6983 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
6984 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
6985 if(canAdjudicate && appData.checkMates) {
6987 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
6988 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
6989 "Xboard adjudication: King destroyed", GE_XBOARD );
6994 /* Bare King in Shatranj (loses) or Losers (wins) */
6995 if( nrW == 1 || nrB == 1) {
6996 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
6997 boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
6998 if(canAdjudicate && appData.checkMates) {
7000 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
7001 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7002 "Xboard adjudication: Bare king", GE_XBOARD );
7006 if( gameInfo.variant == VariantShatranj && --bare < 0)
7008 boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
7009 if(canAdjudicate && appData.checkMates) {
7010 /* but only adjudicate if adjudication enabled */
7012 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7013 GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
7014 "Xboard adjudication: Bare king", GE_XBOARD );
7021 // don't wait for engine to announce game end if we can judge ourselves
7022 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
7024 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
7025 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
7026 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
7027 if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
7030 reason = "Xboard adjudication: 3rd check";
7031 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
7041 reason = "Xboard adjudication: Stalemate";
7042 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
7043 boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
7044 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
7045 boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
7046 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
7047 boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
7048 ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
7049 EP_CHECKMATE : EP_WINS);
7050 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi)
7051 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
7055 reason = "Xboard adjudication: Checkmate";
7056 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
7060 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
7062 result = GameIsDrawn; break;
7064 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
7066 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
7070 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
7072 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7073 GameEnds( result, reason, GE_XBOARD );
7077 /* Next absolutely insufficient mating material. */
7078 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
7079 !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
7080 { /* includes KBK, KNK, KK of KBKB with like Bishops */
7082 /* always flag draws, for judging claims */
7083 boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
7085 if(canAdjudicate && appData.materialDraws) {
7086 /* but only adjudicate them if adjudication enabled */
7087 if(engineOpponent) {
7088 SendToProgram("force\n", engineOpponent); // suppress reply
7089 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
7091 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
7096 /* Then some trivial draws (only adjudicate, cannot be claimed) */
7097 if(gameInfo.variant == VariantXiangqi ?
7098 SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
7100 ( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
7101 || nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
7102 || nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
7103 || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
7105 if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
7106 { /* if the first 3 moves do not show a tactical win, declare draw */
7107 if(engineOpponent) {
7108 SendToProgram("force\n", engineOpponent); // suppress reply
7109 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7111 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
7114 } else moveCount = 6;
7116 if (appData.debugMode) { int i;
7117 fprintf(debugFP, "repeat test fmm=%d bmm=%d ep=%d, reps=%d\n",
7118 forwardMostMove, backwardMostMove, boards[backwardMostMove][EP_STATUS],
7119 appData.drawRepeats);
7120 for( i=forwardMostMove; i>=backwardMostMove; i-- )
7121 fprintf(debugFP, "%d ep=%d\n", i, (signed char)boards[i][EP_STATUS]);
7125 // Repetition draws and 50-move rule can be applied independently of legality testing
7127 /* Check for rep-draws */
7129 for(k = forwardMostMove-2;
7130 k>=backwardMostMove && k>=forwardMostMove-100 &&
7131 (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
7132 (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE;
7135 if(CompareBoards(boards[k], boards[forwardMostMove])) {
7136 /* compare castling rights */
7137 if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
7138 (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
7139 rights++; /* King lost rights, while rook still had them */
7140 if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
7141 if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
7142 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
7143 rights++; /* but at least one rook lost them */
7145 if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
7146 (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
7148 if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
7149 if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
7150 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
7153 if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
7154 && appData.drawRepeats > 1) {
7155 /* adjudicate after user-specified nr of repeats */
7156 int result = GameIsDrawn;
7157 char *details = "XBoard adjudication: repetition draw";
7158 if(gameInfo.variant == VariantXiangqi && appData.testLegality) {
7159 // [HGM] xiangqi: check for forbidden perpetuals
7160 int m, ourPerpetual = 1, hisPerpetual = 1;
7161 for(m=forwardMostMove; m>k; m-=2) {
7162 if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
7163 ourPerpetual = 0; // the current mover did not always check
7164 if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
7165 hisPerpetual = 0; // the opponent did not always check
7167 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
7168 ourPerpetual, hisPerpetual);
7169 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
7170 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7171 details = "Xboard adjudication: perpetual checking";
7173 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
7174 break; // (or we would have caught him before). Abort repetition-checking loop.
7176 // Now check for perpetual chases
7177 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
7178 hisPerpetual = PerpetualChase(k, forwardMostMove);
7179 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
7180 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
7181 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7182 details = "Xboard adjudication: perpetual chasing";
7184 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
7185 break; // Abort repetition-checking loop.
7187 // if neither of us is checking or chasing all the time, or both are, it is draw
7189 if(engineOpponent) {
7190 SendToProgram("force\n", engineOpponent); // suppress reply
7191 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7193 GameEnds( result, details, GE_XBOARD );
7196 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
7197 boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
7201 /* Now we test for 50-move draws. Determine ply count */
7202 count = forwardMostMove;
7203 /* look for last irreversble move */
7204 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
7206 /* if we hit starting position, add initial plies */
7207 if( count == backwardMostMove )
7208 count -= initialRulePlies;
7209 count = forwardMostMove - count;
7210 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
7211 // adjust reversible move counter for checks in Xiangqi
7212 int i = forwardMostMove - count, inCheck = 0, lastCheck;
7213 if(i < backwardMostMove) i = backwardMostMove;
7214 while(i <= forwardMostMove) {
7215 lastCheck = inCheck; // check evasion does not count
7216 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
7217 if(inCheck || lastCheck) count--; // check does not count
7222 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
7223 /* this is used to judge if draw claims are legal */
7224 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
7225 if(engineOpponent) {
7226 SendToProgram("force\n", engineOpponent); // suppress reply
7227 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7229 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
7233 /* if draw offer is pending, treat it as a draw claim
7234 * when draw condition present, to allow engines a way to
7235 * claim draws before making their move to avoid a race
7236 * condition occurring after their move
7238 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
7240 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
7241 p = "Draw claim: 50-move rule";
7242 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
7243 p = "Draw claim: 3-fold repetition";
7244 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
7245 p = "Draw claim: insufficient mating material";
7246 if( p != NULL && canAdjudicate) {
7247 if(engineOpponent) {
7248 SendToProgram("force\n", engineOpponent); // suppress reply
7249 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7251 GameEnds( GameIsDrawn, p, GE_XBOARD );
7256 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
7257 if(engineOpponent) {
7258 SendToProgram("force\n", engineOpponent); // suppress reply
7259 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7261 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
7267 char *SendMoveToBookUser(int moveNr, ChessProgramState *cps, int initial)
7268 { // [HGM] book: this routine intercepts moves to simulate book replies
7269 char *bookHit = NULL;
7271 //first determine if the incoming move brings opponent into his book
7272 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
7273 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
7274 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
7275 if(bookHit != NULL && !cps->bookSuspend) {
7276 // make sure opponent is not going to reply after receiving move to book position
7277 SendToProgram("force\n", cps);
7278 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
7280 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
7281 // now arrange restart after book miss
7283 // after a book hit we never send 'go', and the code after the call to this routine
7284 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
7286 snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), bookHit); // force book move into program supposed to play it
7287 SendToProgram(buf, cps);
7288 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
7289 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
7290 SendToProgram("go\n", cps);
7291 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
7292 } else { // 'go' might be sent based on 'firstMove' after this routine returns
7293 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
7294 SendToProgram("go\n", cps);
7295 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
7297 return bookHit; // notify caller of hit, so it can take action to send move to opponent
7301 ChessProgramState *savedState;
7302 void DeferredBookMove(void)
7304 if(savedState->lastPing != savedState->lastPong)
7305 ScheduleDelayedEvent(DeferredBookMove, 10);
7307 HandleMachineMove(savedMessage, savedState);
7311 HandleMachineMove(message, cps)
7313 ChessProgramState *cps;
7315 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
7316 char realname[MSG_SIZ];
7317 int fromX, fromY, toX, toY;
7326 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
7328 * Kludge to ignore BEL characters
7330 while (*message == '\007') message++;
7333 * [HGM] engine debug message: ignore lines starting with '#' character
7335 if(cps->debug && *message == '#') return;
7338 * Look for book output
7340 if (cps == &first && bookRequested) {
7341 if (message[0] == '\t' || message[0] == ' ') {
7342 /* Part of the book output is here; append it */
7343 strcat(bookOutput, message);
7344 strcat(bookOutput, " \n");
7346 } else if (bookOutput[0] != NULLCHAR) {
7347 /* All of book output has arrived; display it */
7348 char *p = bookOutput;
7349 while (*p != NULLCHAR) {
7350 if (*p == '\t') *p = ' ';
7353 DisplayInformation(bookOutput);
7354 bookRequested = FALSE;
7355 /* Fall through to parse the current output */
7360 * Look for machine move.
7362 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
7363 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
7365 /* This method is only useful on engines that support ping */
7366 if (cps->lastPing != cps->lastPong) {
7367 if (gameMode == BeginningOfGame) {
7368 /* Extra move from before last new; ignore */
7369 if (appData.debugMode) {
7370 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7373 if (appData.debugMode) {
7374 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7375 cps->which, gameMode);
7378 SendToProgram("undo\n", cps);
7384 case BeginningOfGame:
7385 /* Extra move from before last reset; ignore */
7386 if (appData.debugMode) {
7387 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
7394 /* Extra move after we tried to stop. The mode test is
7395 not a reliable way of detecting this problem, but it's
7396 the best we can do on engines that don't support ping.
7398 if (appData.debugMode) {
7399 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
7400 cps->which, gameMode);
7402 SendToProgram("undo\n", cps);
7405 case MachinePlaysWhite:
7406 case IcsPlayingWhite:
7407 machineWhite = TRUE;
7410 case MachinePlaysBlack:
7411 case IcsPlayingBlack:
7412 machineWhite = FALSE;
7415 case TwoMachinesPlay:
7416 machineWhite = (cps->twoMachinesColor[0] == 'w');
7419 if (WhiteOnMove(forwardMostMove) != machineWhite) {
7420 if (appData.debugMode) {
7422 "Ignoring move out of turn by %s, gameMode %d"
7423 ", forwardMost %d\n",
7424 cps->which, gameMode, forwardMostMove);
7429 if (appData.debugMode) { int f = forwardMostMove;
7430 fprintf(debugFP, "machine move %d, castling = %d %d %d %d %d %d\n", f,
7431 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
7432 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
7434 if(cps->alphaRank) AlphaRank(machineMove, 4);
7435 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
7436 &fromX, &fromY, &toX, &toY, &promoChar)) {
7437 /* Machine move could not be parsed; ignore it. */
7438 snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
7439 machineMove, _(cps->which));
7440 DisplayError(buf1, 0);
7441 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
7442 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType);
7443 if (gameMode == TwoMachinesPlay) {
7444 GameEnds(machineWhite ? BlackWins : WhiteWins,
7450 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
7451 /* So we have to redo legality test with true e.p. status here, */
7452 /* to make sure an illegal e.p. capture does not slip through, */
7453 /* to cause a forfeit on a justified illegal-move complaint */
7454 /* of the opponent. */
7455 if( gameMode==TwoMachinesPlay && appData.testLegality ) {
7457 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
7458 fromY, fromX, toY, toX, promoChar);
7459 if (appData.debugMode) {
7461 for(i=0; i< nrCastlingRights; i++) fprintf(debugFP, "(%d,%d) ",
7462 boards[forwardMostMove][CASTLING][i], castlingRank[i]);
7463 fprintf(debugFP, "castling rights\n");
7465 if(moveType == IllegalMove) {
7466 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
7467 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
7468 GameEnds(machineWhite ? BlackWins : WhiteWins,
7471 } else if(gameInfo.variant != VariantFischeRandom && gameInfo.variant != VariantCapaRandom)
7472 /* [HGM] Kludge to handle engines that send FRC-style castling
7473 when they shouldn't (like TSCP-Gothic) */
7475 case WhiteASideCastleFR:
7476 case BlackASideCastleFR:
7478 currentMoveString[2]++;
7480 case WhiteHSideCastleFR:
7481 case BlackHSideCastleFR:
7483 currentMoveString[2]--;
7485 default: ; // nothing to do, but suppresses warning of pedantic compilers
7488 hintRequested = FALSE;
7489 lastHint[0] = NULLCHAR;
7490 bookRequested = FALSE;
7491 /* Program may be pondering now */
7492 cps->maybeThinking = TRUE;
7493 if (cps->sendTime == 2) cps->sendTime = 1;
7494 if (cps->offeredDraw) cps->offeredDraw--;
7496 /* [AS] Save move info*/
7497 pvInfoList[ forwardMostMove ].score = programStats.score;
7498 pvInfoList[ forwardMostMove ].depth = programStats.depth;
7499 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
7501 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
7503 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
7504 if( gameMode == TwoMachinesPlay && adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
7507 while( count < adjudicateLossPlies ) {
7508 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
7511 score = -score; /* Flip score for winning side */
7514 if( score > adjudicateLossThreshold ) {
7521 if( count >= adjudicateLossPlies ) {
7522 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7524 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7525 "Xboard adjudication",
7532 if(Adjudicate(cps)) {
7533 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7534 return; // [HGM] adjudicate: for all automatic game ends
7538 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
7540 if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
7541 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
7543 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7545 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7547 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
7548 char buf[3*MSG_SIZ];
7550 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
7551 programStats.score / 100.,
7553 programStats.time / 100.,
7554 (unsigned int)programStats.nodes,
7555 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
7556 programStats.movelist);
7558 if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.nodes, programStats.nodes);
7563 /* [AS] Clear stats for next move */
7564 ClearProgramStats();
7565 thinkOutput[0] = NULLCHAR;
7566 hiddenThinkOutputState = 0;
7569 if (gameMode == TwoMachinesPlay) {
7570 /* [HGM] relaying draw offers moved to after reception of move */
7571 /* and interpreting offer as claim if it brings draw condition */
7572 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
7573 SendToProgram("draw\n", cps->other);
7575 if (cps->other->sendTime) {
7576 SendTimeRemaining(cps->other,
7577 cps->other->twoMachinesColor[0] == 'w');
7579 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
7580 if (firstMove && !bookHit) {
7582 if (cps->other->useColors) {
7583 SendToProgram(cps->other->twoMachinesColor, cps->other);
7585 SendToProgram("go\n", cps->other);
7587 cps->other->maybeThinking = TRUE;
7590 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7592 if (!pausing && appData.ringBellAfterMoves) {
7597 * Reenable menu items that were disabled while
7598 * machine was thinking
7600 if (gameMode != TwoMachinesPlay)
7601 SetUserThinkingEnables();
7603 // [HGM] book: after book hit opponent has received move and is now in force mode
7604 // force the book reply into it, and then fake that it outputted this move by jumping
7605 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
7607 static char bookMove[MSG_SIZ]; // a bit generous?
7609 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
7610 strcat(bookMove, bookHit);
7613 programStats.nodes = programStats.depth = programStats.time =
7614 programStats.score = programStats.got_only_move = 0;
7615 sprintf(programStats.movelist, "%s (xbook)", bookHit);
7617 if(cps->lastPing != cps->lastPong) {
7618 savedMessage = message; // args for deferred call
7620 ScheduleDelayedEvent(DeferredBookMove, 10);
7629 /* Set special modes for chess engines. Later something general
7630 * could be added here; for now there is just one kludge feature,
7631 * needed because Crafty 15.10 and earlier don't ignore SIGINT
7632 * when "xboard" is given as an interactive command.
7634 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
7635 cps->useSigint = FALSE;
7636 cps->useSigterm = FALSE;
7638 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
7639 ParseFeatures(message+8, cps);
7640 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
7643 if (!appData.testLegality && !strncmp(message, "setup ", 6)) { // [HGM] allow first engine to define opening position
7644 int dummy, s=6; char buf[MSG_SIZ];
7645 if(appData.icsActive || forwardMostMove != 0 || cps != &first || startedFromSetupPosition) return;
7646 if(sscanf(message, "setup (%s", buf) == 1) s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTable(pieceToChar, buf);
7647 ParseFEN(boards[0], &dummy, message+s);
7648 DrawPosition(TRUE, boards[0]);
7649 startedFromSetupPosition = TRUE;
7652 /* [HGM] Allow engine to set up a position. Don't ask me why one would
7653 * want this, I was asked to put it in, and obliged.
7655 if (!strncmp(message, "setboard ", 9)) {
7656 Board initial_position;
7658 GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
7660 if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9)) {
7661 DisplayError(_("Bad FEN received from engine"), 0);
7665 CopyBoard(boards[0], initial_position);
7666 initialRulePlies = FENrulePlies;
7667 if(blackPlaysFirst) gameMode = MachinePlaysWhite;
7668 else gameMode = MachinePlaysBlack;
7669 DrawPosition(FALSE, boards[currentMove]);
7675 * Look for communication commands
7677 if (!strncmp(message, "telluser ", 9)) {
7678 if(message[9] == '\\' && message[10] == '\\')
7679 EscapeExpand(message+9, message+11); // [HGM] esc: allow escape sequences in popup box
7680 DisplayNote(message + 9);
7683 if (!strncmp(message, "tellusererror ", 14)) {
7685 if(message[14] == '\\' && message[15] == '\\')
7686 EscapeExpand(message+14, message+16); // [HGM] esc: allow escape sequences in popup box
7687 DisplayError(message + 14, 0);
7690 if (!strncmp(message, "tellopponent ", 13)) {
7691 if (appData.icsActive) {
7693 snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
7697 DisplayNote(message + 13);
7701 if (!strncmp(message, "tellothers ", 11)) {
7702 if (appData.icsActive) {
7704 snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
7710 if (!strncmp(message, "tellall ", 8)) {
7711 if (appData.icsActive) {
7713 snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
7717 DisplayNote(message + 8);
7721 if (strncmp(message, "warning", 7) == 0) {
7722 /* Undocumented feature, use tellusererror in new code */
7723 DisplayError(message, 0);
7726 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
7727 safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
7728 strcat(realname, " query");
7729 AskQuestion(realname, buf2, buf1, cps->pr);
7732 /* Commands from the engine directly to ICS. We don't allow these to be
7733 * sent until we are logged on. Crafty kibitzes have been known to
7734 * interfere with the login process.
7737 if (!strncmp(message, "tellics ", 8)) {
7738 SendToICS(message + 8);
7742 if (!strncmp(message, "tellicsnoalias ", 15)) {
7743 SendToICS(ics_prefix);
7744 SendToICS(message + 15);
7748 /* The following are for backward compatibility only */
7749 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
7750 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
7751 SendToICS(ics_prefix);
7757 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
7761 * If the move is illegal, cancel it and redraw the board.
7762 * Also deal with other error cases. Matching is rather loose
7763 * here to accommodate engines written before the spec.
7765 if (strncmp(message + 1, "llegal move", 11) == 0 ||
7766 strncmp(message, "Error", 5) == 0) {
7767 if (StrStr(message, "name") ||
7768 StrStr(message, "rating") || StrStr(message, "?") ||
7769 StrStr(message, "result") || StrStr(message, "board") ||
7770 StrStr(message, "bk") || StrStr(message, "computer") ||
7771 StrStr(message, "variant") || StrStr(message, "hint") ||
7772 StrStr(message, "random") || StrStr(message, "depth") ||
7773 StrStr(message, "accepted")) {
7776 if (StrStr(message, "protover")) {
7777 /* Program is responding to input, so it's apparently done
7778 initializing, and this error message indicates it is
7779 protocol version 1. So we don't need to wait any longer
7780 for it to initialize and send feature commands. */
7781 FeatureDone(cps, 1);
7782 cps->protocolVersion = 1;
7785 cps->maybeThinking = FALSE;
7787 if (StrStr(message, "draw")) {
7788 /* Program doesn't have "draw" command */
7789 cps->sendDrawOffers = 0;
7792 if (cps->sendTime != 1 &&
7793 (StrStr(message, "time") || StrStr(message, "otim"))) {
7794 /* Program apparently doesn't have "time" or "otim" command */
7798 if (StrStr(message, "analyze")) {
7799 cps->analysisSupport = FALSE;
7800 cps->analyzing = FALSE;
7802 snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
7803 DisplayError(buf2, 0);
7806 if (StrStr(message, "(no matching move)st")) {
7807 /* Special kludge for GNU Chess 4 only */
7808 cps->stKludge = TRUE;
7809 SendTimeControl(cps, movesPerSession, timeControl,
7810 timeIncrement, appData.searchDepth,
7814 if (StrStr(message, "(no matching move)sd")) {
7815 /* Special kludge for GNU Chess 4 only */
7816 cps->sdKludge = TRUE;
7817 SendTimeControl(cps, movesPerSession, timeControl,
7818 timeIncrement, appData.searchDepth,
7822 if (!StrStr(message, "llegal")) {
7825 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
7826 gameMode == IcsIdle) return;
7827 if (forwardMostMove <= backwardMostMove) return;
7828 if (pausing) PauseEvent();
7829 if(appData.forceIllegal) {
7830 // [HGM] illegal: machine refused move; force position after move into it
7831 SendToProgram("force\n", cps);
7832 if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
7833 // we have a real problem now, as SendBoard will use the a2a3 kludge
7834 // when black is to move, while there might be nothing on a2 or black
7835 // might already have the move. So send the board as if white has the move.
7836 // But first we must change the stm of the engine, as it refused the last move
7837 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
7838 if(WhiteOnMove(forwardMostMove)) {
7839 SendToProgram("a7a6\n", cps); // for the engine black still had the move
7840 SendBoard(cps, forwardMostMove); // kludgeless board
7842 SendToProgram("a2a3\n", cps); // for the engine white still had the move
7843 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
7844 SendBoard(cps, forwardMostMove+1); // kludgeless board
7846 } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
7847 if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
7848 gameMode == TwoMachinesPlay)
7849 SendToProgram("go\n", cps);
7852 if (gameMode == PlayFromGameFile) {
7853 /* Stop reading this game file */
7854 gameMode = EditGame;
7857 /* [HGM] illegal-move claim should forfeit game when Xboard */
7858 /* only passes fully legal moves */
7859 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
7860 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
7861 "False illegal-move claim", GE_XBOARD );
7862 return; // do not take back move we tested as valid
7864 currentMove = forwardMostMove-1;
7865 DisplayMove(currentMove-1); /* before DisplayMoveError */
7866 SwitchClocks(forwardMostMove-1); // [HGM] race
7867 DisplayBothClocks();
7868 snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
7869 parseList[currentMove], _(cps->which));
7870 DisplayMoveError(buf1);
7871 DrawPosition(FALSE, boards[currentMove]);
7874 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
7875 /* Program has a broken "time" command that
7876 outputs a string not ending in newline.
7882 * If chess program startup fails, exit with an error message.
7883 * Attempts to recover here are futile.
7885 if ((StrStr(message, "unknown host") != NULL)
7886 || (StrStr(message, "No remote directory") != NULL)
7887 || (StrStr(message, "not found") != NULL)
7888 || (StrStr(message, "No such file") != NULL)
7889 || (StrStr(message, "can't alloc") != NULL)
7890 || (StrStr(message, "Permission denied") != NULL)) {
7892 cps->maybeThinking = FALSE;
7893 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
7894 _(cps->which), cps->program, cps->host, message);
7895 RemoveInputSource(cps->isr);
7896 DisplayFatalError(buf1, 0, 1);
7901 * Look for hint output
7903 if (sscanf(message, "Hint: %s", buf1) == 1) {
7904 if (cps == &first && hintRequested) {
7905 hintRequested = FALSE;
7906 if (ParseOneMove(buf1, forwardMostMove, &moveType,
7907 &fromX, &fromY, &toX, &toY, &promoChar)) {
7908 (void) CoordsToAlgebraic(boards[forwardMostMove],
7909 PosFlags(forwardMostMove),
7910 fromY, fromX, toY, toX, promoChar, buf1);
7911 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
7912 DisplayInformation(buf2);
7914 /* Hint move could not be parsed!? */
7915 snprintf(buf2, sizeof(buf2),
7916 _("Illegal hint move \"%s\"\nfrom %s chess program"),
7917 buf1, _(cps->which));
7918 DisplayError(buf2, 0);
7921 safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
7927 * Ignore other messages if game is not in progress
7929 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
7930 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
7933 * look for win, lose, draw, or draw offer
7935 if (strncmp(message, "1-0", 3) == 0) {
7936 char *p, *q, *r = "";
7937 p = strchr(message, '{');
7945 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
7947 } else if (strncmp(message, "0-1", 3) == 0) {
7948 char *p, *q, *r = "";
7949 p = strchr(message, '{');
7957 /* Kludge for Arasan 4.1 bug */
7958 if (strcmp(r, "Black resigns") == 0) {
7959 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
7962 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
7964 } else if (strncmp(message, "1/2", 3) == 0) {
7965 char *p, *q, *r = "";
7966 p = strchr(message, '{');
7975 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
7978 } else if (strncmp(message, "White resign", 12) == 0) {
7979 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
7981 } else if (strncmp(message, "Black resign", 12) == 0) {
7982 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
7984 } else if (strncmp(message, "White matches", 13) == 0 ||
7985 strncmp(message, "Black matches", 13) == 0 ) {
7986 /* [HGM] ignore GNUShogi noises */
7988 } else if (strncmp(message, "White", 5) == 0 &&
7989 message[5] != '(' &&
7990 StrStr(message, "Black") == NULL) {
7991 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
7993 } else if (strncmp(message, "Black", 5) == 0 &&
7994 message[5] != '(') {
7995 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
7997 } else if (strcmp(message, "resign") == 0 ||
7998 strcmp(message, "computer resigns") == 0) {
8000 case MachinePlaysBlack:
8001 case IcsPlayingBlack:
8002 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
8004 case MachinePlaysWhite:
8005 case IcsPlayingWhite:
8006 GameEnds(BlackWins, "White resigns", GE_ENGINE);
8008 case TwoMachinesPlay:
8009 if (cps->twoMachinesColor[0] == 'w')
8010 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8012 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8019 } else if (strncmp(message, "opponent mates", 14) == 0) {
8021 case MachinePlaysBlack:
8022 case IcsPlayingBlack:
8023 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8025 case MachinePlaysWhite:
8026 case IcsPlayingWhite:
8027 GameEnds(BlackWins, "Black mates", GE_ENGINE);
8029 case TwoMachinesPlay:
8030 if (cps->twoMachinesColor[0] == 'w')
8031 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8033 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8040 } else if (strncmp(message, "computer mates", 14) == 0) {
8042 case MachinePlaysBlack:
8043 case IcsPlayingBlack:
8044 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
8046 case MachinePlaysWhite:
8047 case IcsPlayingWhite:
8048 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8050 case TwoMachinesPlay:
8051 if (cps->twoMachinesColor[0] == 'w')
8052 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8054 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8061 } else if (strncmp(message, "checkmate", 9) == 0) {
8062 if (WhiteOnMove(forwardMostMove)) {
8063 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8065 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8068 } else if (strstr(message, "Draw") != NULL ||
8069 strstr(message, "game is a draw") != NULL) {
8070 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
8072 } else if (strstr(message, "offer") != NULL &&
8073 strstr(message, "draw") != NULL) {
8075 if (appData.zippyPlay && first.initDone) {
8076 /* Relay offer to ICS */
8077 SendToICS(ics_prefix);
8078 SendToICS("draw\n");
8081 cps->offeredDraw = 2; /* valid until this engine moves twice */
8082 if (gameMode == TwoMachinesPlay) {
8083 if (cps->other->offeredDraw) {
8084 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8085 /* [HGM] in two-machine mode we delay relaying draw offer */
8086 /* until after we also have move, to see if it is really claim */
8088 } else if (gameMode == MachinePlaysWhite ||
8089 gameMode == MachinePlaysBlack) {
8090 if (userOfferedDraw) {
8091 DisplayInformation(_("Machine accepts your draw offer"));
8092 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8094 DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
8101 * Look for thinking output
8103 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
8104 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
8106 int plylev, mvleft, mvtot, curscore, time;
8107 char mvname[MOVE_LEN];
8111 int prefixHint = FALSE;
8112 mvname[0] = NULLCHAR;
8115 case MachinePlaysBlack:
8116 case IcsPlayingBlack:
8117 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8119 case MachinePlaysWhite:
8120 case IcsPlayingWhite:
8121 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8126 case IcsObserving: /* [DM] icsEngineAnalyze */
8127 if (!appData.icsEngineAnalyze) ignore = TRUE;
8129 case TwoMachinesPlay:
8130 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
8140 ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
8142 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8143 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
8145 if (plyext != ' ' && plyext != '\t') {
8149 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8150 if( cps->scoreIsAbsolute &&
8151 ( gameMode == MachinePlaysBlack ||
8152 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
8153 gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
8154 (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
8155 !WhiteOnMove(currentMove)
8158 curscore = -curscore;
8162 tempStats.depth = plylev;
8163 tempStats.nodes = nodes;
8164 tempStats.time = time;
8165 tempStats.score = curscore;
8166 tempStats.got_only_move = 0;
8168 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
8171 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
8172 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
8173 if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
8174 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
8175 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
8176 if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
8177 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
8178 blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
8181 /* Buffer overflow protection */
8182 if (buf1[0] != NULLCHAR) {
8183 if (strlen(buf1) >= sizeof(tempStats.movelist)
8184 && appData.debugMode) {
8186 "PV is too long; using the first %u bytes.\n",
8187 (unsigned) sizeof(tempStats.movelist) - 1);
8190 safeStrCpy( tempStats.movelist, buf1, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
8192 sprintf(tempStats.movelist, " no PV\n");
8195 if (tempStats.seen_stat) {
8196 tempStats.ok_to_send = 1;
8199 if (strchr(tempStats.movelist, '(') != NULL) {
8200 tempStats.line_is_book = 1;
8201 tempStats.nr_moves = 0;
8202 tempStats.moves_left = 0;
8204 tempStats.line_is_book = 0;
8207 if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
8208 programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
8210 SendProgramStatsToFrontend( cps, &tempStats );
8213 [AS] Protect the thinkOutput buffer from overflow... this
8214 is only useful if buf1 hasn't overflowed first!
8216 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s",
8218 (gameMode == TwoMachinesPlay ?
8219 ToUpper(cps->twoMachinesColor[0]) : ' '),
8220 ((double) curscore) / 100.0,
8221 prefixHint ? lastHint : "",
8222 prefixHint ? " " : "" );
8224 if( buf1[0] != NULLCHAR ) {
8225 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
8227 if( strlen(buf1) > max_len ) {
8228 if( appData.debugMode) {
8229 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
8231 buf1[max_len+1] = '\0';
8234 strcat( thinkOutput, buf1 );
8237 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
8238 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8239 DisplayMove(currentMove - 1);
8243 } else if ((p=StrStr(message, "(only move)")) != NULL) {
8244 /* crafty (9.25+) says "(only move) <move>"
8245 * if there is only 1 legal move
8247 sscanf(p, "(only move) %s", buf1);
8248 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
8249 sprintf(programStats.movelist, "%s (only move)", buf1);
8250 programStats.depth = 1;
8251 programStats.nr_moves = 1;
8252 programStats.moves_left = 1;
8253 programStats.nodes = 1;
8254 programStats.time = 1;
8255 programStats.got_only_move = 1;
8257 /* Not really, but we also use this member to
8258 mean "line isn't going to change" (Crafty
8259 isn't searching, so stats won't change) */
8260 programStats.line_is_book = 1;
8262 SendProgramStatsToFrontend( cps, &programStats );
8264 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8265 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8266 DisplayMove(currentMove - 1);
8269 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
8270 &time, &nodes, &plylev, &mvleft,
8271 &mvtot, mvname) >= 5) {
8272 /* The stat01: line is from Crafty (9.29+) in response
8273 to the "." command */
8274 programStats.seen_stat = 1;
8275 cps->maybeThinking = TRUE;
8277 if (programStats.got_only_move || !appData.periodicUpdates)
8280 programStats.depth = plylev;
8281 programStats.time = time;
8282 programStats.nodes = nodes;
8283 programStats.moves_left = mvleft;
8284 programStats.nr_moves = mvtot;
8285 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
8286 programStats.ok_to_send = 1;
8287 programStats.movelist[0] = '\0';
8289 SendProgramStatsToFrontend( cps, &programStats );
8293 } else if (strncmp(message,"++",2) == 0) {
8294 /* Crafty 9.29+ outputs this */
8295 programStats.got_fail = 2;
8298 } else if (strncmp(message,"--",2) == 0) {
8299 /* Crafty 9.29+ outputs this */
8300 programStats.got_fail = 1;
8303 } else if (thinkOutput[0] != NULLCHAR &&
8304 strncmp(message, " ", 4) == 0) {
8305 unsigned message_len;
8308 while (*p && *p == ' ') p++;
8310 message_len = strlen( p );
8312 /* [AS] Avoid buffer overflow */
8313 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
8314 strcat(thinkOutput, " ");
8315 strcat(thinkOutput, p);
8318 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
8319 strcat(programStats.movelist, " ");
8320 strcat(programStats.movelist, p);
8323 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8324 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8325 DisplayMove(currentMove - 1);
8333 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8334 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
8336 ChessProgramStats cpstats;
8338 if (plyext != ' ' && plyext != '\t') {
8342 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8343 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
8344 curscore = -curscore;
8347 cpstats.depth = plylev;
8348 cpstats.nodes = nodes;
8349 cpstats.time = time;
8350 cpstats.score = curscore;
8351 cpstats.got_only_move = 0;
8352 cpstats.movelist[0] = '\0';
8354 if (buf1[0] != NULLCHAR) {
8355 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
8358 cpstats.ok_to_send = 0;
8359 cpstats.line_is_book = 0;
8360 cpstats.nr_moves = 0;
8361 cpstats.moves_left = 0;
8363 SendProgramStatsToFrontend( cps, &cpstats );
8370 /* Parse a game score from the character string "game", and
8371 record it as the history of the current game. The game
8372 score is NOT assumed to start from the standard position.
8373 The display is not updated in any way.
8376 ParseGameHistory(game)
8380 int fromX, fromY, toX, toY, boardIndex;
8385 if (appData.debugMode)
8386 fprintf(debugFP, "Parsing game history: %s\n", game);
8388 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
8389 gameInfo.site = StrSave(appData.icsHost);
8390 gameInfo.date = PGNDate();
8391 gameInfo.round = StrSave("-");
8393 /* Parse out names of players */
8394 while (*game == ' ') game++;
8396 while (*game != ' ') *p++ = *game++;
8398 gameInfo.white = StrSave(buf);
8399 while (*game == ' ') game++;
8401 while (*game != ' ' && *game != '\n') *p++ = *game++;
8403 gameInfo.black = StrSave(buf);
8406 boardIndex = blackPlaysFirst ? 1 : 0;
8409 yyboardindex = boardIndex;
8410 moveType = (ChessMove) Myylex();
8412 case IllegalMove: /* maybe suicide chess, etc. */
8413 if (appData.debugMode) {
8414 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
8415 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8416 setbuf(debugFP, NULL);
8418 case WhitePromotion:
8419 case BlackPromotion:
8420 case WhiteNonPromotion:
8421 case BlackNonPromotion:
8423 case WhiteCapturesEnPassant:
8424 case BlackCapturesEnPassant:
8425 case WhiteKingSideCastle:
8426 case WhiteQueenSideCastle:
8427 case BlackKingSideCastle:
8428 case BlackQueenSideCastle:
8429 case WhiteKingSideCastleWild:
8430 case WhiteQueenSideCastleWild:
8431 case BlackKingSideCastleWild:
8432 case BlackQueenSideCastleWild:
8434 case WhiteHSideCastleFR:
8435 case WhiteASideCastleFR:
8436 case BlackHSideCastleFR:
8437 case BlackASideCastleFR:
8439 fromX = currentMoveString[0] - AAA;
8440 fromY = currentMoveString[1] - ONE;
8441 toX = currentMoveString[2] - AAA;
8442 toY = currentMoveString[3] - ONE;
8443 promoChar = currentMoveString[4];
8447 fromX = moveType == WhiteDrop ?
8448 (int) CharToPiece(ToUpper(currentMoveString[0])) :
8449 (int) CharToPiece(ToLower(currentMoveString[0]));
8451 toX = currentMoveString[2] - AAA;
8452 toY = currentMoveString[3] - ONE;
8453 promoChar = NULLCHAR;
8457 snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
8458 if (appData.debugMode) {
8459 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
8460 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8461 setbuf(debugFP, NULL);
8463 DisplayError(buf, 0);
8465 case ImpossibleMove:
8467 snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
8468 if (appData.debugMode) {
8469 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
8470 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
8471 setbuf(debugFP, NULL);
8473 DisplayError(buf, 0);
8476 if (boardIndex < backwardMostMove) {
8477 /* Oops, gap. How did that happen? */
8478 DisplayError(_("Gap in move list"), 0);
8481 backwardMostMove = blackPlaysFirst ? 1 : 0;
8482 if (boardIndex > forwardMostMove) {
8483 forwardMostMove = boardIndex;
8487 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
8488 strcat(parseList[boardIndex-1], " ");
8489 strcat(parseList[boardIndex-1], yy_text);
8501 case GameUnfinished:
8502 if (gameMode == IcsExamining) {
8503 if (boardIndex < backwardMostMove) {
8504 /* Oops, gap. How did that happen? */
8507 backwardMostMove = blackPlaysFirst ? 1 : 0;
8510 gameInfo.result = moveType;
8511 p = strchr(yy_text, '{');
8512 if (p == NULL) p = strchr(yy_text, '(');
8515 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
8517 q = strchr(p, *p == '{' ? '}' : ')');
8518 if (q != NULL) *q = NULLCHAR;
8521 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
8522 gameInfo.resultDetails = StrSave(p);
8525 if (boardIndex >= forwardMostMove &&
8526 !(gameMode == IcsObserving && ics_gamenum == -1)) {
8527 backwardMostMove = blackPlaysFirst ? 1 : 0;
8530 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
8531 fromY, fromX, toY, toX, promoChar,
8532 parseList[boardIndex]);
8533 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
8534 /* currentMoveString is set as a side-effect of yylex */
8535 safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
8536 strcat(moveList[boardIndex], "\n");
8538 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
8539 switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
8545 if(gameInfo.variant != VariantShogi)
8546 strcat(parseList[boardIndex - 1], "+");
8550 strcat(parseList[boardIndex - 1], "#");
8557 /* Apply a move to the given board */
8559 ApplyMove(fromX, fromY, toX, toY, promoChar, board)
8560 int fromX, fromY, toX, toY;
8564 ChessSquare captured = board[toY][toX], piece, king; int p, oldEP = EP_NONE, berolina = 0;
8565 int promoRank = gameInfo.variant == VariantMakruk ? 3 : 1;
8567 /* [HGM] compute & store e.p. status and castling rights for new position */
8568 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
8570 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
8571 oldEP = (signed char)board[EP_STATUS];
8572 board[EP_STATUS] = EP_NONE;
8574 if( board[toY][toX] != EmptySquare )
8575 board[EP_STATUS] = EP_CAPTURE;
8577 if (fromY == DROP_RANK) {
8579 piece = board[toY][toX] = (ChessSquare) fromX;
8583 if( board[fromY][fromX] == WhiteLance || board[fromY][fromX] == BlackLance ) {
8584 if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi )
8585 board[EP_STATUS] = EP_PAWN_MOVE; // Lance is Pawn-like in most variants
8587 if( board[fromY][fromX] == WhitePawn ) {
8588 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
8589 board[EP_STATUS] = EP_PAWN_MOVE;
8591 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
8592 gameInfo.variant != VariantBerolina || toX < fromX)
8593 board[EP_STATUS] = toX | berolina;
8594 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
8595 gameInfo.variant != VariantBerolina || toX > fromX)
8596 board[EP_STATUS] = toX;
8599 if( board[fromY][fromX] == BlackPawn ) {
8600 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
8601 board[EP_STATUS] = EP_PAWN_MOVE;
8602 if( toY-fromY== -2) {
8603 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
8604 gameInfo.variant != VariantBerolina || toX < fromX)
8605 board[EP_STATUS] = toX | berolina;
8606 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
8607 gameInfo.variant != VariantBerolina || toX > fromX)
8608 board[EP_STATUS] = toX;
8612 for(i=0; i<nrCastlingRights; i++) {
8613 if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
8614 board[CASTLING][i] == toX && castlingRank[i] == toY
8615 ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
8618 if (fromX == toX && fromY == toY) return;
8620 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
8621 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
8622 if(gameInfo.variant == VariantKnightmate)
8623 king += (int) WhiteUnicorn - (int) WhiteKing;
8625 /* Code added by Tord: */
8626 /* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
8627 if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
8628 board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
8629 board[fromY][fromX] = EmptySquare;
8630 board[toY][toX] = EmptySquare;
8631 if((toX > fromX) != (piece == WhiteRook)) {
8632 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
8634 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
8636 } else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
8637 board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
8638 board[fromY][fromX] = EmptySquare;
8639 board[toY][toX] = EmptySquare;
8640 if((toX > fromX) != (piece == BlackRook)) {
8641 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
8643 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
8645 /* End of code added by Tord */
8647 } else if (board[fromY][fromX] == king
8648 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8649 && toY == fromY && toX > fromX+1) {
8650 board[fromY][fromX] = EmptySquare;
8651 board[toY][toX] = king;
8652 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
8653 board[fromY][BOARD_RGHT-1] = EmptySquare;
8654 } else if (board[fromY][fromX] == king
8655 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8656 && toY == fromY && toX < fromX-1) {
8657 board[fromY][fromX] = EmptySquare;
8658 board[toY][toX] = king;
8659 board[toY][toX+1] = board[fromY][BOARD_LEFT];
8660 board[fromY][BOARD_LEFT] = EmptySquare;
8661 } else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
8662 board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
8663 && toY >= BOARD_HEIGHT-promoRank
8665 /* white pawn promotion */
8666 board[toY][toX] = CharToPiece(ToUpper(promoChar));
8667 if (board[toY][toX] == EmptySquare) {
8668 board[toY][toX] = WhiteQueen;
8670 if(gameInfo.variant==VariantBughouse ||
8671 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
8672 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
8673 board[fromY][fromX] = EmptySquare;
8674 } else if ((fromY == BOARD_HEIGHT-4)
8676 && gameInfo.variant != VariantXiangqi
8677 && gameInfo.variant != VariantBerolina
8678 && (board[fromY][fromX] == WhitePawn)
8679 && (board[toY][toX] == EmptySquare)) {
8680 board[fromY][fromX] = EmptySquare;
8681 board[toY][toX] = WhitePawn;
8682 captured = board[toY - 1][toX];
8683 board[toY - 1][toX] = EmptySquare;
8684 } else if ((fromY == BOARD_HEIGHT-4)
8686 && gameInfo.variant == VariantBerolina
8687 && (board[fromY][fromX] == WhitePawn)
8688 && (board[toY][toX] == EmptySquare)) {
8689 board[fromY][fromX] = EmptySquare;
8690 board[toY][toX] = WhitePawn;
8691 if(oldEP & EP_BEROLIN_A) {
8692 captured = board[fromY][fromX-1];
8693 board[fromY][fromX-1] = EmptySquare;
8694 }else{ captured = board[fromY][fromX+1];
8695 board[fromY][fromX+1] = EmptySquare;
8697 } else if (board[fromY][fromX] == king
8698 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8699 && toY == fromY && toX > fromX+1) {
8700 board[fromY][fromX] = EmptySquare;
8701 board[toY][toX] = king;
8702 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
8703 board[fromY][BOARD_RGHT-1] = EmptySquare;
8704 } else if (board[fromY][fromX] == king
8705 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
8706 && toY == fromY && toX < fromX-1) {
8707 board[fromY][fromX] = EmptySquare;
8708 board[toY][toX] = king;
8709 board[toY][toX+1] = board[fromY][BOARD_LEFT];
8710 board[fromY][BOARD_LEFT] = EmptySquare;
8711 } else if (fromY == 7 && fromX == 3
8712 && board[fromY][fromX] == BlackKing
8713 && toY == 7 && toX == 5) {
8714 board[fromY][fromX] = EmptySquare;
8715 board[toY][toX] = BlackKing;
8716 board[fromY][7] = EmptySquare;
8717 board[toY][4] = BlackRook;
8718 } else if (fromY == 7 && fromX == 3
8719 && board[fromY][fromX] == BlackKing
8720 && toY == 7 && toX == 1) {
8721 board[fromY][fromX] = EmptySquare;
8722 board[toY][toX] = BlackKing;
8723 board[fromY][0] = EmptySquare;
8724 board[toY][2] = BlackRook;
8725 } else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
8726 board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
8729 /* black pawn promotion */
8730 board[toY][toX] = CharToPiece(ToLower(promoChar));
8731 if (board[toY][toX] == EmptySquare) {
8732 board[toY][toX] = BlackQueen;
8734 if(gameInfo.variant==VariantBughouse ||
8735 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
8736 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
8737 board[fromY][fromX] = EmptySquare;
8738 } else if ((fromY == 3)
8740 && gameInfo.variant != VariantXiangqi
8741 && gameInfo.variant != VariantBerolina
8742 && (board[fromY][fromX] == BlackPawn)
8743 && (board[toY][toX] == EmptySquare)) {
8744 board[fromY][fromX] = EmptySquare;
8745 board[toY][toX] = BlackPawn;
8746 captured = board[toY + 1][toX];
8747 board[toY + 1][toX] = EmptySquare;
8748 } else if ((fromY == 3)
8750 && gameInfo.variant == VariantBerolina
8751 && (board[fromY][fromX] == BlackPawn)
8752 && (board[toY][toX] == EmptySquare)) {
8753 board[fromY][fromX] = EmptySquare;
8754 board[toY][toX] = BlackPawn;
8755 if(oldEP & EP_BEROLIN_A) {
8756 captured = board[fromY][fromX-1];
8757 board[fromY][fromX-1] = EmptySquare;
8758 }else{ captured = board[fromY][fromX+1];
8759 board[fromY][fromX+1] = EmptySquare;
8762 board[toY][toX] = board[fromY][fromX];
8763 board[fromY][fromX] = EmptySquare;
8767 if (gameInfo.holdingsWidth != 0) {
8769 /* !!A lot more code needs to be written to support holdings */
8770 /* [HGM] OK, so I have written it. Holdings are stored in the */
8771 /* penultimate board files, so they are automaticlly stored */
8772 /* in the game history. */
8773 if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
8774 && promoChar && piece != WhitePawn && piece != BlackPawn) {
8775 /* Delete from holdings, by decreasing count */
8776 /* and erasing image if necessary */
8777 p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
8778 if(p < (int) BlackPawn) { /* white drop */
8779 p -= (int)WhitePawn;
8780 p = PieceToNumber((ChessSquare)p);
8781 if(p >= gameInfo.holdingsSize) p = 0;
8782 if(--board[p][BOARD_WIDTH-2] <= 0)
8783 board[p][BOARD_WIDTH-1] = EmptySquare;
8784 if((int)board[p][BOARD_WIDTH-2] < 0)
8785 board[p][BOARD_WIDTH-2] = 0;
8786 } else { /* black drop */
8787 p -= (int)BlackPawn;
8788 p = PieceToNumber((ChessSquare)p);
8789 if(p >= gameInfo.holdingsSize) p = 0;
8790 if(--board[BOARD_HEIGHT-1-p][1] <= 0)
8791 board[BOARD_HEIGHT-1-p][0] = EmptySquare;
8792 if((int)board[BOARD_HEIGHT-1-p][1] < 0)
8793 board[BOARD_HEIGHT-1-p][1] = 0;
8796 if (captured != EmptySquare && gameInfo.holdingsSize > 0
8797 && gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess ) {
8798 /* [HGM] holdings: Add to holdings, if holdings exist */
8799 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat) {
8800 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
8801 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
8804 if (p >= (int) BlackPawn) {
8805 p -= (int)BlackPawn;
8806 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
8807 /* in Shogi restore piece to its original first */
8808 captured = (ChessSquare) (DEMOTED captured);
8811 p = PieceToNumber((ChessSquare)p);
8812 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
8813 board[p][BOARD_WIDTH-2]++;
8814 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
8816 p -= (int)WhitePawn;
8817 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
8818 captured = (ChessSquare) (DEMOTED captured);
8821 p = PieceToNumber((ChessSquare)p);
8822 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
8823 board[BOARD_HEIGHT-1-p][1]++;
8824 board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
8827 } else if (gameInfo.variant == VariantAtomic) {
8828 if (captured != EmptySquare) {
8830 for (y = toY-1; y <= toY+1; y++) {
8831 for (x = toX-1; x <= toX+1; x++) {
8832 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
8833 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
8834 board[y][x] = EmptySquare;
8838 board[toY][toX] = EmptySquare;
8841 if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
8842 board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
8844 if(promoChar == '+') {
8845 /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite orinary Pawn promotion) */
8846 board[toY][toX] = (ChessSquare) (PROMOTED piece);
8847 } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
8848 board[toY][toX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
8850 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
8851 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
8852 // [HGM] superchess: take promotion piece out of holdings
8853 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
8854 if((int)piece < (int)BlackPawn) { // determine stm from piece color
8855 if(!--board[k][BOARD_WIDTH-2])
8856 board[k][BOARD_WIDTH-1] = EmptySquare;
8858 if(!--board[BOARD_HEIGHT-1-k][1])
8859 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
8865 /* Updates forwardMostMove */
8867 MakeMove(fromX, fromY, toX, toY, promoChar)
8868 int fromX, fromY, toX, toY;
8871 // forwardMostMove++; // [HGM] bare: moved downstream
8873 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
8874 int timeLeft; static int lastLoadFlag=0; int king, piece;
8875 piece = boards[forwardMostMove][fromY][fromX];
8876 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
8877 if(gameInfo.variant == VariantKnightmate)
8878 king += (int) WhiteUnicorn - (int) WhiteKing;
8879 if(forwardMostMove == 0) {
8881 fprintf(serverMoves, "%s;", second.tidy);
8882 fprintf(serverMoves, "%s;", first.tidy);
8883 if(!blackPlaysFirst)
8884 fprintf(serverMoves, "%s;", second.tidy);
8885 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
8886 lastLoadFlag = loadFlag;
8888 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
8889 // print castling suffix
8890 if( toY == fromY && piece == king ) {
8892 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
8894 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
8897 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
8898 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
8899 boards[forwardMostMove][toY][toX] == EmptySquare
8900 && fromX != toX && fromY != toY)
8901 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
8903 if(promoChar != NULLCHAR)
8904 fprintf(serverMoves, ":%c:%c%c", promoChar, AAA+toX, ONE+toY);
8906 fprintf(serverMoves, "/%d/%d",
8907 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
8908 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
8909 else timeLeft = blackTimeRemaining/1000;
8910 fprintf(serverMoves, "/%d", timeLeft);
8912 fflush(serverMoves);
8915 if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations
8916 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
8920 UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
8921 if (commentList[forwardMostMove+1] != NULL) {
8922 free(commentList[forwardMostMove+1]);
8923 commentList[forwardMostMove+1] = NULL;
8925 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
8926 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
8927 // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
8928 SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
8929 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
8930 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
8931 gameInfo.result = GameUnfinished;
8932 if (gameInfo.resultDetails != NULL) {
8933 free(gameInfo.resultDetails);
8934 gameInfo.resultDetails = NULL;
8936 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
8937 moveList[forwardMostMove - 1]);
8938 (void) CoordsToAlgebraic(boards[forwardMostMove - 1],
8939 PosFlags(forwardMostMove - 1),
8940 fromY, fromX, toY, toX, promoChar,
8941 parseList[forwardMostMove - 1]);
8942 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
8948 if(gameInfo.variant != VariantShogi)
8949 strcat(parseList[forwardMostMove - 1], "+");
8953 strcat(parseList[forwardMostMove - 1], "#");
8956 if (appData.debugMode) {
8957 fprintf(debugFP, "move: %s, parse: %s (%c)\n", moveList[forwardMostMove-1], parseList[forwardMostMove-1], moveList[forwardMostMove-1][4]);
8962 /* Updates currentMove if not pausing */
8964 ShowMove(fromX, fromY, toX, toY)
8966 int instant = (gameMode == PlayFromGameFile) ?
8967 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
8968 if(appData.noGUI) return;
8969 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
8971 if (forwardMostMove == currentMove + 1) {
8972 AnimateMove(boards[forwardMostMove - 1],
8973 fromX, fromY, toX, toY);
8975 if (appData.highlightLastMove) {
8976 SetHighlights(fromX, fromY, toX, toY);
8979 currentMove = forwardMostMove;
8982 if (instant) return;
8984 DisplayMove(currentMove - 1);
8985 DrawPosition(FALSE, boards[currentMove]);
8986 DisplayBothClocks();
8987 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
8990 void SendEgtPath(ChessProgramState *cps)
8991 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
8992 char buf[MSG_SIZ], name[MSG_SIZ], *p;
8994 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
8997 char c, *q = name+1, *r, *s;
8999 name[0] = ','; // extract next format name from feature and copy with prefixed ','
9000 while(*p && *p != ',') *q++ = *p++;
9002 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
9003 strcmp(name, ",nalimov:") == 0 ) {
9004 // take nalimov path from the menu-changeable option first, if it is defined
9005 snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
9006 SendToProgram(buf,cps); // send egtbpath command for nalimov
9008 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
9009 (s = StrStr(appData.egtFormats, name)) != NULL) {
9010 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
9011 s = r = StrStr(s, ":") + 1; // beginning of path info
9012 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
9013 c = *r; *r = 0; // temporarily null-terminate path info
9014 *--q = 0; // strip of trailig ':' from name
9015 snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
9017 SendToProgram(buf,cps); // send egtbpath command for this format
9019 if(*p == ',') p++; // read away comma to position for next format name
9024 InitChessProgram(cps, setup)
9025 ChessProgramState *cps;
9026 int setup; /* [HGM] needed to setup FRC opening position */
9028 char buf[MSG_SIZ], b[MSG_SIZ]; int overruled;
9029 if (appData.noChessProgram) return;
9030 hintRequested = FALSE;
9031 bookRequested = FALSE;
9033 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
9034 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
9035 if(cps->memSize) { /* [HGM] memory */
9036 snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
9037 SendToProgram(buf, cps);
9039 SendEgtPath(cps); /* [HGM] EGT */
9040 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
9041 snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
9042 SendToProgram(buf, cps);
9045 SendToProgram(cps->initString, cps);
9046 if (gameInfo.variant != VariantNormal &&
9047 gameInfo.variant != VariantLoadable
9048 /* [HGM] also send variant if board size non-standard */
9049 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0
9051 char *v = VariantName(gameInfo.variant);
9052 if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) {
9053 /* [HGM] in protocol 1 we have to assume all variants valid */
9054 snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), v, cps->tidy);
9055 DisplayFatalError(buf, 0, 1);
9059 /* [HGM] make prefix for non-standard board size. Awkward testing... */
9060 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9061 if( gameInfo.variant == VariantXiangqi )
9062 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 0;
9063 if( gameInfo.variant == VariantShogi )
9064 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 9 || gameInfo.holdingsSize != 7;
9065 if( gameInfo.variant == VariantBughouse || gameInfo.variant == VariantCrazyhouse )
9066 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 5;
9067 if( gameInfo.variant == VariantCapablanca || gameInfo.variant == VariantCapaRandom ||
9068 gameInfo.variant == VariantGothic || gameInfo.variant == VariantFalcon || gameInfo.variant == VariantJanus )
9069 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9070 if( gameInfo.variant == VariantCourier )
9071 overruled = gameInfo.boardWidth != 12 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9072 if( gameInfo.variant == VariantSuper )
9073 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9074 if( gameInfo.variant == VariantGreat )
9075 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9076 if( gameInfo.variant == VariantSChess )
9077 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 7;
9080 snprintf(b, MSG_SIZ, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
9081 gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
9082 /* [HGM] varsize: try first if this defiant size variant is specifically known */
9083 if(StrStr(cps->variants, b) == NULL) {
9084 // specific sized variant not known, check if general sizing allowed
9085 if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best
9086 if(StrStr(cps->variants, "boardsize") == NULL) {
9087 snprintf(buf, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
9088 gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy);
9089 DisplayFatalError(buf, 0, 1);
9092 /* [HGM] here we really should compare with the maximum supported board size */
9095 } else snprintf(b, MSG_SIZ,"%s", VariantName(gameInfo.variant));
9096 snprintf(buf, MSG_SIZ, "variant %s\n", b);
9097 SendToProgram(buf, cps);
9099 currentlyInitializedVariant = gameInfo.variant;
9101 /* [HGM] send opening position in FRC to first engine */
9103 SendToProgram("force\n", cps);
9105 /* engine is now in force mode! Set flag to wake it up after first move. */
9106 setboardSpoiledMachineBlack = 1;
9110 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
9111 SendToProgram(buf, cps);
9113 cps->maybeThinking = FALSE;
9114 cps->offeredDraw = 0;
9115 if (!appData.icsActive) {
9116 SendTimeControl(cps, movesPerSession, timeControl,
9117 timeIncrement, appData.searchDepth,
9120 if (appData.showThinking
9121 // [HGM] thinking: four options require thinking output to be sent
9122 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
9124 SendToProgram("post\n", cps);
9126 SendToProgram("hard\n", cps);
9127 if (!appData.ponderNextMove) {
9128 /* Warning: "easy" is a toggle in GNU Chess, so don't send
9129 it without being sure what state we are in first. "hard"
9130 is not a toggle, so that one is OK.
9132 SendToProgram("easy\n", cps);
9135 snprintf(buf, MSG_SIZ, "ping %d\n", ++cps->lastPing);
9136 SendToProgram(buf, cps);
9138 cps->initDone = TRUE;
9143 StartChessProgram(cps)
9144 ChessProgramState *cps;
9149 if (appData.noChessProgram) return;
9150 cps->initDone = FALSE;
9152 if (strcmp(cps->host, "localhost") == 0) {
9153 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
9154 } else if (*appData.remoteShell == NULLCHAR) {
9155 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
9157 if (*appData.remoteUser == NULLCHAR) {
9158 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
9161 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
9162 cps->host, appData.remoteUser, cps->program);
9164 err = StartChildProcess(buf, "", &cps->pr);
9168 snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
9169 DisplayFatalError(buf, err, 1);
9175 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
9176 if (cps->protocolVersion > 1) {
9177 snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
9178 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
9179 cps->comboCnt = 0; // and values of combo boxes
9180 SendToProgram(buf, cps);
9182 SendToProgram("xboard\n", cps);
9188 TwoMachinesEventIfReady P((void))
9190 if (first.lastPing != first.lastPong) {
9191 DisplayMessage("", _("Waiting for first chess program"));
9192 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9195 if (second.lastPing != second.lastPong) {
9196 DisplayMessage("", _("Waiting for second chess program"));
9197 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9205 NextMatchGame P((void))
9207 int index; /* [HGM] autoinc: step load index during match */
9209 if (*appData.loadGameFile != NULLCHAR) {
9210 index = appData.loadGameIndex;
9211 if(index < 0) { // [HGM] autoinc
9212 lastIndex = index = (index == -2 && first.twoMachinesColor[0] == 'b') ? lastIndex : lastIndex+1;
9213 if(appData.rewindIndex > 0 && index > appData.rewindIndex) lastIndex = index = 1;
9215 LoadGameFromFile(appData.loadGameFile,
9217 appData.loadGameFile, FALSE);
9218 } else if (*appData.loadPositionFile != NULLCHAR) {
9219 index = appData.loadPositionIndex;
9220 if(index < 0) { // [HGM] autoinc
9221 lastIndex = index = (index == -2 && first.twoMachinesColor[0] == 'b') ? lastIndex : lastIndex+1;
9222 if(appData.rewindIndex > 0 && index > appData.rewindIndex) lastIndex = index = 1;
9224 LoadPositionFromFile(appData.loadPositionFile,
9226 appData.loadPositionFile);
9228 TwoMachinesEventIfReady();
9231 void UserAdjudicationEvent( int result )
9233 ChessMove gameResult = GameIsDrawn;
9236 gameResult = WhiteWins;
9238 else if( result < 0 ) {
9239 gameResult = BlackWins;
9242 if( gameMode == TwoMachinesPlay ) {
9243 GameEnds( gameResult, "User adjudication", GE_XBOARD );
9248 // [HGM] save: calculate checksum of game to make games easily identifiable
9249 int StringCheckSum(char *s)
9252 if(s==NULL) return 0;
9253 while(*s) i = i*259 + *s++;
9260 for(i=backwardMostMove; i<forwardMostMove; i++) {
9261 sum += pvInfoList[i].depth;
9262 sum += StringCheckSum(parseList[i]);
9263 sum += StringCheckSum(commentList[i]);
9266 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
9267 return sum + StringCheckSum(commentList[i]);
9268 } // end of save patch
9271 GameEnds(result, resultDetails, whosays)
9273 char *resultDetails;
9276 GameMode nextGameMode;
9278 char buf[MSG_SIZ], popupRequested = 0;
9280 if(endingGame) return; /* [HGM] crash: forbid recursion */
9282 if(twoBoards) { // [HGM] dual: switch back to one board
9283 twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
9284 DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
9286 if (appData.debugMode) {
9287 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
9288 result, resultDetails ? resultDetails : "(null)", whosays);
9291 fromX = fromY = -1; // [HGM] abort any move the user is entering.
9293 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
9294 /* If we are playing on ICS, the server decides when the
9295 game is over, but the engine can offer to draw, claim
9299 if (appData.zippyPlay && first.initDone) {
9300 if (result == GameIsDrawn) {
9301 /* In case draw still needs to be claimed */
9302 SendToICS(ics_prefix);
9303 SendToICS("draw\n");
9304 } else if (StrCaseStr(resultDetails, "resign")) {
9305 SendToICS(ics_prefix);
9306 SendToICS("resign\n");
9310 endingGame = 0; /* [HGM] crash */
9314 /* If we're loading the game from a file, stop */
9315 if (whosays == GE_FILE) {
9316 (void) StopLoadGameTimer();
9320 /* Cancel draw offers */
9321 first.offeredDraw = second.offeredDraw = 0;
9323 /* If this is an ICS game, only ICS can really say it's done;
9324 if not, anyone can. */
9325 isIcsGame = (gameMode == IcsPlayingWhite ||
9326 gameMode == IcsPlayingBlack ||
9327 gameMode == IcsObserving ||
9328 gameMode == IcsExamining);
9330 if (!isIcsGame || whosays == GE_ICS) {
9331 /* OK -- not an ICS game, or ICS said it was done */
9333 if (!isIcsGame && !appData.noChessProgram)
9334 SetUserThinkingEnables();
9336 /* [HGM] if a machine claims the game end we verify this claim */
9337 if(gameMode == TwoMachinesPlay && appData.testClaims) {
9338 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
9340 ChessMove trueResult = (ChessMove) -1;
9342 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
9343 first.twoMachinesColor[0] :
9344 second.twoMachinesColor[0] ;
9346 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
9347 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
9348 /* [HGM] verify: engine mate claims accepted if they were flagged */
9349 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
9351 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
9352 /* [HGM] verify: engine mate claims accepted if they were flagged */
9353 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
9355 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
9356 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
9359 // now verify win claims, but not in drop games, as we don't understand those yet
9360 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
9361 || gameInfo.variant == VariantGreat) &&
9362 (result == WhiteWins && claimer == 'w' ||
9363 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
9364 if (appData.debugMode) {
9365 fprintf(debugFP, "result=%d sp=%d move=%d\n",
9366 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
9368 if(result != trueResult) {
9369 snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
9370 result = claimer == 'w' ? BlackWins : WhiteWins;
9371 resultDetails = buf;
9374 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
9375 && (forwardMostMove <= backwardMostMove ||
9376 (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
9377 (claimer=='b')==(forwardMostMove&1))
9379 /* [HGM] verify: draws that were not flagged are false claims */
9380 snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
9381 result = claimer == 'w' ? BlackWins : WhiteWins;
9382 resultDetails = buf;
9384 /* (Claiming a loss is accepted no questions asked!) */
9386 /* [HGM] bare: don't allow bare King to win */
9387 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat)
9388 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
9389 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
9390 && result != GameIsDrawn)
9391 { int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
9392 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
9393 int p = (signed char)boards[forwardMostMove][i][j] - color;
9394 if(p >= 0 && p <= (int)WhiteKing) k++;
9396 if (appData.debugMode) {
9397 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
9398 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
9401 result = GameIsDrawn;
9402 snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
9403 resultDetails = buf;
9409 if(serverMoves != NULL && !loadFlag) { char c = '=';
9410 if(result==WhiteWins) c = '+';
9411 if(result==BlackWins) c = '-';
9412 if(resultDetails != NULL)
9413 fprintf(serverMoves, ";%c;%s\n", c, resultDetails);
9415 if (resultDetails != NULL) {
9416 gameInfo.result = result;
9417 gameInfo.resultDetails = StrSave(resultDetails);
9419 /* display last move only if game was not loaded from file */
9420 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
9421 DisplayMove(currentMove - 1);
9423 if (forwardMostMove != 0) {
9424 if (gameMode != PlayFromGameFile && gameMode != EditGame
9425 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
9427 if (*appData.saveGameFile != NULLCHAR) {
9428 SaveGameToFile(appData.saveGameFile, TRUE);
9429 } else if (appData.autoSaveGames) {
9432 if (*appData.savePositionFile != NULLCHAR) {
9433 SavePositionToFile(appData.savePositionFile);
9438 /* Tell program how game ended in case it is learning */
9439 /* [HGM] Moved this to after saving the PGN, just in case */
9440 /* engine died and we got here through time loss. In that */
9441 /* case we will get a fatal error writing the pipe, which */
9442 /* would otherwise lose us the PGN. */
9443 /* [HGM] crash: not needed anymore, but doesn't hurt; */
9444 /* output during GameEnds should never be fatal anymore */
9445 if (gameMode == MachinePlaysWhite ||
9446 gameMode == MachinePlaysBlack ||
9447 gameMode == TwoMachinesPlay ||
9448 gameMode == IcsPlayingWhite ||
9449 gameMode == IcsPlayingBlack ||
9450 gameMode == BeginningOfGame) {
9452 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
9454 if (first.pr != NoProc) {
9455 SendToProgram(buf, &first);
9457 if (second.pr != NoProc &&
9458 gameMode == TwoMachinesPlay) {
9459 SendToProgram(buf, &second);
9464 if (appData.icsActive) {
9465 if (appData.quietPlay &&
9466 (gameMode == IcsPlayingWhite ||
9467 gameMode == IcsPlayingBlack)) {
9468 SendToICS(ics_prefix);
9469 SendToICS("set shout 1\n");
9471 nextGameMode = IcsIdle;
9472 ics_user_moved = FALSE;
9473 /* clean up premove. It's ugly when the game has ended and the
9474 * premove highlights are still on the board.
9478 ClearPremoveHighlights();
9479 DrawPosition(FALSE, boards[currentMove]);
9481 if (whosays == GE_ICS) {
9484 if (gameMode == IcsPlayingWhite)
9486 else if(gameMode == IcsPlayingBlack)
9490 if (gameMode == IcsPlayingBlack)
9492 else if(gameMode == IcsPlayingWhite)
9499 PlayIcsUnfinishedSound();
9502 } else if (gameMode == EditGame ||
9503 gameMode == PlayFromGameFile ||
9504 gameMode == AnalyzeMode ||
9505 gameMode == AnalyzeFile) {
9506 nextGameMode = gameMode;
9508 nextGameMode = EndOfGame;
9513 nextGameMode = gameMode;
9516 if (appData.noChessProgram) {
9517 gameMode = nextGameMode;
9519 endingGame = 0; /* [HGM] crash */
9524 /* Put first chess program into idle state */
9525 if (first.pr != NoProc &&
9526 (gameMode == MachinePlaysWhite ||
9527 gameMode == MachinePlaysBlack ||
9528 gameMode == TwoMachinesPlay ||
9529 gameMode == IcsPlayingWhite ||
9530 gameMode == IcsPlayingBlack ||
9531 gameMode == BeginningOfGame)) {
9532 SendToProgram("force\n", &first);
9533 if (first.usePing) {
9535 snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
9536 SendToProgram(buf, &first);
9539 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
9540 /* Kill off first chess program */
9541 if (first.isr != NULL)
9542 RemoveInputSource(first.isr);
9545 if (first.pr != NoProc) {
9547 DoSleep( appData.delayBeforeQuit );
9548 SendToProgram("quit\n", &first);
9549 DoSleep( appData.delayAfterQuit );
9550 DestroyChildProcess(first.pr, first.useSigterm);
9555 /* Put second chess program into idle state */
9556 if (second.pr != NoProc &&
9557 gameMode == TwoMachinesPlay) {
9558 SendToProgram("force\n", &second);
9559 if (second.usePing) {
9561 snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
9562 SendToProgram(buf, &second);
9565 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
9566 /* Kill off second chess program */
9567 if (second.isr != NULL)
9568 RemoveInputSource(second.isr);
9571 if (second.pr != NoProc) {
9572 DoSleep( appData.delayBeforeQuit );
9573 SendToProgram("quit\n", &second);
9574 DoSleep( appData.delayAfterQuit );
9575 DestroyChildProcess(second.pr, second.useSigterm);
9580 if (matchMode && gameMode == TwoMachinesPlay) {
9583 if (first.twoMachinesColor[0] == 'w') {
9590 if (first.twoMachinesColor[0] == 'b') {
9599 if (matchGame < appData.matchGames) {
9601 if(appData.sameColorGames <= 1) { /* [HGM] alternate: suppress color swap */
9602 tmp = first.twoMachinesColor;
9603 first.twoMachinesColor = second.twoMachinesColor;
9604 second.twoMachinesColor = tmp;
9606 gameMode = nextGameMode;
9608 if(appData.matchPause>10000 || appData.matchPause<10)
9609 appData.matchPause = 10000; /* [HGM] make pause adjustable */
9610 ScheduleDelayedEvent(NextMatchGame, appData.matchPause);
9611 endingGame = 0; /* [HGM] crash */
9614 gameMode = nextGameMode;
9615 snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
9616 first.tidy, second.tidy,
9617 first.matchWins, second.matchWins,
9618 appData.matchGames - (first.matchWins + second.matchWins));
9619 popupRequested++; // [HGM] crash: postpone to after resetting endingGame
9620 if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
9621 first.twoMachinesColor = "black\n";
9622 second.twoMachinesColor = "white\n";
9624 first.twoMachinesColor = "white\n";
9625 second.twoMachinesColor = "black\n";
9629 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
9630 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
9632 gameMode = nextGameMode;
9634 endingGame = 0; /* [HGM] crash */
9635 if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
9636 if(matchMode == TRUE) DisplayFatalError(buf, 0, 0); else {
9637 matchMode = FALSE; appData.matchGames = matchGame = 0;
9643 /* Assumes program was just initialized (initString sent).
9644 Leaves program in force mode. */
9646 FeedMovesToProgram(cps, upto)
9647 ChessProgramState *cps;
9652 if (appData.debugMode)
9653 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
9654 startedFromSetupPosition ? "position and " : "",
9655 backwardMostMove, upto, cps->which);
9656 if(currentlyInitializedVariant != gameInfo.variant) {
9658 // [HGM] variantswitch: make engine aware of new variant
9659 if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL)
9660 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
9661 snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
9662 SendToProgram(buf, cps);
9663 currentlyInitializedVariant = gameInfo.variant;
9665 SendToProgram("force\n", cps);
9666 if (startedFromSetupPosition) {
9667 SendBoard(cps, backwardMostMove);
9668 if (appData.debugMode) {
9669 fprintf(debugFP, "feedMoves\n");
9672 for (i = backwardMostMove; i < upto; i++) {
9673 SendMoveToProgram(i, cps);
9679 ResurrectChessProgram()
9681 /* The chess program may have exited.
9682 If so, restart it and feed it all the moves made so far. */
9684 if (appData.noChessProgram || first.pr != NoProc) return;
9686 StartChessProgram(&first);
9687 InitChessProgram(&first, FALSE);
9688 FeedMovesToProgram(&first, currentMove);
9690 if (!first.sendTime) {
9691 /* can't tell gnuchess what its clock should read,
9692 so we bow to its notion. */
9694 timeRemaining[0][currentMove] = whiteTimeRemaining;
9695 timeRemaining[1][currentMove] = blackTimeRemaining;
9698 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
9699 appData.icsEngineAnalyze) && first.analysisSupport) {
9700 SendToProgram("analyze\n", &first);
9701 first.analyzing = TRUE;
9714 if (appData.debugMode) {
9715 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
9716 redraw, init, gameMode);
9718 CleanupTail(); // [HGM] vari: delete any stored variations
9719 pausing = pauseExamInvalid = FALSE;
9720 startedFromSetupPosition = blackPlaysFirst = FALSE;
9722 whiteFlag = blackFlag = FALSE;
9723 userOfferedDraw = FALSE;
9724 hintRequested = bookRequested = FALSE;
9725 first.maybeThinking = FALSE;
9726 second.maybeThinking = FALSE;
9727 first.bookSuspend = FALSE; // [HGM] book
9728 second.bookSuspend = FALSE;
9729 thinkOutput[0] = NULLCHAR;
9730 lastHint[0] = NULLCHAR;
9731 ClearGameInfo(&gameInfo);
9732 gameInfo.variant = StringToVariant(appData.variant);
9733 ics_user_moved = ics_clock_paused = FALSE;
9734 ics_getting_history = H_FALSE;
9736 white_holding[0] = black_holding[0] = NULLCHAR;
9737 ClearProgramStats();
9738 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
9742 flipView = appData.flipView;
9743 ClearPremoveHighlights();
9745 alarmSounded = FALSE;
9747 GameEnds(EndOfFile, NULL, GE_PLAYER);
9748 if(appData.serverMovesName != NULL) {
9749 /* [HGM] prepare to make moves file for broadcasting */
9750 clock_t t = clock();
9751 if(serverMoves != NULL) fclose(serverMoves);
9752 serverMoves = fopen(appData.serverMovesName, "r");
9753 if(serverMoves != NULL) {
9754 fclose(serverMoves);
9755 /* delay 15 sec before overwriting, so all clients can see end */
9756 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
9758 serverMoves = fopen(appData.serverMovesName, "w");
9762 gameMode = BeginningOfGame;
9764 if(appData.icsActive) gameInfo.variant = VariantNormal;
9765 currentMove = forwardMostMove = backwardMostMove = 0;
9766 InitPosition(redraw);
9767 for (i = 0; i < MAX_MOVES; i++) {
9768 if (commentList[i] != NULL) {
9769 free(commentList[i]);
9770 commentList[i] = NULL;
9774 timeRemaining[0][0] = whiteTimeRemaining;
9775 timeRemaining[1][0] = blackTimeRemaining;
9776 if (first.pr == NULL) {
9777 StartChessProgram(&first);
9780 InitChessProgram(&first, startedFromSetupPosition);
9783 DisplayMessage("", "");
9784 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
9785 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
9792 if (!AutoPlayOneMove())
9794 if (matchMode || appData.timeDelay == 0)
9796 if (appData.timeDelay < 0)
9798 StartLoadGameTimer((long)(1000.0 * appData.timeDelay));
9807 int fromX, fromY, toX, toY;
9809 if (appData.debugMode) {
9810 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
9813 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
9816 if (gameMode == AnalyzeFile && currentMove > backwardMostMove) {
9817 pvInfoList[currentMove].depth = programStats.depth;
9818 pvInfoList[currentMove].score = programStats.score;
9819 pvInfoList[currentMove].time = 0;
9820 if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
9823 if (currentMove >= forwardMostMove) {
9824 if(gameMode == AnalyzeFile) { ExitAnalyzeMode(); SendToProgram("force\n", &first); }
9825 gameMode = EditGame;
9828 /* [AS] Clear current move marker at the end of a game */
9829 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
9834 toX = moveList[currentMove][2] - AAA;
9835 toY = moveList[currentMove][3] - ONE;
9837 if (moveList[currentMove][1] == '@') {
9838 if (appData.highlightLastMove) {
9839 SetHighlights(-1, -1, toX, toY);
9842 fromX = moveList[currentMove][0] - AAA;
9843 fromY = moveList[currentMove][1] - ONE;
9845 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
9847 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
9849 if (appData.highlightLastMove) {
9850 SetHighlights(fromX, fromY, toX, toY);
9853 DisplayMove(currentMove);
9854 SendMoveToProgram(currentMove++, &first);
9855 DisplayBothClocks();
9856 DrawPosition(FALSE, boards[currentMove]);
9857 // [HGM] PV info: always display, routine tests if empty
9858 DisplayComment(currentMove - 1, commentList[currentMove]);
9864 LoadGameOneMove(readAhead)
9865 ChessMove readAhead;
9867 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
9868 char promoChar = NULLCHAR;
9873 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
9874 gameMode != AnalyzeMode && gameMode != Training) {
9879 yyboardindex = forwardMostMove;
9880 if (readAhead != EndOfFile) {
9881 moveType = readAhead;
9883 if (gameFileFP == NULL)
9885 moveType = (ChessMove) Myylex();
9891 if (appData.debugMode)
9892 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
9895 /* append the comment but don't display it */
9896 AppendComment(currentMove, p, FALSE);
9899 case WhiteCapturesEnPassant:
9900 case BlackCapturesEnPassant:
9901 case WhitePromotion:
9902 case BlackPromotion:
9903 case WhiteNonPromotion:
9904 case BlackNonPromotion:
9906 case WhiteKingSideCastle:
9907 case WhiteQueenSideCastle:
9908 case BlackKingSideCastle:
9909 case BlackQueenSideCastle:
9910 case WhiteKingSideCastleWild:
9911 case WhiteQueenSideCastleWild:
9912 case BlackKingSideCastleWild:
9913 case BlackQueenSideCastleWild:
9915 case WhiteHSideCastleFR:
9916 case WhiteASideCastleFR:
9917 case BlackHSideCastleFR:
9918 case BlackASideCastleFR:
9920 if (appData.debugMode)
9921 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
9922 fromX = currentMoveString[0] - AAA;
9923 fromY = currentMoveString[1] - ONE;
9924 toX = currentMoveString[2] - AAA;
9925 toY = currentMoveString[3] - ONE;
9926 promoChar = currentMoveString[4];
9931 if (appData.debugMode)
9932 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
9933 fromX = moveType == WhiteDrop ?
9934 (int) CharToPiece(ToUpper(currentMoveString[0])) :
9935 (int) CharToPiece(ToLower(currentMoveString[0]));
9937 toX = currentMoveString[2] - AAA;
9938 toY = currentMoveString[3] - ONE;
9944 case GameUnfinished:
9945 if (appData.debugMode)
9946 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
9947 p = strchr(yy_text, '{');
9948 if (p == NULL) p = strchr(yy_text, '(');
9951 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
9953 q = strchr(p, *p == '{' ? '}' : ')');
9954 if (q != NULL) *q = NULLCHAR;
9957 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
9958 GameEnds(moveType, p, GE_FILE);
9960 if (cmailMsgLoaded) {
9962 flipView = WhiteOnMove(currentMove);
9963 if (moveType == GameUnfinished) flipView = !flipView;
9964 if (appData.debugMode)
9965 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
9970 if (appData.debugMode)
9971 fprintf(debugFP, "Parser hit end of file\n");
9972 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
9978 if (WhiteOnMove(currentMove)) {
9979 GameEnds(BlackWins, "Black mates", GE_FILE);
9981 GameEnds(WhiteWins, "White mates", GE_FILE);
9985 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
9992 if (lastLoadGameStart == GNUChessGame) {
9993 /* GNUChessGames have numbers, but they aren't move numbers */
9994 if (appData.debugMode)
9995 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
9996 yy_text, (int) moveType);
9997 return LoadGameOneMove(EndOfFile); /* tail recursion */
9999 /* else fall thru */
10004 /* Reached start of next game in file */
10005 if (appData.debugMode)
10006 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
10007 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
10013 if (WhiteOnMove(currentMove)) {
10014 GameEnds(BlackWins, "Black mates", GE_FILE);
10016 GameEnds(WhiteWins, "White mates", GE_FILE);
10020 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
10026 case PositionDiagram: /* should not happen; ignore */
10027 case ElapsedTime: /* ignore */
10028 case NAG: /* ignore */
10029 if (appData.debugMode)
10030 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
10031 yy_text, (int) moveType);
10032 return LoadGameOneMove(EndOfFile); /* tail recursion */
10035 if (appData.testLegality) {
10036 if (appData.debugMode)
10037 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
10038 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
10039 (forwardMostMove / 2) + 1,
10040 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10041 DisplayError(move, 0);
10044 if (appData.debugMode)
10045 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
10046 yy_text, currentMoveString);
10047 fromX = currentMoveString[0] - AAA;
10048 fromY = currentMoveString[1] - ONE;
10049 toX = currentMoveString[2] - AAA;
10050 toY = currentMoveString[3] - ONE;
10051 promoChar = currentMoveString[4];
10055 case AmbiguousMove:
10056 if (appData.debugMode)
10057 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
10058 snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
10059 (forwardMostMove / 2) + 1,
10060 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10061 DisplayError(move, 0);
10066 case ImpossibleMove:
10067 if (appData.debugMode)
10068 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
10069 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
10070 (forwardMostMove / 2) + 1,
10071 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
10072 DisplayError(move, 0);
10078 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
10079 DrawPosition(FALSE, boards[currentMove]);
10080 DisplayBothClocks();
10081 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
10082 DisplayComment(currentMove - 1, commentList[currentMove]);
10084 (void) StopLoadGameTimer();
10086 cmailOldMove = forwardMostMove;
10089 /* currentMoveString is set as a side-effect of yylex */
10091 thinkOutput[0] = NULLCHAR;
10092 MakeMove(fromX, fromY, toX, toY, promoChar);
10093 currentMove = forwardMostMove;
10098 /* Load the nth game from the given file */
10100 LoadGameFromFile(filename, n, title, useList)
10104 /*Boolean*/ int useList;
10109 if (strcmp(filename, "-") == 0) {
10113 f = fopen(filename, "rb");
10115 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10116 DisplayError(buf, errno);
10120 if (fseek(f, 0, 0) == -1) {
10121 /* f is not seekable; probably a pipe */
10124 if (useList && n == 0) {
10125 int error = GameListBuild(f);
10127 DisplayError(_("Cannot build game list"), error);
10128 } else if (!ListEmpty(&gameList) &&
10129 ((ListGame *) gameList.tailPred)->number > 1) {
10130 GameListPopUp(f, title);
10137 return LoadGame(f, n, title, FALSE);
10142 MakeRegisteredMove()
10144 int fromX, fromY, toX, toY;
10146 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
10147 switch (cmailMoveType[lastLoadGameNumber - 1]) {
10150 if (appData.debugMode)
10151 fprintf(debugFP, "Restoring %s for game %d\n",
10152 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
10154 thinkOutput[0] = NULLCHAR;
10155 safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
10156 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
10157 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
10158 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
10159 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
10160 promoChar = cmailMove[lastLoadGameNumber - 1][4];
10161 MakeMove(fromX, fromY, toX, toY, promoChar);
10162 ShowMove(fromX, fromY, toX, toY);
10164 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
10171 if (WhiteOnMove(currentMove)) {
10172 GameEnds(BlackWins, "Black mates", GE_PLAYER);
10174 GameEnds(WhiteWins, "White mates", GE_PLAYER);
10179 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
10186 if (WhiteOnMove(currentMove)) {
10187 GameEnds(BlackWins, "White resigns", GE_PLAYER);
10189 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
10194 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
10205 /* Wrapper around LoadGame for use when a Cmail message is loaded */
10207 CmailLoadGame(f, gameNumber, title, useList)
10215 if (gameNumber > nCmailGames) {
10216 DisplayError(_("No more games in this message"), 0);
10219 if (f == lastLoadGameFP) {
10220 int offset = gameNumber - lastLoadGameNumber;
10222 cmailMsg[0] = NULLCHAR;
10223 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
10224 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
10225 nCmailMovesRegistered--;
10227 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
10228 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
10229 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
10232 if (! RegisterMove()) return FALSE;
10236 retVal = LoadGame(f, gameNumber, title, useList);
10238 /* Make move registered during previous look at this game, if any */
10239 MakeRegisteredMove();
10241 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
10242 commentList[currentMove]
10243 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
10244 DisplayComment(currentMove - 1, commentList[currentMove]);
10250 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
10255 int gameNumber = lastLoadGameNumber + offset;
10256 if (lastLoadGameFP == NULL) {
10257 DisplayError(_("No game has been loaded yet"), 0);
10260 if (gameNumber <= 0) {
10261 DisplayError(_("Can't back up any further"), 0);
10264 if (cmailMsgLoaded) {
10265 return CmailLoadGame(lastLoadGameFP, gameNumber,
10266 lastLoadGameTitle, lastLoadGameUseList);
10268 return LoadGame(lastLoadGameFP, gameNumber,
10269 lastLoadGameTitle, lastLoadGameUseList);
10275 /* Load the nth game from open file f */
10277 LoadGame(f, gameNumber, title, useList)
10285 int gn = gameNumber;
10286 ListGame *lg = NULL;
10287 int numPGNTags = 0;
10289 GameMode oldGameMode;
10290 VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
10292 if (appData.debugMode)
10293 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
10295 if (gameMode == Training )
10296 SetTrainingModeOff();
10298 oldGameMode = gameMode;
10299 if (gameMode != BeginningOfGame) {
10300 Reset(FALSE, TRUE);
10304 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
10305 fclose(lastLoadGameFP);
10309 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
10312 fseek(f, lg->offset, 0);
10313 GameListHighlight(gameNumber);
10317 DisplayError(_("Game number out of range"), 0);
10322 if (fseek(f, 0, 0) == -1) {
10323 if (f == lastLoadGameFP ?
10324 gameNumber == lastLoadGameNumber + 1 :
10328 DisplayError(_("Can't seek on game file"), 0);
10333 lastLoadGameFP = f;
10334 lastLoadGameNumber = gameNumber;
10335 safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
10336 lastLoadGameUseList = useList;
10340 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
10341 snprintf(buf, sizeof(buf), "%s vs. %s", lg->gameInfo.white,
10342 lg->gameInfo.black);
10344 } else if (*title != NULLCHAR) {
10345 if (gameNumber > 1) {
10346 snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
10349 DisplayTitle(title);
10353 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
10354 gameMode = PlayFromGameFile;
10358 currentMove = forwardMostMove = backwardMostMove = 0;
10359 CopyBoard(boards[0], initialPosition);
10363 * Skip the first gn-1 games in the file.
10364 * Also skip over anything that precedes an identifiable
10365 * start of game marker, to avoid being confused by
10366 * garbage at the start of the file. Currently
10367 * recognized start of game markers are the move number "1",
10368 * the pattern "gnuchess .* game", the pattern
10369 * "^[#;%] [^ ]* game file", and a PGN tag block.
10370 * A game that starts with one of the latter two patterns
10371 * will also have a move number 1, possibly
10372 * following a position diagram.
10373 * 5-4-02: Let's try being more lenient and allowing a game to
10374 * start with an unnumbered move. Does that break anything?
10376 cm = lastLoadGameStart = EndOfFile;
10378 yyboardindex = forwardMostMove;
10379 cm = (ChessMove) Myylex();
10382 if (cmailMsgLoaded) {
10383 nCmailGames = CMAIL_MAX_GAMES - gn;
10386 DisplayError(_("Game not found in file"), 0);
10393 lastLoadGameStart = cm;
10396 case MoveNumberOne:
10397 switch (lastLoadGameStart) {
10402 case MoveNumberOne:
10404 gn--; /* count this game */
10405 lastLoadGameStart = cm;
10414 switch (lastLoadGameStart) {
10417 case MoveNumberOne:
10419 gn--; /* count this game */
10420 lastLoadGameStart = cm;
10423 lastLoadGameStart = cm; /* game counted already */
10431 yyboardindex = forwardMostMove;
10432 cm = (ChessMove) Myylex();
10433 } while (cm == PGNTag || cm == Comment);
10440 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
10441 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
10442 != CMAIL_OLD_RESULT) {
10444 cmailResult[ CMAIL_MAX_GAMES
10445 - gn - 1] = CMAIL_OLD_RESULT;
10451 /* Only a NormalMove can be at the start of a game
10452 * without a position diagram. */
10453 if (lastLoadGameStart == EndOfFile ) {
10455 lastLoadGameStart = MoveNumberOne;
10464 if (appData.debugMode)
10465 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
10467 if (cm == XBoardGame) {
10468 /* Skip any header junk before position diagram and/or move 1 */
10470 yyboardindex = forwardMostMove;
10471 cm = (ChessMove) Myylex();
10473 if (cm == EndOfFile ||
10474 cm == GNUChessGame || cm == XBoardGame) {
10475 /* Empty game; pretend end-of-file and handle later */
10480 if (cm == MoveNumberOne || cm == PositionDiagram ||
10481 cm == PGNTag || cm == Comment)
10484 } else if (cm == GNUChessGame) {
10485 if (gameInfo.event != NULL) {
10486 free(gameInfo.event);
10488 gameInfo.event = StrSave(yy_text);
10491 startedFromSetupPosition = FALSE;
10492 while (cm == PGNTag) {
10493 if (appData.debugMode)
10494 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
10495 err = ParsePGNTag(yy_text, &gameInfo);
10496 if (!err) numPGNTags++;
10498 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
10499 if(gameInfo.variant != oldVariant) {
10500 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
10501 ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
10502 InitPosition(TRUE);
10503 oldVariant = gameInfo.variant;
10504 if (appData.debugMode)
10505 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
10509 if (gameInfo.fen != NULL) {
10510 Board initial_position;
10511 startedFromSetupPosition = TRUE;
10512 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
10514 DisplayError(_("Bad FEN position in file"), 0);
10517 CopyBoard(boards[0], initial_position);
10518 if (blackPlaysFirst) {
10519 currentMove = forwardMostMove = backwardMostMove = 1;
10520 CopyBoard(boards[1], initial_position);
10521 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10522 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10523 timeRemaining[0][1] = whiteTimeRemaining;
10524 timeRemaining[1][1] = blackTimeRemaining;
10525 if (commentList[0] != NULL) {
10526 commentList[1] = commentList[0];
10527 commentList[0] = NULL;
10530 currentMove = forwardMostMove = backwardMostMove = 0;
10532 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
10534 initialRulePlies = FENrulePlies;
10535 for( i=0; i< nrCastlingRights; i++ )
10536 initialRights[i] = initial_position[CASTLING][i];
10538 yyboardindex = forwardMostMove;
10539 free(gameInfo.fen);
10540 gameInfo.fen = NULL;
10543 yyboardindex = forwardMostMove;
10544 cm = (ChessMove) Myylex();
10546 /* Handle comments interspersed among the tags */
10547 while (cm == Comment) {
10549 if (appData.debugMode)
10550 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10552 AppendComment(currentMove, p, FALSE);
10553 yyboardindex = forwardMostMove;
10554 cm = (ChessMove) Myylex();
10558 /* don't rely on existence of Event tag since if game was
10559 * pasted from clipboard the Event tag may not exist
10561 if (numPGNTags > 0){
10563 if (gameInfo.variant == VariantNormal) {
10564 VariantClass v = StringToVariant(gameInfo.event);
10565 // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
10566 if(v < VariantShogi) gameInfo.variant = v;
10569 if( appData.autoDisplayTags ) {
10570 tags = PGNTags(&gameInfo);
10571 TagsPopUp(tags, CmailMsg());
10576 /* Make something up, but don't display it now */
10581 if (cm == PositionDiagram) {
10584 Board initial_position;
10586 if (appData.debugMode)
10587 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
10589 if (!startedFromSetupPosition) {
10591 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
10592 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
10603 initial_position[i][j++] = CharToPiece(*p);
10606 while (*p == ' ' || *p == '\t' ||
10607 *p == '\n' || *p == '\r') p++;
10609 if (strncmp(p, "black", strlen("black"))==0)
10610 blackPlaysFirst = TRUE;
10612 blackPlaysFirst = FALSE;
10613 startedFromSetupPosition = TRUE;
10615 CopyBoard(boards[0], initial_position);
10616 if (blackPlaysFirst) {
10617 currentMove = forwardMostMove = backwardMostMove = 1;
10618 CopyBoard(boards[1], initial_position);
10619 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10620 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10621 timeRemaining[0][1] = whiteTimeRemaining;
10622 timeRemaining[1][1] = blackTimeRemaining;
10623 if (commentList[0] != NULL) {
10624 commentList[1] = commentList[0];
10625 commentList[0] = NULL;
10628 currentMove = forwardMostMove = backwardMostMove = 0;
10631 yyboardindex = forwardMostMove;
10632 cm = (ChessMove) Myylex();
10635 if (first.pr == NoProc) {
10636 StartChessProgram(&first);
10638 InitChessProgram(&first, FALSE);
10639 SendToProgram("force\n", &first);
10640 if (startedFromSetupPosition) {
10641 SendBoard(&first, forwardMostMove);
10642 if (appData.debugMode) {
10643 fprintf(debugFP, "Load Game\n");
10645 DisplayBothClocks();
10648 /* [HGM] server: flag to write setup moves in broadcast file as one */
10649 loadFlag = appData.suppressLoadMoves;
10651 while (cm == Comment) {
10653 if (appData.debugMode)
10654 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
10656 AppendComment(currentMove, p, FALSE);
10657 yyboardindex = forwardMostMove;
10658 cm = (ChessMove) Myylex();
10661 if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
10662 cm == WhiteWins || cm == BlackWins ||
10663 cm == GameIsDrawn || cm == GameUnfinished) {
10664 DisplayMessage("", _("No moves in game"));
10665 if (cmailMsgLoaded) {
10666 if (appData.debugMode)
10667 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
10671 DrawPosition(FALSE, boards[currentMove]);
10672 DisplayBothClocks();
10673 gameMode = EditGame;
10680 // [HGM] PV info: routine tests if comment empty
10681 if (!matchMode && (pausing || appData.timeDelay != 0)) {
10682 DisplayComment(currentMove - 1, commentList[currentMove]);
10684 if (!matchMode && appData.timeDelay != 0)
10685 DrawPosition(FALSE, boards[currentMove]);
10687 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
10688 programStats.ok_to_send = 1;
10691 /* if the first token after the PGN tags is a move
10692 * and not move number 1, retrieve it from the parser
10694 if (cm != MoveNumberOne)
10695 LoadGameOneMove(cm);
10697 /* load the remaining moves from the file */
10698 while (LoadGameOneMove(EndOfFile)) {
10699 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
10700 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
10703 /* rewind to the start of the game */
10704 currentMove = backwardMostMove;
10706 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
10708 if (oldGameMode == AnalyzeFile ||
10709 oldGameMode == AnalyzeMode) {
10710 AnalyzeFileEvent();
10713 if (matchMode || appData.timeDelay == 0) {
10715 gameMode = EditGame;
10717 } else if (appData.timeDelay > 0) {
10718 AutoPlayGameLoop();
10721 if (appData.debugMode)
10722 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
10724 loadFlag = 0; /* [HGM] true game starts */
10728 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
10730 ReloadPosition(offset)
10733 int positionNumber = lastLoadPositionNumber + offset;
10734 if (lastLoadPositionFP == NULL) {
10735 DisplayError(_("No position has been loaded yet"), 0);
10738 if (positionNumber <= 0) {
10739 DisplayError(_("Can't back up any further"), 0);
10742 return LoadPosition(lastLoadPositionFP, positionNumber,
10743 lastLoadPositionTitle);
10746 /* Load the nth position from the given file */
10748 LoadPositionFromFile(filename, n, title)
10756 if (strcmp(filename, "-") == 0) {
10757 return LoadPosition(stdin, n, "stdin");
10759 f = fopen(filename, "rb");
10761 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10762 DisplayError(buf, errno);
10765 return LoadPosition(f, n, title);
10770 /* Load the nth position from the given open file, and close it */
10772 LoadPosition(f, positionNumber, title)
10774 int positionNumber;
10777 char *p, line[MSG_SIZ];
10778 Board initial_position;
10779 int i, j, fenMode, pn;
10781 if (gameMode == Training )
10782 SetTrainingModeOff();
10784 if (gameMode != BeginningOfGame) {
10785 Reset(FALSE, TRUE);
10787 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
10788 fclose(lastLoadPositionFP);
10790 if (positionNumber == 0) positionNumber = 1;
10791 lastLoadPositionFP = f;
10792 lastLoadPositionNumber = positionNumber;
10793 safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
10794 if (first.pr == NoProc) {
10795 StartChessProgram(&first);
10796 InitChessProgram(&first, FALSE);
10798 pn = positionNumber;
10799 if (positionNumber < 0) {
10800 /* Negative position number means to seek to that byte offset */
10801 if (fseek(f, -positionNumber, 0) == -1) {
10802 DisplayError(_("Can't seek on position file"), 0);
10807 if (fseek(f, 0, 0) == -1) {
10808 if (f == lastLoadPositionFP ?
10809 positionNumber == lastLoadPositionNumber + 1 :
10810 positionNumber == 1) {
10813 DisplayError(_("Can't seek on position file"), 0);
10818 /* See if this file is FEN or old-style xboard */
10819 if (fgets(line, MSG_SIZ, f) == NULL) {
10820 DisplayError(_("Position not found in file"), 0);
10823 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
10824 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
10827 if (fenMode || line[0] == '#') pn--;
10829 /* skip positions before number pn */
10830 if (fgets(line, MSG_SIZ, f) == NULL) {
10832 DisplayError(_("Position not found in file"), 0);
10835 if (fenMode || line[0] == '#') pn--;
10840 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
10841 DisplayError(_("Bad FEN position in file"), 0);
10845 (void) fgets(line, MSG_SIZ, f);
10846 (void) fgets(line, MSG_SIZ, f);
10848 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
10849 (void) fgets(line, MSG_SIZ, f);
10850 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
10853 initial_position[i][j++] = CharToPiece(*p);
10857 blackPlaysFirst = FALSE;
10859 (void) fgets(line, MSG_SIZ, f);
10860 if (strncmp(line, "black", strlen("black"))==0)
10861 blackPlaysFirst = TRUE;
10864 startedFromSetupPosition = TRUE;
10866 SendToProgram("force\n", &first);
10867 CopyBoard(boards[0], initial_position);
10868 if (blackPlaysFirst) {
10869 currentMove = forwardMostMove = backwardMostMove = 1;
10870 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
10871 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
10872 CopyBoard(boards[1], initial_position);
10873 DisplayMessage("", _("Black to play"));
10875 currentMove = forwardMostMove = backwardMostMove = 0;
10876 DisplayMessage("", _("White to play"));
10878 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
10879 SendBoard(&first, forwardMostMove);
10880 if (appData.debugMode) {
10882 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
10883 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
10884 fprintf(debugFP, "Load Position\n");
10887 if (positionNumber > 1) {
10888 snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
10889 DisplayTitle(line);
10891 DisplayTitle(title);
10893 gameMode = EditGame;
10896 timeRemaining[0][1] = whiteTimeRemaining;
10897 timeRemaining[1][1] = blackTimeRemaining;
10898 DrawPosition(FALSE, boards[currentMove]);
10905 CopyPlayerNameIntoFileName(dest, src)
10908 while (*src != NULLCHAR && *src != ',') {
10913 *(*dest)++ = *src++;
10918 char *DefaultFileName(ext)
10921 static char def[MSG_SIZ];
10924 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
10926 CopyPlayerNameIntoFileName(&p, gameInfo.white);
10928 CopyPlayerNameIntoFileName(&p, gameInfo.black);
10930 safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
10937 /* Save the current game to the given file */
10939 SaveGameToFile(filename, append)
10946 if (strcmp(filename, "-") == 0) {
10947 return SaveGame(stdout, 0, NULL);
10949 f = fopen(filename, append ? "a" : "w");
10951 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
10952 DisplayError(buf, errno);
10955 return SaveGame(f, 0, NULL);
10964 static char buf[MSG_SIZ];
10967 p = strchr(str, ' ');
10968 if (p == NULL) return str;
10969 strncpy(buf, str, p - str);
10970 buf[p - str] = NULLCHAR;
10974 #define PGN_MAX_LINE 75
10976 #define PGN_SIDE_WHITE 0
10977 #define PGN_SIDE_BLACK 1
10980 static int FindFirstMoveOutOfBook( int side )
10984 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
10985 int index = backwardMostMove;
10986 int has_book_hit = 0;
10988 if( (index % 2) != side ) {
10992 while( index < forwardMostMove ) {
10993 /* Check to see if engine is in book */
10994 int depth = pvInfoList[index].depth;
10995 int score = pvInfoList[index].score;
11001 else if( score == 0 && depth == 63 ) {
11002 in_book = 1; /* Zappa */
11004 else if( score == 2 && depth == 99 ) {
11005 in_book = 1; /* Abrok */
11008 has_book_hit += in_book;
11024 void GetOutOfBookInfo( char * buf )
11028 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
11030 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
11031 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
11035 if( oob[0] >= 0 || oob[1] >= 0 ) {
11036 for( i=0; i<2; i++ ) {
11040 if( i > 0 && oob[0] >= 0 ) {
11041 strcat( buf, " " );
11044 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
11045 sprintf( buf+strlen(buf), "%s%.2f",
11046 pvInfoList[idx].score >= 0 ? "+" : "",
11047 pvInfoList[idx].score / 100.0 );
11053 /* Save game in PGN style and close the file */
11058 int i, offset, linelen, newblock;
11062 int movelen, numlen, blank;
11063 char move_buffer[100]; /* [AS] Buffer for move+PV info */
11065 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
11067 tm = time((time_t *) NULL);
11069 PrintPGNTags(f, &gameInfo);
11071 if (backwardMostMove > 0 || startedFromSetupPosition) {
11072 char *fen = PositionToFEN(backwardMostMove, NULL);
11073 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
11074 fprintf(f, "\n{--------------\n");
11075 PrintPosition(f, backwardMostMove);
11076 fprintf(f, "--------------}\n");
11080 /* [AS] Out of book annotation */
11081 if( appData.saveOutOfBookInfo ) {
11084 GetOutOfBookInfo( buf );
11086 if( buf[0] != '\0' ) {
11087 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
11094 i = backwardMostMove;
11098 while (i < forwardMostMove) {
11099 /* Print comments preceding this move */
11100 if (commentList[i] != NULL) {
11101 if (linelen > 0) fprintf(f, "\n");
11102 fprintf(f, "%s", commentList[i]);
11107 /* Format move number */
11109 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
11112 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
11114 numtext[0] = NULLCHAR;
11116 numlen = strlen(numtext);
11119 /* Print move number */
11120 blank = linelen > 0 && numlen > 0;
11121 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
11130 fprintf(f, "%s", numtext);
11134 safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
11135 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
11138 blank = linelen > 0 && movelen > 0;
11139 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
11148 fprintf(f, "%s", move_buffer);
11149 linelen += movelen;
11151 /* [AS] Add PV info if present */
11152 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
11153 /* [HGM] add time */
11154 char buf[MSG_SIZ]; int seconds;
11156 seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
11162 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
11165 seconds = (seconds + 4)/10; // round to full seconds
11167 snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
11169 snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
11172 snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
11173 pvInfoList[i].score >= 0 ? "+" : "",
11174 pvInfoList[i].score / 100.0,
11175 pvInfoList[i].depth,
11178 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
11180 /* Print score/depth */
11181 blank = linelen > 0 && movelen > 0;
11182 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
11191 fprintf(f, "%s", move_buffer);
11192 linelen += movelen;
11198 /* Start a new line */
11199 if (linelen > 0) fprintf(f, "\n");
11201 /* Print comments after last move */
11202 if (commentList[i] != NULL) {
11203 fprintf(f, "%s\n", commentList[i]);
11207 if (gameInfo.resultDetails != NULL &&
11208 gameInfo.resultDetails[0] != NULLCHAR) {
11209 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
11210 PGNResult(gameInfo.result));
11212 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
11216 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
11220 /* Save game in old style and close the file */
11222 SaveGameOldStyle(f)
11228 tm = time((time_t *) NULL);
11230 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
11233 if (backwardMostMove > 0 || startedFromSetupPosition) {
11234 fprintf(f, "\n[--------------\n");
11235 PrintPosition(f, backwardMostMove);
11236 fprintf(f, "--------------]\n");
11241 i = backwardMostMove;
11242 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
11244 while (i < forwardMostMove) {
11245 if (commentList[i] != NULL) {
11246 fprintf(f, "[%s]\n", commentList[i]);
11249 if ((i % 2) == 1) {
11250 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
11253 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
11255 if (commentList[i] != NULL) {
11259 if (i >= forwardMostMove) {
11263 fprintf(f, "%s\n", parseList[i]);
11268 if (commentList[i] != NULL) {
11269 fprintf(f, "[%s]\n", commentList[i]);
11272 /* This isn't really the old style, but it's close enough */
11273 if (gameInfo.resultDetails != NULL &&
11274 gameInfo.resultDetails[0] != NULLCHAR) {
11275 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
11276 gameInfo.resultDetails);
11278 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
11285 /* Save the current game to open file f and close the file */
11287 SaveGame(f, dummy, dummy2)
11292 if (gameMode == EditPosition) EditPositionDone(TRUE);
11293 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
11294 if (appData.oldSaveStyle)
11295 return SaveGameOldStyle(f);
11297 return SaveGamePGN(f);
11300 /* Save the current position to the given file */
11302 SavePositionToFile(filename)
11308 if (strcmp(filename, "-") == 0) {
11309 return SavePosition(stdout, 0, NULL);
11311 f = fopen(filename, "a");
11313 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
11314 DisplayError(buf, errno);
11317 SavePosition(f, 0, NULL);
11323 /* Save the current position to the given open file and close the file */
11325 SavePosition(f, dummy, dummy2)
11333 if (gameMode == EditPosition) EditPositionDone(TRUE);
11334 if (appData.oldSaveStyle) {
11335 tm = time((time_t *) NULL);
11337 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
11339 fprintf(f, "[--------------\n");
11340 PrintPosition(f, currentMove);
11341 fprintf(f, "--------------]\n");
11343 fen = PositionToFEN(currentMove, NULL);
11344 fprintf(f, "%s\n", fen);
11352 ReloadCmailMsgEvent(unregister)
11356 static char *inFilename = NULL;
11357 static char *outFilename;
11359 struct stat inbuf, outbuf;
11362 /* Any registered moves are unregistered if unregister is set, */
11363 /* i.e. invoked by the signal handler */
11365 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
11366 cmailMoveRegistered[i] = FALSE;
11367 if (cmailCommentList[i] != NULL) {
11368 free(cmailCommentList[i]);
11369 cmailCommentList[i] = NULL;
11372 nCmailMovesRegistered = 0;
11375 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
11376 cmailResult[i] = CMAIL_NOT_RESULT;
11380 if (inFilename == NULL) {
11381 /* Because the filenames are static they only get malloced once */
11382 /* and they never get freed */
11383 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
11384 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
11386 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
11387 sprintf(outFilename, "%s.out", appData.cmailGameName);
11390 status = stat(outFilename, &outbuf);
11392 cmailMailedMove = FALSE;
11394 status = stat(inFilename, &inbuf);
11395 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
11398 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
11399 counts the games, notes how each one terminated, etc.
11401 It would be nice to remove this kludge and instead gather all
11402 the information while building the game list. (And to keep it
11403 in the game list nodes instead of having a bunch of fixed-size
11404 parallel arrays.) Note this will require getting each game's
11405 termination from the PGN tags, as the game list builder does
11406 not process the game moves. --mann
11408 cmailMsgLoaded = TRUE;
11409 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
11411 /* Load first game in the file or popup game menu */
11412 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
11414 #endif /* !WIN32 */
11422 char string[MSG_SIZ];
11424 if ( cmailMailedMove
11425 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
11426 return TRUE; /* Allow free viewing */
11429 /* Unregister move to ensure that we don't leave RegisterMove */
11430 /* with the move registered when the conditions for registering no */
11432 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11433 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
11434 nCmailMovesRegistered --;
11436 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
11438 free(cmailCommentList[lastLoadGameNumber - 1]);
11439 cmailCommentList[lastLoadGameNumber - 1] = NULL;
11443 if (cmailOldMove == -1) {
11444 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
11448 if (currentMove > cmailOldMove + 1) {
11449 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
11453 if (currentMove < cmailOldMove) {
11454 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
11458 if (forwardMostMove > currentMove) {
11459 /* Silently truncate extra moves */
11463 if ( (currentMove == cmailOldMove + 1)
11464 || ( (currentMove == cmailOldMove)
11465 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
11466 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
11467 if (gameInfo.result != GameUnfinished) {
11468 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
11471 if (commentList[currentMove] != NULL) {
11472 cmailCommentList[lastLoadGameNumber - 1]
11473 = StrSave(commentList[currentMove]);
11475 safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
11477 if (appData.debugMode)
11478 fprintf(debugFP, "Saving %s for game %d\n",
11479 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
11481 snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
11483 f = fopen(string, "w");
11484 if (appData.oldSaveStyle) {
11485 SaveGameOldStyle(f); /* also closes the file */
11487 snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
11488 f = fopen(string, "w");
11489 SavePosition(f, 0, NULL); /* also closes the file */
11491 fprintf(f, "{--------------\n");
11492 PrintPosition(f, currentMove);
11493 fprintf(f, "--------------}\n\n");
11495 SaveGame(f, 0, NULL); /* also closes the file*/
11498 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
11499 nCmailMovesRegistered ++;
11500 } else if (nCmailGames == 1) {
11501 DisplayError(_("You have not made a move yet"), 0);
11512 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
11513 FILE *commandOutput;
11514 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
11515 int nBytes = 0; /* Suppress warnings on uninitialized variables */
11521 if (! cmailMsgLoaded) {
11522 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
11526 if (nCmailGames == nCmailResults) {
11527 DisplayError(_("No unfinished games"), 0);
11531 #if CMAIL_PROHIBIT_REMAIL
11532 if (cmailMailedMove) {
11533 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);
11534 DisplayError(msg, 0);
11539 if (! (cmailMailedMove || RegisterMove())) return;
11541 if ( cmailMailedMove
11542 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
11543 snprintf(string, MSG_SIZ, partCommandString,
11544 appData.debugMode ? " -v" : "", appData.cmailGameName);
11545 commandOutput = popen(string, "r");
11547 if (commandOutput == NULL) {
11548 DisplayError(_("Failed to invoke cmail"), 0);
11550 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
11551 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
11553 if (nBuffers > 1) {
11554 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
11555 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
11556 nBytes = MSG_SIZ - 1;
11558 (void) memcpy(msg, buffer, nBytes);
11560 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
11562 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
11563 cmailMailedMove = TRUE; /* Prevent >1 moves */
11566 for (i = 0; i < nCmailGames; i ++) {
11567 if (cmailResult[i] == CMAIL_NOT_RESULT) {
11572 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
11574 snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
11576 appData.cmailGameName,
11578 LoadGameFromFile(buffer, 1, buffer, FALSE);
11579 cmailMsgLoaded = FALSE;
11583 DisplayInformation(msg);
11584 pclose(commandOutput);
11587 if ((*cmailMsg) != '\0') {
11588 DisplayInformation(cmailMsg);
11593 #endif /* !WIN32 */
11602 int prependComma = 0;
11604 char string[MSG_SIZ]; /* Space for game-list */
11607 if (!cmailMsgLoaded) return "";
11609 if (cmailMailedMove) {
11610 snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
11612 /* Create a list of games left */
11613 snprintf(string, MSG_SIZ, "[");
11614 for (i = 0; i < nCmailGames; i ++) {
11615 if (! ( cmailMoveRegistered[i]
11616 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
11617 if (prependComma) {
11618 snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
11620 snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
11624 strcat(string, number);
11627 strcat(string, "]");
11629 if (nCmailMovesRegistered + nCmailResults == 0) {
11630 switch (nCmailGames) {
11632 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
11636 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
11640 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
11645 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
11647 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
11652 if (nCmailResults == nCmailGames) {
11653 snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
11655 snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
11660 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
11672 if (gameMode == Training)
11673 SetTrainingModeOff();
11676 cmailMsgLoaded = FALSE;
11677 if (appData.icsActive) {
11678 SendToICS(ics_prefix);
11679 SendToICS("refresh\n");
11689 /* Give up on clean exit */
11693 /* Keep trying for clean exit */
11697 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
11699 if (telnetISR != NULL) {
11700 RemoveInputSource(telnetISR);
11702 if (icsPR != NoProc) {
11703 DestroyChildProcess(icsPR, TRUE);
11706 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
11707 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
11709 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
11710 /* make sure this other one finishes before killing it! */
11711 if(endingGame) { int count = 0;
11712 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
11713 while(endingGame && count++ < 10) DoSleep(1);
11714 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
11717 /* Kill off chess programs */
11718 if (first.pr != NoProc) {
11721 DoSleep( appData.delayBeforeQuit );
11722 SendToProgram("quit\n", &first);
11723 DoSleep( appData.delayAfterQuit );
11724 DestroyChildProcess(first.pr, 10 /* [AS] first.useSigterm */ );
11726 if (second.pr != NoProc) {
11727 DoSleep( appData.delayBeforeQuit );
11728 SendToProgram("quit\n", &second);
11729 DoSleep( appData.delayAfterQuit );
11730 DestroyChildProcess(second.pr, 10 /* [AS] second.useSigterm */ );
11732 if (first.isr != NULL) {
11733 RemoveInputSource(first.isr);
11735 if (second.isr != NULL) {
11736 RemoveInputSource(second.isr);
11739 ShutDownFrontEnd();
11746 if (appData.debugMode)
11747 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
11751 if (gameMode == MachinePlaysWhite ||
11752 gameMode == MachinePlaysBlack) {
11755 DisplayBothClocks();
11757 if (gameMode == PlayFromGameFile) {
11758 if (appData.timeDelay >= 0)
11759 AutoPlayGameLoop();
11760 } else if (gameMode == IcsExamining && pauseExamInvalid) {
11761 Reset(FALSE, TRUE);
11762 SendToICS(ics_prefix);
11763 SendToICS("refresh\n");
11764 } else if (currentMove < forwardMostMove) {
11765 ForwardInner(forwardMostMove);
11767 pauseExamInvalid = FALSE;
11769 switch (gameMode) {
11773 pauseExamForwardMostMove = forwardMostMove;
11774 pauseExamInvalid = FALSE;
11777 case IcsPlayingWhite:
11778 case IcsPlayingBlack:
11782 case PlayFromGameFile:
11783 (void) StopLoadGameTimer();
11787 case BeginningOfGame:
11788 if (appData.icsActive) return;
11789 /* else fall through */
11790 case MachinePlaysWhite:
11791 case MachinePlaysBlack:
11792 case TwoMachinesPlay:
11793 if (forwardMostMove == 0)
11794 return; /* don't pause if no one has moved */
11795 if ((gameMode == MachinePlaysWhite &&
11796 !WhiteOnMove(forwardMostMove)) ||
11797 (gameMode == MachinePlaysBlack &&
11798 WhiteOnMove(forwardMostMove))) {
11811 char title[MSG_SIZ];
11813 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
11814 safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
11816 snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
11817 WhiteOnMove(currentMove - 1) ? " " : ".. ",
11818 parseList[currentMove - 1]);
11821 EditCommentPopUp(currentMove, title, commentList[currentMove]);
11828 char *tags = PGNTags(&gameInfo);
11829 EditTagsPopUp(tags, NULL);
11836 if (appData.noChessProgram || gameMode == AnalyzeMode)
11839 if (gameMode != AnalyzeFile) {
11840 if (!appData.icsEngineAnalyze) {
11842 if (gameMode != EditGame) return;
11844 ResurrectChessProgram();
11845 SendToProgram("analyze\n", &first);
11846 first.analyzing = TRUE;
11847 /*first.maybeThinking = TRUE;*/
11848 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11849 EngineOutputPopUp();
11851 if (!appData.icsEngineAnalyze) gameMode = AnalyzeMode;
11856 StartAnalysisClock();
11857 GetTimeMark(&lastNodeCountTime);
11864 if (appData.noChessProgram || gameMode == AnalyzeFile)
11867 if (gameMode != AnalyzeMode) {
11869 if (gameMode != EditGame) return;
11870 ResurrectChessProgram();
11871 SendToProgram("analyze\n", &first);
11872 first.analyzing = TRUE;
11873 /*first.maybeThinking = TRUE;*/
11874 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
11875 EngineOutputPopUp();
11877 gameMode = AnalyzeFile;
11882 StartAnalysisClock();
11883 GetTimeMark(&lastNodeCountTime);
11888 MachineWhiteEvent()
11891 char *bookHit = NULL;
11893 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
11897 if (gameMode == PlayFromGameFile ||
11898 gameMode == TwoMachinesPlay ||
11899 gameMode == Training ||
11900 gameMode == AnalyzeMode ||
11901 gameMode == EndOfGame)
11904 if (gameMode == EditPosition)
11905 EditPositionDone(TRUE);
11907 if (!WhiteOnMove(currentMove)) {
11908 DisplayError(_("It is not White's turn"), 0);
11912 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
11915 if (gameMode == EditGame || gameMode == AnalyzeMode ||
11916 gameMode == AnalyzeFile)
11919 ResurrectChessProgram(); /* in case it isn't running */
11920 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
11921 gameMode = MachinePlaysWhite;
11924 gameMode = MachinePlaysWhite;
11928 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
11930 if (first.sendName) {
11931 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
11932 SendToProgram(buf, &first);
11934 if (first.sendTime) {
11935 if (first.useColors) {
11936 SendToProgram("black\n", &first); /*gnu kludge*/
11938 SendTimeRemaining(&first, TRUE);
11940 if (first.useColors) {
11941 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
11943 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
11944 SetMachineThinkingEnables();
11945 first.maybeThinking = TRUE;
11949 if (appData.autoFlipView && !flipView) {
11950 flipView = !flipView;
11951 DrawPosition(FALSE, NULL);
11952 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
11955 if(bookHit) { // [HGM] book: simulate book reply
11956 static char bookMove[MSG_SIZ]; // a bit generous?
11958 programStats.nodes = programStats.depth = programStats.time =
11959 programStats.score = programStats.got_only_move = 0;
11960 sprintf(programStats.movelist, "%s (xbook)", bookHit);
11962 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
11963 strcat(bookMove, bookHit);
11964 HandleMachineMove(bookMove, &first);
11969 MachineBlackEvent()
11972 char *bookHit = NULL;
11974 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
11978 if (gameMode == PlayFromGameFile ||
11979 gameMode == TwoMachinesPlay ||
11980 gameMode == Training ||
11981 gameMode == AnalyzeMode ||
11982 gameMode == EndOfGame)
11985 if (gameMode == EditPosition)
11986 EditPositionDone(TRUE);
11988 if (WhiteOnMove(currentMove)) {
11989 DisplayError(_("It is not Black's turn"), 0);
11993 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
11996 if (gameMode == EditGame || gameMode == AnalyzeMode ||
11997 gameMode == AnalyzeFile)
12000 ResurrectChessProgram(); /* in case it isn't running */
12001 gameMode = MachinePlaysBlack;
12005 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
12007 if (first.sendName) {
12008 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
12009 SendToProgram(buf, &first);
12011 if (first.sendTime) {
12012 if (first.useColors) {
12013 SendToProgram("white\n", &first); /*gnu kludge*/
12015 SendTimeRemaining(&first, FALSE);
12017 if (first.useColors) {
12018 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
12020 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
12021 SetMachineThinkingEnables();
12022 first.maybeThinking = TRUE;
12025 if (appData.autoFlipView && flipView) {
12026 flipView = !flipView;
12027 DrawPosition(FALSE, NULL);
12028 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
12030 if(bookHit) { // [HGM] book: simulate book reply
12031 static char bookMove[MSG_SIZ]; // a bit generous?
12033 programStats.nodes = programStats.depth = programStats.time =
12034 programStats.score = programStats.got_only_move = 0;
12035 sprintf(programStats.movelist, "%s (xbook)", bookHit);
12037 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
12038 strcat(bookMove, bookHit);
12039 HandleMachineMove(bookMove, &first);
12045 DisplayTwoMachinesTitle()
12048 if (appData.matchGames > 0) {
12049 if (first.twoMachinesColor[0] == 'w') {
12050 snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
12051 gameInfo.white, gameInfo.black,
12052 first.matchWins, second.matchWins,
12053 matchGame - 1 - (first.matchWins + second.matchWins));
12055 snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)",
12056 gameInfo.white, gameInfo.black,
12057 second.matchWins, first.matchWins,
12058 matchGame - 1 - (first.matchWins + second.matchWins));
12061 snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black);
12067 SettingsMenuIfReady()
12069 if (second.lastPing != second.lastPong) {
12070 DisplayMessage("", _("Waiting for second chess program"));
12071 ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
12075 DisplayMessage("", "");
12076 SettingsPopUp(&second);
12080 WaitForEngine(ChessProgramState *cps, DelayedEventCallback retry)
12083 if (cps->pr == NULL) {
12084 StartChessProgram(cps);
12085 if (cps->protocolVersion == 1) {
12088 /* kludge: allow timeout for initial "feature" command */
12090 snprintf(buf, MSG_SIZ, _("Starting %s chess program"), cps->which);
12091 DisplayMessage("", buf);
12092 ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
12100 TwoMachinesEvent P((void))
12104 ChessProgramState *onmove;
12105 char *bookHit = NULL;
12106 static int stalling = 0;
12108 if (appData.noChessProgram) return;
12110 switch (gameMode) {
12111 case TwoMachinesPlay:
12113 case MachinePlaysWhite:
12114 case MachinePlaysBlack:
12115 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
12116 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
12120 case BeginningOfGame:
12121 case PlayFromGameFile:
12124 if (gameMode != EditGame) return;
12127 EditPositionDone(TRUE);
12138 // forwardMostMove = currentMove;
12139 TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
12140 ResurrectChessProgram(); /* in case first program isn't running */
12142 if(WaitForEngine(&second, TwoMachinesEventIfReady)) return;
12143 if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
12144 DisplayMessage("", _("Waiting for first chess program"));
12145 ScheduleDelayedEvent(TwoMachinesEvent, 10);
12149 InitChessProgram(&second, FALSE);
12150 SendToProgram("force\n", &second);
12152 if(second.lastPing != second.lastPong) { // [HGM] second engine might have to reallocate hash
12153 if(!stalling) DisplayMessage("", _("Waiting for second chess program"));
12155 ScheduleDelayedEvent(TwoMachinesEvent, 10);
12159 DisplayMessage("", "");
12160 if (startedFromSetupPosition) {
12161 SendBoard(&second, backwardMostMove);
12162 if (appData.debugMode) {
12163 fprintf(debugFP, "Two Machines\n");
12166 for (i = backwardMostMove; i < forwardMostMove; i++) {
12167 SendMoveToProgram(i, &second);
12170 gameMode = TwoMachinesPlay;
12174 DisplayTwoMachinesTitle();
12176 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
12182 SendToProgram(first.computerString, &first);
12183 if (first.sendName) {
12184 snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
12185 SendToProgram(buf, &first);
12187 SendToProgram(second.computerString, &second);
12188 if (second.sendName) {
12189 snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
12190 SendToProgram(buf, &second);
12194 if (!first.sendTime || !second.sendTime) {
12195 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
12196 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
12198 if (onmove->sendTime) {
12199 if (onmove->useColors) {
12200 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
12202 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
12204 if (onmove->useColors) {
12205 SendToProgram(onmove->twoMachinesColor, onmove);
12207 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
12208 // SendToProgram("go\n", onmove);
12209 onmove->maybeThinking = TRUE;
12210 SetMachineThinkingEnables();
12214 if(bookHit) { // [HGM] book: simulate book reply
12215 static char bookMove[MSG_SIZ]; // a bit generous?
12217 programStats.nodes = programStats.depth = programStats.time =
12218 programStats.score = programStats.got_only_move = 0;
12219 sprintf(programStats.movelist, "%s (xbook)", bookHit);
12221 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
12222 strcat(bookMove, bookHit);
12223 savedMessage = bookMove; // args for deferred call
12224 savedState = onmove;
12225 ScheduleDelayedEvent(DeferredBookMove, 1);
12232 if (gameMode == Training) {
12233 SetTrainingModeOff();
12234 gameMode = PlayFromGameFile;
12235 DisplayMessage("", _("Training mode off"));
12237 gameMode = Training;
12238 animateTraining = appData.animate;
12240 /* make sure we are not already at the end of the game */
12241 if (currentMove < forwardMostMove) {
12242 SetTrainingModeOn();
12243 DisplayMessage("", _("Training mode on"));
12245 gameMode = PlayFromGameFile;
12246 DisplayError(_("Already at end of game"), 0);
12255 if (!appData.icsActive) return;
12256 switch (gameMode) {
12257 case IcsPlayingWhite:
12258 case IcsPlayingBlack:
12261 case BeginningOfGame:
12269 EditPositionDone(TRUE);
12282 gameMode = IcsIdle;
12293 switch (gameMode) {
12295 SetTrainingModeOff();
12297 case MachinePlaysWhite:
12298 case MachinePlaysBlack:
12299 case BeginningOfGame:
12300 SendToProgram("force\n", &first);
12301 SetUserThinkingEnables();
12303 case PlayFromGameFile:
12304 (void) StopLoadGameTimer();
12305 if (gameFileFP != NULL) {
12310 EditPositionDone(TRUE);
12315 SendToProgram("force\n", &first);
12317 case TwoMachinesPlay:
12318 GameEnds(EndOfFile, NULL, GE_PLAYER);
12319 ResurrectChessProgram();
12320 SetUserThinkingEnables();
12323 ResurrectChessProgram();
12325 case IcsPlayingBlack:
12326 case IcsPlayingWhite:
12327 DisplayError(_("Warning: You are still playing a game"), 0);
12330 DisplayError(_("Warning: You are still observing a game"), 0);
12333 DisplayError(_("Warning: You are still examining a game"), 0);
12344 first.offeredDraw = second.offeredDraw = 0;
12346 if (gameMode == PlayFromGameFile) {
12347 whiteTimeRemaining = timeRemaining[0][currentMove];
12348 blackTimeRemaining = timeRemaining[1][currentMove];
12352 if (gameMode == MachinePlaysWhite ||
12353 gameMode == MachinePlaysBlack ||
12354 gameMode == TwoMachinesPlay ||
12355 gameMode == EndOfGame) {
12356 i = forwardMostMove;
12357 while (i > currentMove) {
12358 SendToProgram("undo\n", &first);
12361 whiteTimeRemaining = timeRemaining[0][currentMove];
12362 blackTimeRemaining = timeRemaining[1][currentMove];
12363 DisplayBothClocks();
12364 if (whiteFlag || blackFlag) {
12365 whiteFlag = blackFlag = 0;
12370 gameMode = EditGame;
12377 EditPositionEvent()
12379 if (gameMode == EditPosition) {
12385 if (gameMode != EditGame) return;
12387 gameMode = EditPosition;
12390 if (currentMove > 0)
12391 CopyBoard(boards[0], boards[currentMove]);
12393 blackPlaysFirst = !WhiteOnMove(currentMove);
12395 currentMove = forwardMostMove = backwardMostMove = 0;
12396 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12403 /* [DM] icsEngineAnalyze - possible call from other functions */
12404 if (appData.icsEngineAnalyze) {
12405 appData.icsEngineAnalyze = FALSE;
12407 DisplayMessage("",_("Close ICS engine analyze..."));
12409 if (first.analysisSupport && first.analyzing) {
12410 SendToProgram("exit\n", &first);
12411 first.analyzing = FALSE;
12413 thinkOutput[0] = NULLCHAR;
12417 EditPositionDone(Boolean fakeRights)
12419 int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
12421 startedFromSetupPosition = TRUE;
12422 InitChessProgram(&first, FALSE);
12423 if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
12424 boards[0][EP_STATUS] = EP_NONE;
12425 boards[0][CASTLING][2] = boards[0][CASTLING][5] = BOARD_WIDTH>>1;
12426 if(boards[0][0][BOARD_WIDTH>>1] == king) {
12427 boards[0][CASTLING][1] = boards[0][0][BOARD_LEFT] == WhiteRook ? 0 : NoRights;
12428 boards[0][CASTLING][0] = boards[0][0][BOARD_RGHT-1] == WhiteRook ? BOARD_RGHT-1 : NoRights;
12429 } else boards[0][CASTLING][2] = NoRights;
12430 if(boards[0][BOARD_HEIGHT-1][BOARD_WIDTH>>1] == WHITE_TO_BLACK king) {
12431 boards[0][CASTLING][4] = boards[0][BOARD_HEIGHT-1][BOARD_LEFT] == BlackRook ? 0 : NoRights;
12432 boards[0][CASTLING][3] = boards[0][BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook ? BOARD_RGHT-1 : NoRights;
12433 } else boards[0][CASTLING][5] = NoRights;
12435 SendToProgram("force\n", &first);
12436 if (blackPlaysFirst) {
12437 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12438 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12439 currentMove = forwardMostMove = backwardMostMove = 1;
12440 CopyBoard(boards[1], boards[0]);
12442 currentMove = forwardMostMove = backwardMostMove = 0;
12444 SendBoard(&first, forwardMostMove);
12445 if (appData.debugMode) {
12446 fprintf(debugFP, "EditPosDone\n");
12449 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
12450 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
12451 gameMode = EditGame;
12453 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12454 ClearHighlights(); /* [AS] */
12457 /* Pause for `ms' milliseconds */
12458 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
12468 } while (SubtractTimeMarks(&m2, &m1) < ms);
12471 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
12473 SendMultiLineToICS(buf)
12476 char temp[MSG_SIZ+1], *p;
12483 strncpy(temp, buf, len);
12488 if (*p == '\n' || *p == '\r')
12493 strcat(temp, "\n");
12495 SendToPlayer(temp, strlen(temp));
12499 SetWhiteToPlayEvent()
12501 if (gameMode == EditPosition) {
12502 blackPlaysFirst = FALSE;
12503 DisplayBothClocks(); /* works because currentMove is 0 */
12504 } else if (gameMode == IcsExamining) {
12505 SendToICS(ics_prefix);
12506 SendToICS("tomove white\n");
12511 SetBlackToPlayEvent()
12513 if (gameMode == EditPosition) {
12514 blackPlaysFirst = TRUE;
12515 currentMove = 1; /* kludge */
12516 DisplayBothClocks();
12518 } else if (gameMode == IcsExamining) {
12519 SendToICS(ics_prefix);
12520 SendToICS("tomove black\n");
12525 EditPositionMenuEvent(selection, x, y)
12526 ChessSquare selection;
12530 ChessSquare piece = boards[0][y][x];
12532 if (gameMode != EditPosition && gameMode != IcsExamining) return;
12534 switch (selection) {
12536 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
12537 SendToICS(ics_prefix);
12538 SendToICS("bsetup clear\n");
12539 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
12540 SendToICS(ics_prefix);
12541 SendToICS("clearboard\n");
12543 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
12544 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
12545 for (y = 0; y < BOARD_HEIGHT; y++) {
12546 if (gameMode == IcsExamining) {
12547 if (boards[currentMove][y][x] != EmptySquare) {
12548 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
12553 boards[0][y][x] = p;
12558 if (gameMode == EditPosition) {
12559 DrawPosition(FALSE, boards[0]);
12564 SetWhiteToPlayEvent();
12568 SetBlackToPlayEvent();
12572 if (gameMode == IcsExamining) {
12573 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
12574 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
12577 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
12578 if(x == BOARD_LEFT-2) {
12579 if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
12580 boards[0][y][1] = 0;
12582 if(x == BOARD_RGHT+1) {
12583 if(y >= gameInfo.holdingsSize) break;
12584 boards[0][y][BOARD_WIDTH-2] = 0;
12587 boards[0][y][x] = EmptySquare;
12588 DrawPosition(FALSE, boards[0]);
12593 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
12594 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
12595 selection = (ChessSquare) (PROMOTED piece);
12596 } else if(piece == EmptySquare) selection = WhiteSilver;
12597 else selection = (ChessSquare)((int)piece - 1);
12601 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
12602 piece > (int)BlackMan && piece <= (int)BlackKing ) {
12603 selection = (ChessSquare) (DEMOTED piece);
12604 } else if(piece == EmptySquare) selection = BlackSilver;
12605 else selection = (ChessSquare)((int)piece + 1);
12610 if(gameInfo.variant == VariantShatranj ||
12611 gameInfo.variant == VariantXiangqi ||
12612 gameInfo.variant == VariantCourier ||
12613 gameInfo.variant == VariantMakruk )
12614 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
12619 if(gameInfo.variant == VariantXiangqi)
12620 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
12621 if(gameInfo.variant == VariantKnightmate)
12622 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
12625 if (gameMode == IcsExamining) {
12626 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
12627 snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
12628 PieceToChar(selection), AAA + x, ONE + y);
12631 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
12633 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
12634 n = PieceToNumber(selection - BlackPawn);
12635 if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
12636 boards[0][BOARD_HEIGHT-1-n][0] = selection;
12637 boards[0][BOARD_HEIGHT-1-n][1]++;
12639 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
12640 n = PieceToNumber(selection);
12641 if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
12642 boards[0][n][BOARD_WIDTH-1] = selection;
12643 boards[0][n][BOARD_WIDTH-2]++;
12646 boards[0][y][x] = selection;
12647 DrawPosition(TRUE, boards[0]);
12655 DropMenuEvent(selection, x, y)
12656 ChessSquare selection;
12659 ChessMove moveType;
12661 switch (gameMode) {
12662 case IcsPlayingWhite:
12663 case MachinePlaysBlack:
12664 if (!WhiteOnMove(currentMove)) {
12665 DisplayMoveError(_("It is Black's turn"));
12668 moveType = WhiteDrop;
12670 case IcsPlayingBlack:
12671 case MachinePlaysWhite:
12672 if (WhiteOnMove(currentMove)) {
12673 DisplayMoveError(_("It is White's turn"));
12676 moveType = BlackDrop;
12679 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
12685 if (moveType == BlackDrop && selection < BlackPawn) {
12686 selection = (ChessSquare) ((int) selection
12687 + (int) BlackPawn - (int) WhitePawn);
12689 if (boards[currentMove][y][x] != EmptySquare) {
12690 DisplayMoveError(_("That square is occupied"));
12694 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
12700 /* Accept a pending offer of any kind from opponent */
12702 if (appData.icsActive) {
12703 SendToICS(ics_prefix);
12704 SendToICS("accept\n");
12705 } else if (cmailMsgLoaded) {
12706 if (currentMove == cmailOldMove &&
12707 commentList[cmailOldMove] != NULL &&
12708 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12709 "Black offers a draw" : "White offers a draw")) {
12711 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12712 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
12714 DisplayError(_("There is no pending offer on this move"), 0);
12715 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12718 /* Not used for offers from chess program */
12725 /* Decline a pending offer of any kind from opponent */
12727 if (appData.icsActive) {
12728 SendToICS(ics_prefix);
12729 SendToICS("decline\n");
12730 } else if (cmailMsgLoaded) {
12731 if (currentMove == cmailOldMove &&
12732 commentList[cmailOldMove] != NULL &&
12733 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12734 "Black offers a draw" : "White offers a draw")) {
12736 AppendComment(cmailOldMove, "Draw declined", TRUE);
12737 DisplayComment(cmailOldMove - 1, "Draw declined");
12740 DisplayError(_("There is no pending offer on this move"), 0);
12743 /* Not used for offers from chess program */
12750 /* Issue ICS rematch command */
12751 if (appData.icsActive) {
12752 SendToICS(ics_prefix);
12753 SendToICS("rematch\n");
12760 /* Call your opponent's flag (claim a win on time) */
12761 if (appData.icsActive) {
12762 SendToICS(ics_prefix);
12763 SendToICS("flag\n");
12765 switch (gameMode) {
12768 case MachinePlaysWhite:
12771 GameEnds(GameIsDrawn, "Both players ran out of time",
12774 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
12776 DisplayError(_("Your opponent is not out of time"), 0);
12779 case MachinePlaysBlack:
12782 GameEnds(GameIsDrawn, "Both players ran out of time",
12785 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
12787 DisplayError(_("Your opponent is not out of time"), 0);
12795 ClockClick(int which)
12796 { // [HGM] code moved to back-end from winboard.c
12797 if(which) { // black clock
12798 if (gameMode == EditPosition || gameMode == IcsExamining) {
12799 if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
12800 SetBlackToPlayEvent();
12801 } else if (gameMode == EditGame || shiftKey) {
12802 AdjustClock(which, -1);
12803 } else if (gameMode == IcsPlayingWhite ||
12804 gameMode == MachinePlaysBlack) {
12807 } else { // white clock
12808 if (gameMode == EditPosition || gameMode == IcsExamining) {
12809 if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
12810 SetWhiteToPlayEvent();
12811 } else if (gameMode == EditGame || shiftKey) {
12812 AdjustClock(which, -1);
12813 } else if (gameMode == IcsPlayingBlack ||
12814 gameMode == MachinePlaysWhite) {
12823 /* Offer draw or accept pending draw offer from opponent */
12825 if (appData.icsActive) {
12826 /* Note: tournament rules require draw offers to be
12827 made after you make your move but before you punch
12828 your clock. Currently ICS doesn't let you do that;
12829 instead, you immediately punch your clock after making
12830 a move, but you can offer a draw at any time. */
12832 SendToICS(ics_prefix);
12833 SendToICS("draw\n");
12834 userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
12835 } else if (cmailMsgLoaded) {
12836 if (currentMove == cmailOldMove &&
12837 commentList[cmailOldMove] != NULL &&
12838 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
12839 "Black offers a draw" : "White offers a draw")) {
12840 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12841 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
12842 } else if (currentMove == cmailOldMove + 1) {
12843 char *offer = WhiteOnMove(cmailOldMove) ?
12844 "White offers a draw" : "Black offers a draw";
12845 AppendComment(currentMove, offer, TRUE);
12846 DisplayComment(currentMove - 1, offer);
12847 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
12849 DisplayError(_("You must make your move before offering a draw"), 0);
12850 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12852 } else if (first.offeredDraw) {
12853 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
12855 if (first.sendDrawOffers) {
12856 SendToProgram("draw\n", &first);
12857 userOfferedDraw = TRUE;
12865 /* Offer Adjourn or accept pending Adjourn offer from opponent */
12867 if (appData.icsActive) {
12868 SendToICS(ics_prefix);
12869 SendToICS("adjourn\n");
12871 /* Currently GNU Chess doesn't offer or accept Adjourns */
12879 /* Offer Abort or accept pending Abort offer from opponent */
12881 if (appData.icsActive) {
12882 SendToICS(ics_prefix);
12883 SendToICS("abort\n");
12885 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
12892 /* Resign. You can do this even if it's not your turn. */
12894 if (appData.icsActive) {
12895 SendToICS(ics_prefix);
12896 SendToICS("resign\n");
12898 switch (gameMode) {
12899 case MachinePlaysWhite:
12900 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12902 case MachinePlaysBlack:
12903 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12906 if (cmailMsgLoaded) {
12908 if (WhiteOnMove(cmailOldMove)) {
12909 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12911 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12913 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
12924 StopObservingEvent()
12926 /* Stop observing current games */
12927 SendToICS(ics_prefix);
12928 SendToICS("unobserve\n");
12932 StopExaminingEvent()
12934 /* Stop observing current game */
12935 SendToICS(ics_prefix);
12936 SendToICS("unexamine\n");
12940 ForwardInner(target)
12945 if (appData.debugMode)
12946 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
12947 target, currentMove, forwardMostMove);
12949 if (gameMode == EditPosition)
12952 if (gameMode == PlayFromGameFile && !pausing)
12955 if (gameMode == IcsExamining && pausing)
12956 limit = pauseExamForwardMostMove;
12958 limit = forwardMostMove;
12960 if (target > limit) target = limit;
12962 if (target > 0 && moveList[target - 1][0]) {
12963 int fromX, fromY, toX, toY;
12964 toX = moveList[target - 1][2] - AAA;
12965 toY = moveList[target - 1][3] - ONE;
12966 if (moveList[target - 1][1] == '@') {
12967 if (appData.highlightLastMove) {
12968 SetHighlights(-1, -1, toX, toY);
12971 fromX = moveList[target - 1][0] - AAA;
12972 fromY = moveList[target - 1][1] - ONE;
12973 if (target == currentMove + 1) {
12974 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
12976 if (appData.highlightLastMove) {
12977 SetHighlights(fromX, fromY, toX, toY);
12981 if (gameMode == EditGame || gameMode == AnalyzeMode ||
12982 gameMode == Training || gameMode == PlayFromGameFile ||
12983 gameMode == AnalyzeFile) {
12984 while (currentMove < target) {
12985 SendMoveToProgram(currentMove++, &first);
12988 currentMove = target;
12991 if (gameMode == EditGame || gameMode == EndOfGame) {
12992 whiteTimeRemaining = timeRemaining[0][currentMove];
12993 blackTimeRemaining = timeRemaining[1][currentMove];
12995 DisplayBothClocks();
12996 DisplayMove(currentMove - 1);
12997 DrawPosition(FALSE, boards[currentMove]);
12998 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
12999 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
13000 DisplayComment(currentMove - 1, commentList[currentMove]);
13008 if (gameMode == IcsExamining && !pausing) {
13009 SendToICS(ics_prefix);
13010 SendToICS("forward\n");
13012 ForwardInner(currentMove + 1);
13019 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13020 /* to optimze, we temporarily turn off analysis mode while we feed
13021 * the remaining moves to the engine. Otherwise we get analysis output
13024 if (first.analysisSupport) {
13025 SendToProgram("exit\nforce\n", &first);
13026 first.analyzing = FALSE;
13030 if (gameMode == IcsExamining && !pausing) {
13031 SendToICS(ics_prefix);
13032 SendToICS("forward 999999\n");
13034 ForwardInner(forwardMostMove);
13037 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13038 /* we have fed all the moves, so reactivate analysis mode */
13039 SendToProgram("analyze\n", &first);
13040 first.analyzing = TRUE;
13041 /*first.maybeThinking = TRUE;*/
13042 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13047 BackwardInner(target)
13050 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
13052 if (appData.debugMode)
13053 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
13054 target, currentMove, forwardMostMove);
13056 if (gameMode == EditPosition) return;
13057 if (currentMove <= backwardMostMove) {
13059 DrawPosition(full_redraw, boards[currentMove]);
13062 if (gameMode == PlayFromGameFile && !pausing)
13065 if (moveList[target][0]) {
13066 int fromX, fromY, toX, toY;
13067 toX = moveList[target][2] - AAA;
13068 toY = moveList[target][3] - ONE;
13069 if (moveList[target][1] == '@') {
13070 if (appData.highlightLastMove) {
13071 SetHighlights(-1, -1, toX, toY);
13074 fromX = moveList[target][0] - AAA;
13075 fromY = moveList[target][1] - ONE;
13076 if (target == currentMove - 1) {
13077 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
13079 if (appData.highlightLastMove) {
13080 SetHighlights(fromX, fromY, toX, toY);
13084 if (gameMode == EditGame || gameMode==AnalyzeMode ||
13085 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
13086 while (currentMove > target) {
13087 SendToProgram("undo\n", &first);
13091 currentMove = target;
13094 if (gameMode == EditGame || gameMode == EndOfGame) {
13095 whiteTimeRemaining = timeRemaining[0][currentMove];
13096 blackTimeRemaining = timeRemaining[1][currentMove];
13098 DisplayBothClocks();
13099 DisplayMove(currentMove - 1);
13100 DrawPosition(full_redraw, boards[currentMove]);
13101 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
13102 // [HGM] PV info: routine tests if comment empty
13103 DisplayComment(currentMove - 1, commentList[currentMove]);
13109 if (gameMode == IcsExamining && !pausing) {
13110 SendToICS(ics_prefix);
13111 SendToICS("backward\n");
13113 BackwardInner(currentMove - 1);
13120 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13121 /* to optimize, we temporarily turn off analysis mode while we undo
13122 * all the moves. Otherwise we get analysis output after each undo.
13124 if (first.analysisSupport) {
13125 SendToProgram("exit\nforce\n", &first);
13126 first.analyzing = FALSE;
13130 if (gameMode == IcsExamining && !pausing) {
13131 SendToICS(ics_prefix);
13132 SendToICS("backward 999999\n");
13134 BackwardInner(backwardMostMove);
13137 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
13138 /* we have fed all the moves, so reactivate analysis mode */
13139 SendToProgram("analyze\n", &first);
13140 first.analyzing = TRUE;
13141 /*first.maybeThinking = TRUE;*/
13142 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13149 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
13150 if (to >= forwardMostMove) to = forwardMostMove;
13151 if (to <= backwardMostMove) to = backwardMostMove;
13152 if (to < currentMove) {
13160 RevertEvent(Boolean annotate)
13162 if(PopTail(annotate)) { // [HGM] vari: restore old game tail
13165 if (gameMode != IcsExamining) {
13166 DisplayError(_("You are not examining a game"), 0);
13170 DisplayError(_("You can't revert while pausing"), 0);
13173 SendToICS(ics_prefix);
13174 SendToICS("revert\n");
13180 switch (gameMode) {
13181 case MachinePlaysWhite:
13182 case MachinePlaysBlack:
13183 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
13184 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
13187 if (forwardMostMove < 2) return;
13188 currentMove = forwardMostMove = forwardMostMove - 2;
13189 whiteTimeRemaining = timeRemaining[0][currentMove];
13190 blackTimeRemaining = timeRemaining[1][currentMove];
13191 DisplayBothClocks();
13192 DisplayMove(currentMove - 1);
13193 ClearHighlights();/*!! could figure this out*/
13194 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
13195 SendToProgram("remove\n", &first);
13196 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
13199 case BeginningOfGame:
13203 case IcsPlayingWhite:
13204 case IcsPlayingBlack:
13205 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
13206 SendToICS(ics_prefix);
13207 SendToICS("takeback 2\n");
13209 SendToICS(ics_prefix);
13210 SendToICS("takeback 1\n");
13219 ChessProgramState *cps;
13221 switch (gameMode) {
13222 case MachinePlaysWhite:
13223 if (!WhiteOnMove(forwardMostMove)) {
13224 DisplayError(_("It is your turn"), 0);
13229 case MachinePlaysBlack:
13230 if (WhiteOnMove(forwardMostMove)) {
13231 DisplayError(_("It is your turn"), 0);
13236 case TwoMachinesPlay:
13237 if (WhiteOnMove(forwardMostMove) ==
13238 (first.twoMachinesColor[0] == 'w')) {
13244 case BeginningOfGame:
13248 SendToProgram("?\n", cps);
13252 TruncateGameEvent()
13255 if (gameMode != EditGame) return;
13262 CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
13263 if (forwardMostMove > currentMove) {
13264 if (gameInfo.resultDetails != NULL) {
13265 free(gameInfo.resultDetails);
13266 gameInfo.resultDetails = NULL;
13267 gameInfo.result = GameUnfinished;
13269 forwardMostMove = currentMove;
13270 HistorySet(parseList, backwardMostMove, forwardMostMove,
13278 if (appData.noChessProgram) return;
13279 switch (gameMode) {
13280 case MachinePlaysWhite:
13281 if (WhiteOnMove(forwardMostMove)) {
13282 DisplayError(_("Wait until your turn"), 0);
13286 case BeginningOfGame:
13287 case MachinePlaysBlack:
13288 if (!WhiteOnMove(forwardMostMove)) {
13289 DisplayError(_("Wait until your turn"), 0);
13294 DisplayError(_("No hint available"), 0);
13297 SendToProgram("hint\n", &first);
13298 hintRequested = TRUE;
13304 if (appData.noChessProgram) return;
13305 switch (gameMode) {
13306 case MachinePlaysWhite:
13307 if (WhiteOnMove(forwardMostMove)) {
13308 DisplayError(_("Wait until your turn"), 0);
13312 case BeginningOfGame:
13313 case MachinePlaysBlack:
13314 if (!WhiteOnMove(forwardMostMove)) {
13315 DisplayError(_("Wait until your turn"), 0);
13320 EditPositionDone(TRUE);
13322 case TwoMachinesPlay:
13327 SendToProgram("bk\n", &first);
13328 bookOutput[0] = NULLCHAR;
13329 bookRequested = TRUE;
13335 char *tags = PGNTags(&gameInfo);
13336 TagsPopUp(tags, CmailMsg());
13340 /* end button procedures */
13343 PrintPosition(fp, move)
13349 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
13350 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
13351 char c = PieceToChar(boards[move][i][j]);
13352 fputc(c == 'x' ? '.' : c, fp);
13353 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
13356 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
13357 fprintf(fp, "white to play\n");
13359 fprintf(fp, "black to play\n");
13366 if (gameInfo.white != NULL) {
13367 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
13373 /* Find last component of program's own name, using some heuristics */
13375 TidyProgramName(prog, host, buf)
13376 char *prog, *host, buf[MSG_SIZ];
13379 int local = (strcmp(host, "localhost") == 0);
13380 while (!local && (p = strchr(prog, ';')) != NULL) {
13382 while (*p == ' ') p++;
13385 if (*prog == '"' || *prog == '\'') {
13386 q = strchr(prog + 1, *prog);
13388 q = strchr(prog, ' ');
13390 if (q == NULL) q = prog + strlen(prog);
13392 while (p >= prog && *p != '/' && *p != '\\') p--;
13394 if(p == prog && *p == '"') p++;
13395 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) q -= 4;
13396 memcpy(buf, p, q - p);
13397 buf[q - p] = NULLCHAR;
13405 TimeControlTagValue()
13408 if (!appData.clockMode) {
13409 safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
13410 } else if (movesPerSession > 0) {
13411 snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
13412 } else if (timeIncrement == 0) {
13413 snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
13415 snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
13417 return StrSave(buf);
13423 /* This routine is used only for certain modes */
13424 VariantClass v = gameInfo.variant;
13425 ChessMove r = GameUnfinished;
13428 if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
13429 r = gameInfo.result;
13430 p = gameInfo.resultDetails;
13431 gameInfo.resultDetails = NULL;
13433 ClearGameInfo(&gameInfo);
13434 gameInfo.variant = v;
13436 switch (gameMode) {
13437 case MachinePlaysWhite:
13438 gameInfo.event = StrSave( appData.pgnEventHeader );
13439 gameInfo.site = StrSave(HostName());
13440 gameInfo.date = PGNDate();
13441 gameInfo.round = StrSave("-");
13442 gameInfo.white = StrSave(first.tidy);
13443 gameInfo.black = StrSave(UserName());
13444 gameInfo.timeControl = TimeControlTagValue();
13447 case MachinePlaysBlack:
13448 gameInfo.event = StrSave( appData.pgnEventHeader );
13449 gameInfo.site = StrSave(HostName());
13450 gameInfo.date = PGNDate();
13451 gameInfo.round = StrSave("-");
13452 gameInfo.white = StrSave(UserName());
13453 gameInfo.black = StrSave(first.tidy);
13454 gameInfo.timeControl = TimeControlTagValue();
13457 case TwoMachinesPlay:
13458 gameInfo.event = StrSave( appData.pgnEventHeader );
13459 gameInfo.site = StrSave(HostName());
13460 gameInfo.date = PGNDate();
13461 if (matchGame > 0) {
13463 snprintf(buf, MSG_SIZ, "%d", matchGame);
13464 gameInfo.round = StrSave(buf);
13466 gameInfo.round = StrSave("-");
13468 if (first.twoMachinesColor[0] == 'w') {
13469 gameInfo.white = StrSave(first.tidy);
13470 gameInfo.black = StrSave(second.tidy);
13472 gameInfo.white = StrSave(second.tidy);
13473 gameInfo.black = StrSave(first.tidy);
13475 gameInfo.timeControl = TimeControlTagValue();
13479 gameInfo.event = StrSave("Edited game");
13480 gameInfo.site = StrSave(HostName());
13481 gameInfo.date = PGNDate();
13482 gameInfo.round = StrSave("-");
13483 gameInfo.white = StrSave("-");
13484 gameInfo.black = StrSave("-");
13485 gameInfo.result = r;
13486 gameInfo.resultDetails = p;
13490 gameInfo.event = StrSave("Edited position");
13491 gameInfo.site = StrSave(HostName());
13492 gameInfo.date = PGNDate();
13493 gameInfo.round = StrSave("-");
13494 gameInfo.white = StrSave("-");
13495 gameInfo.black = StrSave("-");
13498 case IcsPlayingWhite:
13499 case IcsPlayingBlack:
13504 case PlayFromGameFile:
13505 gameInfo.event = StrSave("Game from non-PGN file");
13506 gameInfo.site = StrSave(HostName());
13507 gameInfo.date = PGNDate();
13508 gameInfo.round = StrSave("-");
13509 gameInfo.white = StrSave("?");
13510 gameInfo.black = StrSave("?");
13519 ReplaceComment(index, text)
13527 if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
13528 pvInfoList[index-1].depth == len &&
13529 fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
13530 (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
13531 while (*text == '\n') text++;
13532 len = strlen(text);
13533 while (len > 0 && text[len - 1] == '\n') len--;
13535 if (commentList[index] != NULL)
13536 free(commentList[index]);
13539 commentList[index] = NULL;
13542 if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
13543 *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
13544 *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
13545 commentList[index] = (char *) malloc(len + 2);
13546 strncpy(commentList[index], text, len);
13547 commentList[index][len] = '\n';
13548 commentList[index][len + 1] = NULLCHAR;
13550 // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
13552 commentList[index] = (char *) malloc(len + 7);
13553 safeStrCpy(commentList[index], "{\n", 3);
13554 safeStrCpy(commentList[index]+2, text, len+1);
13555 commentList[index][len+2] = NULLCHAR;
13556 while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
13557 strcat(commentList[index], "\n}\n");
13571 if (ch == '\r') continue;
13573 } while (ch != '\0');
13577 AppendComment(index, text, addBraces)
13580 Boolean addBraces; // [HGM] braces: tells if we should add {}
13585 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces); fflush(debugFP);
13586 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
13589 while (*text == '\n') text++;
13590 len = strlen(text);
13591 while (len > 0 && text[len - 1] == '\n') len--;
13593 if (len == 0) return;
13595 if (commentList[index] != NULL) {
13596 old = commentList[index];
13597 oldlen = strlen(old);
13598 while(commentList[index][oldlen-1] == '\n')
13599 commentList[index][--oldlen] = NULLCHAR;
13600 commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
13601 safeStrCpy(commentList[index], old, oldlen + len + 6);
13603 // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
13604 if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
13605 if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
13606 while (*text == '\n') { text++; len--; }
13607 commentList[index][--oldlen] = NULLCHAR;
13609 if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
13610 else strcat(commentList[index], "\n");
13611 strcat(commentList[index], text);
13612 if(addBraces) strcat(commentList[index], addBraces == 2 ? ")\n" : "\n}\n");
13613 else strcat(commentList[index], "\n");
13615 commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
13617 safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
13618 else commentList[index][0] = NULLCHAR;
13619 strcat(commentList[index], text);
13620 strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
13621 if(addBraces == TRUE) strcat(commentList[index], "}\n");
13625 static char * FindStr( char * text, char * sub_text )
13627 char * result = strstr( text, sub_text );
13629 if( result != NULL ) {
13630 result += strlen( sub_text );
13636 /* [AS] Try to extract PV info from PGN comment */
13637 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
13638 char *GetInfoFromComment( int index, char * text )
13640 char * sep = text, *p;
13642 if( text != NULL && index > 0 ) {
13645 int time = -1, sec = 0, deci;
13646 char * s_eval = FindStr( text, "[%eval " );
13647 char * s_emt = FindStr( text, "[%emt " );
13649 if( s_eval != NULL || s_emt != NULL ) {
13653 if( s_eval != NULL ) {
13654 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
13658 if( delim != ']' ) {
13663 if( s_emt != NULL ) {
13668 /* We expect something like: [+|-]nnn.nn/dd */
13671 if(*text != '{') return text; // [HGM] braces: must be normal comment
13673 sep = strchr( text, '/' );
13674 if( sep == NULL || sep < (text+4) ) {
13679 if(p[1] == '(') { // comment starts with PV
13680 p = strchr(p, ')'); // locate end of PV
13681 if(p == NULL || sep < p+5) return text;
13682 // at this point we have something like "{(.*) +0.23/6 ..."
13683 p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
13684 *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
13685 // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
13687 time = -1; sec = -1; deci = -1;
13688 if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
13689 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
13690 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
13691 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
13695 if( score_lo < 0 || score_lo >= 100 ) {
13699 if(sec >= 0) time = 600*time + 10*sec; else
13700 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
13702 score = score >= 0 ? score*100 + score_lo : score*100 - score_lo;
13704 /* [HGM] PV time: now locate end of PV info */
13705 while( *++sep >= '0' && *sep <= '9'); // strip depth
13707 while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
13709 while( *++sep >= '0' && *sep <= '9'); // strip seconds
13711 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
13712 while(*sep == ' ') sep++;
13723 pvInfoList[index-1].depth = depth;
13724 pvInfoList[index-1].score = score;
13725 pvInfoList[index-1].time = 10*time; // centi-sec
13726 if(*sep == '}') *sep = 0; else *--sep = '{';
13727 if(p != text) { while(*p++ = *sep++); sep = text; } // squeeze out space between PV and comment, and return both
13733 SendToProgram(message, cps)
13735 ChessProgramState *cps;
13737 int count, outCount, error;
13740 if (cps->pr == NULL) return;
13743 if (appData.debugMode) {
13746 fprintf(debugFP, "%ld >%-6s: %s",
13747 SubtractTimeMarks(&now, &programStartTime),
13748 cps->which, message);
13751 count = strlen(message);
13752 outCount = OutputToProcess(cps->pr, message, count, &error);
13753 if (outCount < count && !exiting
13754 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
13755 snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
13756 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
13757 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
13758 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
13759 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
13761 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
13763 gameInfo.resultDetails = StrSave(buf);
13765 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
13770 ReceiveFromProgram(isr, closure, message, count, error)
13771 InputSourceRef isr;
13779 ChessProgramState *cps = (ChessProgramState *)closure;
13781 if (isr != cps->isr) return; /* Killed intentionally */
13784 snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
13785 _(cps->which), cps->program);
13786 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
13787 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
13788 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
13789 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
13791 gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
13793 gameInfo.resultDetails = StrSave(buf);
13795 RemoveInputSource(cps->isr);
13796 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
13798 snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
13799 _(cps->which), cps->program);
13800 RemoveInputSource(cps->isr);
13802 /* [AS] Program is misbehaving badly... kill it */
13803 if( count == -2 ) {
13804 DestroyChildProcess( cps->pr, 9 );
13808 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
13813 if ((end_str = strchr(message, '\r')) != NULL)
13814 *end_str = NULLCHAR;
13815 if ((end_str = strchr(message, '\n')) != NULL)
13816 *end_str = NULLCHAR;
13818 if (appData.debugMode) {
13819 TimeMark now; int print = 1;
13820 char *quote = ""; char c; int i;
13822 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
13823 char start = message[0];
13824 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
13825 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
13826 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
13827 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
13828 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
13829 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
13830 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
13831 sscanf(message, "setboard %c", &c)!=1 && sscanf(message, "setup %c", &c)!=1 &&
13832 sscanf(message, "hint: %c", &c)!=1 &&
13833 sscanf(message, "pong %c", &c)!=1 && start != '#') {
13834 quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
13835 print = (appData.engineComments >= 2);
13837 message[0] = start; // restore original message
13841 fprintf(debugFP, "%ld <%-6s: %s%s\n",
13842 SubtractTimeMarks(&now, &programStartTime), cps->which,
13848 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
13849 if (appData.icsEngineAnalyze) {
13850 if (strstr(message, "whisper") != NULL ||
13851 strstr(message, "kibitz") != NULL ||
13852 strstr(message, "tellics") != NULL) return;
13855 HandleMachineMove(message, cps);
13860 SendTimeControl(cps, mps, tc, inc, sd, st)
13861 ChessProgramState *cps;
13862 int mps, inc, sd, st;
13868 if( timeControl_2 > 0 ) {
13869 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
13870 tc = timeControl_2;
13873 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
13874 inc /= cps->timeOdds;
13875 st /= cps->timeOdds;
13877 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
13880 /* Set exact time per move, normally using st command */
13881 if (cps->stKludge) {
13882 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
13884 if (seconds == 0) {
13885 snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
13887 snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
13890 snprintf(buf, MSG_SIZ, "st %d\n", st);
13893 /* Set conventional or incremental time control, using level command */
13894 if (seconds == 0) {
13895 /* Note old gnuchess bug -- minutes:seconds used to not work.
13896 Fixed in later versions, but still avoid :seconds
13897 when seconds is 0. */
13898 snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
13900 snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
13901 seconds, inc/1000.);
13904 SendToProgram(buf, cps);
13906 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
13907 /* Orthogonally, limit search to given depth */
13909 if (cps->sdKludge) {
13910 snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
13912 snprintf(buf, MSG_SIZ, "sd %d\n", sd);
13914 SendToProgram(buf, cps);
13917 if(cps->nps >= 0) { /* [HGM] nps */
13918 if(cps->supportsNPS == FALSE)
13919 cps->nps = -1; // don't use if engine explicitly says not supported!
13921 snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
13922 SendToProgram(buf, cps);
13927 ChessProgramState *WhitePlayer()
13928 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
13930 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
13931 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
13937 SendTimeRemaining(cps, machineWhite)
13938 ChessProgramState *cps;
13939 int /*boolean*/ machineWhite;
13941 char message[MSG_SIZ];
13944 /* Note: this routine must be called when the clocks are stopped
13945 or when they have *just* been set or switched; otherwise
13946 it will be off by the time since the current tick started.
13948 if (machineWhite) {
13949 time = whiteTimeRemaining / 10;
13950 otime = blackTimeRemaining / 10;
13952 time = blackTimeRemaining / 10;
13953 otime = whiteTimeRemaining / 10;
13955 /* [HGM] translate opponent's time by time-odds factor */
13956 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
13957 if (appData.debugMode) {
13958 fprintf(debugFP, "time odds: %f %f \n", cps->timeOdds, cps->other->timeOdds);
13961 if (time <= 0) time = 1;
13962 if (otime <= 0) otime = 1;
13964 snprintf(message, MSG_SIZ, "time %ld\n", time);
13965 SendToProgram(message, cps);
13967 snprintf(message, MSG_SIZ, "otim %ld\n", otime);
13968 SendToProgram(message, cps);
13972 BoolFeature(p, name, loc, cps)
13976 ChessProgramState *cps;
13979 int len = strlen(name);
13982 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
13984 sscanf(*p, "%d", &val);
13986 while (**p && **p != ' ')
13988 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
13989 SendToProgram(buf, cps);
13996 IntFeature(p, name, loc, cps)
14000 ChessProgramState *cps;
14003 int len = strlen(name);
14004 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
14006 sscanf(*p, "%d", loc);
14007 while (**p && **p != ' ') (*p)++;
14008 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
14009 SendToProgram(buf, cps);
14016 StringFeature(p, name, loc, cps)
14020 ChessProgramState *cps;
14023 int len = strlen(name);
14024 if (strncmp((*p), name, len) == 0
14025 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
14027 sscanf(*p, "%[^\"]", loc);
14028 while (**p && **p != '\"') (*p)++;
14029 if (**p == '\"') (*p)++;
14030 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
14031 SendToProgram(buf, cps);
14038 ParseOption(Option *opt, ChessProgramState *cps)
14039 // [HGM] options: process the string that defines an engine option, and determine
14040 // name, type, default value, and allowed value range
14042 char *p, *q, buf[MSG_SIZ];
14043 int n, min = (-1)<<31, max = 1<<31, def;
14045 if(p = strstr(opt->name, " -spin ")) {
14046 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
14047 if(max < min) max = min; // enforce consistency
14048 if(def < min) def = min;
14049 if(def > max) def = max;
14054 } else if((p = strstr(opt->name, " -slider "))) {
14055 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
14056 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
14057 if(max < min) max = min; // enforce consistency
14058 if(def < min) def = min;
14059 if(def > max) def = max;
14063 opt->type = Spin; // Slider;
14064 } else if((p = strstr(opt->name, " -string "))) {
14065 opt->textValue = p+9;
14066 opt->type = TextBox;
14067 } else if((p = strstr(opt->name, " -file "))) {
14068 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
14069 opt->textValue = p+7;
14070 opt->type = FileName; // FileName;
14071 } else if((p = strstr(opt->name, " -path "))) {
14072 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
14073 opt->textValue = p+7;
14074 opt->type = PathName; // PathName;
14075 } else if(p = strstr(opt->name, " -check ")) {
14076 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
14077 opt->value = (def != 0);
14078 opt->type = CheckBox;
14079 } else if(p = strstr(opt->name, " -combo ")) {
14080 opt->textValue = (char*) (&cps->comboList[cps->comboCnt]); // cheat with pointer type
14081 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
14082 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
14083 opt->value = n = 0;
14084 while(q = StrStr(q, " /// ")) {
14085 n++; *q = 0; // count choices, and null-terminate each of them
14087 if(*q == '*') { // remember default, which is marked with * prefix
14091 cps->comboList[cps->comboCnt++] = q;
14093 cps->comboList[cps->comboCnt++] = NULL;
14095 opt->type = ComboBox;
14096 } else if(p = strstr(opt->name, " -button")) {
14097 opt->type = Button;
14098 } else if(p = strstr(opt->name, " -save")) {
14099 opt->type = SaveButton;
14100 } else return FALSE;
14101 *p = 0; // terminate option name
14102 // now look if the command-line options define a setting for this engine option.
14103 if(cps->optionSettings && cps->optionSettings[0])
14104 p = strstr(cps->optionSettings, opt->name); else p = NULL;
14105 if(p && (p == cps->optionSettings || p[-1] == ',')) {
14106 snprintf(buf, MSG_SIZ, "option %s", p);
14107 if(p = strstr(buf, ",")) *p = 0;
14108 if(q = strchr(buf, '=')) switch(opt->type) {
14110 for(n=0; n<opt->max; n++)
14111 if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
14114 safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
14118 opt->value = atoi(q+1);
14123 SendToProgram(buf, cps);
14129 FeatureDone(cps, val)
14130 ChessProgramState* cps;
14133 DelayedEventCallback cb = GetDelayedEvent();
14134 if ((cb == InitBackEnd3 && cps == &first) ||
14135 (cb == SettingsMenuIfReady && cps == &second) ||
14136 (cb == TwoMachinesEventIfReady && cps == &second)) {
14137 CancelDelayedEvent();
14138 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
14140 cps->initDone = val;
14143 /* Parse feature command from engine */
14145 ParseFeatures(args, cps)
14147 ChessProgramState *cps;
14155 while (*p == ' ') p++;
14156 if (*p == NULLCHAR) return;
14158 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
14159 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
14160 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
14161 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
14162 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
14163 if (BoolFeature(&p, "reuse", &val, cps)) {
14164 /* Engine can disable reuse, but can't enable it if user said no */
14165 if (!val) cps->reuse = FALSE;
14168 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
14169 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
14170 if (gameMode == TwoMachinesPlay) {
14171 DisplayTwoMachinesTitle();
14177 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
14178 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
14179 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
14180 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
14181 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
14182 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
14183 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
14184 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
14185 if (BoolFeature(&p, "pause", &val, cps)) continue; /* unused at present */
14186 if (IntFeature(&p, "done", &val, cps)) {
14187 FeatureDone(cps, val);
14190 /* Added by Tord: */
14191 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
14192 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
14193 /* End of additions by Tord */
14195 /* [HGM] added features: */
14196 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
14197 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
14198 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
14199 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
14200 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
14201 if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
14202 if (StringFeature(&p, "option", &(cps->option[cps->nrOptions].name), cps)) {
14203 if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
14204 snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
14205 SendToProgram(buf, cps);
14208 if(cps->nrOptions >= MAX_OPTIONS) {
14210 snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
14211 DisplayError(buf, 0);
14215 /* End of additions by HGM */
14217 /* unknown feature: complain and skip */
14219 while (*q && *q != '=') q++;
14220 snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
14221 SendToProgram(buf, cps);
14227 while (*p && *p != '\"') p++;
14228 if (*p == '\"') p++;
14230 while (*p && *p != ' ') p++;
14238 PeriodicUpdatesEvent(newState)
14241 if (newState == appData.periodicUpdates)
14244 appData.periodicUpdates=newState;
14246 /* Display type changes, so update it now */
14247 // DisplayAnalysis();
14249 /* Get the ball rolling again... */
14251 AnalysisPeriodicEvent(1);
14252 StartAnalysisClock();
14257 PonderNextMoveEvent(newState)
14260 if (newState == appData.ponderNextMove) return;
14261 if (gameMode == EditPosition) EditPositionDone(TRUE);
14263 SendToProgram("hard\n", &first);
14264 if (gameMode == TwoMachinesPlay) {
14265 SendToProgram("hard\n", &second);
14268 SendToProgram("easy\n", &first);
14269 thinkOutput[0] = NULLCHAR;
14270 if (gameMode == TwoMachinesPlay) {
14271 SendToProgram("easy\n", &second);
14274 appData.ponderNextMove = newState;
14278 NewSettingEvent(option, feature, command, value)
14280 int option, value, *feature;
14284 if (gameMode == EditPosition) EditPositionDone(TRUE);
14285 snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
14286 if(feature == NULL || *feature) SendToProgram(buf, &first);
14287 if (gameMode == TwoMachinesPlay) {
14288 if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
14293 ShowThinkingEvent()
14294 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
14296 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
14297 int newState = appData.showThinking
14298 // [HGM] thinking: other features now need thinking output as well
14299 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
14301 if (oldState == newState) return;
14302 oldState = newState;
14303 if (gameMode == EditPosition) EditPositionDone(TRUE);
14305 SendToProgram("post\n", &first);
14306 if (gameMode == TwoMachinesPlay) {
14307 SendToProgram("post\n", &second);
14310 SendToProgram("nopost\n", &first);
14311 thinkOutput[0] = NULLCHAR;
14312 if (gameMode == TwoMachinesPlay) {
14313 SendToProgram("nopost\n", &second);
14316 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
14320 AskQuestionEvent(title, question, replyPrefix, which)
14321 char *title; char *question; char *replyPrefix; char *which;
14323 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
14324 if (pr == NoProc) return;
14325 AskQuestion(title, question, replyPrefix, pr);
14329 TypeInEvent(char firstChar)
14331 if ((gameMode == BeginningOfGame && !appData.icsActive) ||
\r
14332 gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
\r
14333 gameMode == AnalyzeMode || gameMode == EditGame ||
\r
14334 gameMode == EditPosition || gameMode == IcsExamining ||
\r
14335 gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
\r
14336 isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
\r
14337 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
\r
14338 gameMode == IcsObserving || gameMode == TwoMachinesPlay ) ||
\r
14339 gameMode == Training) PopUpMoveDialog(firstChar);
14343 TypeInDoneEvent(char *move)
14346 int n, fromX, fromY, toX, toY;
14348 ChessMove moveType;
\r
14351 if(gameMode == EditPosition && ParseFEN(board, &n, move) ) {
\r
14352 EditPositionPasteFEN(move);
\r
14355 // [HGM] movenum: allow move number to be typed in any mode
\r
14356 if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
\r
14357 ToNrEvent(2*n-1);
\r
14361 if (gameMode != EditGame && currentMove != forwardMostMove &&
\r
14362 gameMode != Training) {
\r
14363 DisplayMoveError(_("Displayed move is not current"));
\r
14365 int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
\r
14366 &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
\r
14367 if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
\r
14368 if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
\r
14369 &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
\r
14370 UserMoveEvent(fromX, fromY, toX, toY, promoChar);
\r
14372 DisplayMoveError(_("Could not parse move"));
\r
14378 DisplayMove(moveNumber)
14381 char message[MSG_SIZ];
14383 char cpThinkOutput[MSG_SIZ];
14385 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
14387 if (moveNumber == forwardMostMove - 1 ||
14388 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14390 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
14392 if (strchr(cpThinkOutput, '\n')) {
14393 *strchr(cpThinkOutput, '\n') = NULLCHAR;
14396 *cpThinkOutput = NULLCHAR;
14399 /* [AS] Hide thinking from human user */
14400 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
14401 *cpThinkOutput = NULLCHAR;
14402 if( thinkOutput[0] != NULLCHAR ) {
14405 for( i=0; i<=hiddenThinkOutputState; i++ ) {
14406 cpThinkOutput[i] = '.';
14408 cpThinkOutput[i] = NULLCHAR;
14409 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
14413 if (moveNumber == forwardMostMove - 1 &&
14414 gameInfo.resultDetails != NULL) {
14415 if (gameInfo.resultDetails[0] == NULLCHAR) {
14416 snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
14418 snprintf(res, MSG_SIZ, " {%s} %s",
14419 T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
14425 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
14426 DisplayMessage(res, cpThinkOutput);
14428 snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
14429 WhiteOnMove(moveNumber) ? " " : ".. ",
14430 parseList[moveNumber], res);
14431 DisplayMessage(message, cpThinkOutput);
14436 DisplayComment(moveNumber, text)
14440 char title[MSG_SIZ];
14441 char buf[8000]; // comment can be long!
14444 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
14445 safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
14447 snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
14448 WhiteOnMove(moveNumber) ? " " : ".. ",
14449 parseList[moveNumber]);
14451 // [HGM] PV info: display PV info together with (or as) comment
14452 if(moveNumber >= 0 && (depth = pvInfoList[moveNumber].depth) > 0) {
14453 if(text == NULL) text = "";
14454 score = pvInfoList[moveNumber].score;
14455 snprintf(buf,sizeof(buf)/sizeof(buf[0]), "%s%.2f/%d %d\n%s", score>0 ? "+" : "", score/100.,
14456 depth, (pvInfoList[moveNumber].time+50)/100, text);
14459 if (text != NULL && (appData.autoDisplayComment || commentUp))
14460 CommentPopUp(title, text);
14463 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
14464 * might be busy thinking or pondering. It can be omitted if your
14465 * gnuchess is configured to stop thinking immediately on any user
14466 * input. However, that gnuchess feature depends on the FIONREAD
14467 * ioctl, which does not work properly on some flavors of Unix.
14471 ChessProgramState *cps;
14474 if (!cps->useSigint) return;
14475 if (appData.noChessProgram || (cps->pr == NoProc)) return;
14476 switch (gameMode) {
14477 case MachinePlaysWhite:
14478 case MachinePlaysBlack:
14479 case TwoMachinesPlay:
14480 case IcsPlayingWhite:
14481 case IcsPlayingBlack:
14484 /* Skip if we know it isn't thinking */
14485 if (!cps->maybeThinking) return;
14486 if (appData.debugMode)
14487 fprintf(debugFP, "Interrupting %s\n", cps->which);
14488 InterruptChildProcess(cps->pr);
14489 cps->maybeThinking = FALSE;
14494 #endif /*ATTENTION*/
14500 if (whiteTimeRemaining <= 0) {
14503 if (appData.icsActive) {
14504 if (appData.autoCallFlag &&
14505 gameMode == IcsPlayingBlack && !blackFlag) {
14506 SendToICS(ics_prefix);
14507 SendToICS("flag\n");
14511 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
14513 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
14514 if (appData.autoCallFlag) {
14515 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
14522 if (blackTimeRemaining <= 0) {
14525 if (appData.icsActive) {
14526 if (appData.autoCallFlag &&
14527 gameMode == IcsPlayingWhite && !whiteFlag) {
14528 SendToICS(ics_prefix);
14529 SendToICS("flag\n");
14533 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
14535 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
14536 if (appData.autoCallFlag) {
14537 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
14550 if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
14551 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
14554 * add time to clocks when time control is achieved ([HGM] now also used for increment)
14556 if ( !WhiteOnMove(forwardMostMove) ) {
14557 /* White made time control */
14558 lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
14559 whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
14560 /* [HGM] time odds: correct new time quota for time odds! */
14561 / WhitePlayer()->timeOdds;
14562 lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
14564 lastBlack -= blackTimeRemaining;
14565 /* Black made time control */
14566 blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
14567 / WhitePlayer()->other->timeOdds;
14568 lastWhite = whiteTimeRemaining;
14573 DisplayBothClocks()
14575 int wom = gameMode == EditPosition ?
14576 !blackPlaysFirst : WhiteOnMove(currentMove);
14577 DisplayWhiteClock(whiteTimeRemaining, wom);
14578 DisplayBlackClock(blackTimeRemaining, !wom);
14582 /* Timekeeping seems to be a portability nightmare. I think everyone
14583 has ftime(), but I'm really not sure, so I'm including some ifdefs
14584 to use other calls if you don't. Clocks will be less accurate if
14585 you have neither ftime nor gettimeofday.
14588 /* VS 2008 requires the #include outside of the function */
14589 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
14590 #include <sys/timeb.h>
14593 /* Get the current time as a TimeMark */
14598 #if HAVE_GETTIMEOFDAY
14600 struct timeval timeVal;
14601 struct timezone timeZone;
14603 gettimeofday(&timeVal, &timeZone);
14604 tm->sec = (long) timeVal.tv_sec;
14605 tm->ms = (int) (timeVal.tv_usec / 1000L);
14607 #else /*!HAVE_GETTIMEOFDAY*/
14610 // include <sys/timeb.h> / moved to just above start of function
14611 struct timeb timeB;
14614 tm->sec = (long) timeB.time;
14615 tm->ms = (int) timeB.millitm;
14617 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
14618 tm->sec = (long) time(NULL);
14624 /* Return the difference in milliseconds between two
14625 time marks. We assume the difference will fit in a long!
14628 SubtractTimeMarks(tm2, tm1)
14629 TimeMark *tm2, *tm1;
14631 return 1000L*(tm2->sec - tm1->sec) +
14632 (long) (tm2->ms - tm1->ms);
14637 * Code to manage the game clocks.
14639 * In tournament play, black starts the clock and then white makes a move.
14640 * We give the human user a slight advantage if he is playing white---the
14641 * clocks don't run until he makes his first move, so it takes zero time.
14642 * Also, we don't account for network lag, so we could get out of sync
14643 * with GNU Chess's clock -- but then, referees are always right.
14646 static TimeMark tickStartTM;
14647 static long intendedTickLength;
14650 NextTickLength(timeRemaining)
14651 long timeRemaining;
14653 long nominalTickLength, nextTickLength;
14655 if (timeRemaining > 0L && timeRemaining <= 10000L)
14656 nominalTickLength = 100L;
14658 nominalTickLength = 1000L;
14659 nextTickLength = timeRemaining % nominalTickLength;
14660 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
14662 return nextTickLength;
14665 /* Adjust clock one minute up or down */
14667 AdjustClock(Boolean which, int dir)
14669 if(which) blackTimeRemaining += 60000*dir;
14670 else whiteTimeRemaining += 60000*dir;
14671 DisplayBothClocks();
14674 /* Stop clocks and reset to a fresh time control */
14678 (void) StopClockTimer();
14679 if (appData.icsActive) {
14680 whiteTimeRemaining = blackTimeRemaining = 0;
14681 } else if (searchTime) {
14682 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
14683 blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
14684 } else { /* [HGM] correct new time quote for time odds */
14685 whiteTC = blackTC = fullTimeControlString;
14686 whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
14687 blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
14689 if (whiteFlag || blackFlag) {
14691 whiteFlag = blackFlag = FALSE;
14693 lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
14694 DisplayBothClocks();
14697 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
14699 /* Decrement running clock by amount of time that has passed */
14703 long timeRemaining;
14704 long lastTickLength, fudge;
14707 if (!appData.clockMode) return;
14708 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
14712 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14714 /* Fudge if we woke up a little too soon */
14715 fudge = intendedTickLength - lastTickLength;
14716 if (fudge < 0 || fudge > FUDGE) fudge = 0;
14718 if (WhiteOnMove(forwardMostMove)) {
14719 if(whiteNPS >= 0) lastTickLength = 0;
14720 timeRemaining = whiteTimeRemaining -= lastTickLength;
14721 if(timeRemaining < 0 && !appData.icsActive) {
14722 GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
14723 if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
14724 whiteStartMove = forwardMostMove; whiteTC = nextSession;
14725 lastWhite= timeRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
14728 DisplayWhiteClock(whiteTimeRemaining - fudge,
14729 WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
14731 if(blackNPS >= 0) lastTickLength = 0;
14732 timeRemaining = blackTimeRemaining -= lastTickLength;
14733 if(timeRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
14734 GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
14736 blackStartMove = forwardMostMove;
14737 lastBlack = timeRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
14740 DisplayBlackClock(blackTimeRemaining - fudge,
14741 !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
14743 if (CheckFlags()) return;
14746 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
14747 StartClockTimer(intendedTickLength);
14749 /* if the time remaining has fallen below the alarm threshold, sound the
14750 * alarm. if the alarm has sounded and (due to a takeback or time control
14751 * with increment) the time remaining has increased to a level above the
14752 * threshold, reset the alarm so it can sound again.
14755 if (appData.icsActive && appData.icsAlarm) {
14757 /* make sure we are dealing with the user's clock */
14758 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
14759 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
14762 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
14763 alarmSounded = FALSE;
14764 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
14766 alarmSounded = TRUE;
14772 /* A player has just moved, so stop the previously running
14773 clock and (if in clock mode) start the other one.
14774 We redisplay both clocks in case we're in ICS mode, because
14775 ICS gives us an update to both clocks after every move.
14776 Note that this routine is called *after* forwardMostMove
14777 is updated, so the last fractional tick must be subtracted
14778 from the color that is *not* on move now.
14781 SwitchClocks(int newMoveNr)
14783 long lastTickLength;
14785 int flagged = FALSE;
14789 if (StopClockTimer() && appData.clockMode) {
14790 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14791 if (!WhiteOnMove(forwardMostMove)) {
14792 if(blackNPS >= 0) lastTickLength = 0;
14793 blackTimeRemaining -= lastTickLength;
14794 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
14795 // if(pvInfoList[forwardMostMove].time == -1)
14796 pvInfoList[forwardMostMove].time = // use GUI time
14797 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
14799 if(whiteNPS >= 0) lastTickLength = 0;
14800 whiteTimeRemaining -= lastTickLength;
14801 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
14802 // if(pvInfoList[forwardMostMove].time == -1)
14803 pvInfoList[forwardMostMove].time =
14804 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
14806 flagged = CheckFlags();
14808 forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
14809 CheckTimeControl();
14811 if (flagged || !appData.clockMode) return;
14813 switch (gameMode) {
14814 case MachinePlaysBlack:
14815 case MachinePlaysWhite:
14816 case BeginningOfGame:
14817 if (pausing) return;
14821 case PlayFromGameFile:
14829 if (searchTime) { // [HGM] st: set clock of player that has to move to max time
14830 if(WhiteOnMove(forwardMostMove))
14831 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
14832 else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
14836 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
14837 whiteTimeRemaining : blackTimeRemaining);
14838 StartClockTimer(intendedTickLength);
14842 /* Stop both clocks */
14846 long lastTickLength;
14849 if (!StopClockTimer()) return;
14850 if (!appData.clockMode) return;
14854 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
14855 if (WhiteOnMove(forwardMostMove)) {
14856 if(whiteNPS >= 0) lastTickLength = 0;
14857 whiteTimeRemaining -= lastTickLength;
14858 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
14860 if(blackNPS >= 0) lastTickLength = 0;
14861 blackTimeRemaining -= lastTickLength;
14862 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
14867 /* Start clock of player on move. Time may have been reset, so
14868 if clock is already running, stop and restart it. */
14872 (void) StopClockTimer(); /* in case it was running already */
14873 DisplayBothClocks();
14874 if (CheckFlags()) return;
14876 if (!appData.clockMode) return;
14877 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
14879 GetTimeMark(&tickStartTM);
14880 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
14881 whiteTimeRemaining : blackTimeRemaining);
14883 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
14884 whiteNPS = blackNPS = -1;
14885 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
14886 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
14887 whiteNPS = first.nps;
14888 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
14889 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
14890 blackNPS = first.nps;
14891 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
14892 whiteNPS = second.nps;
14893 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
14894 blackNPS = second.nps;
14895 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
14897 StartClockTimer(intendedTickLength);
14904 long second, minute, hour, day;
14906 static char buf[32];
14908 if (ms > 0 && ms <= 9900) {
14909 /* convert milliseconds to tenths, rounding up */
14910 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
14912 snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
14916 /* convert milliseconds to seconds, rounding up */
14917 /* use floating point to avoid strangeness of integer division
14918 with negative dividends on many machines */
14919 second = (long) floor(((double) (ms + 999L)) / 1000.0);
14926 day = second / (60 * 60 * 24);
14927 second = second % (60 * 60 * 24);
14928 hour = second / (60 * 60);
14929 second = second % (60 * 60);
14930 minute = second / 60;
14931 second = second % 60;
14934 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ",
14935 sign, day, hour, minute, second);
14937 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
14939 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second);
14946 * This is necessary because some C libraries aren't ANSI C compliant yet.
14949 StrStr(string, match)
14950 char *string, *match;
14954 length = strlen(match);
14956 for (i = strlen(string) - length; i >= 0; i--, string++)
14957 if (!strncmp(match, string, length))
14964 StrCaseStr(string, match)
14965 char *string, *match;
14969 length = strlen(match);
14971 for (i = strlen(string) - length; i >= 0; i--, string++) {
14972 for (j = 0; j < length; j++) {
14973 if (ToLower(match[j]) != ToLower(string[j]))
14976 if (j == length) return string;
14990 c1 = ToLower(*s1++);
14991 c2 = ToLower(*s2++);
14992 if (c1 > c2) return 1;
14993 if (c1 < c2) return -1;
14994 if (c1 == NULLCHAR) return 0;
15003 return isupper(c) ? tolower(c) : c;
15011 return islower(c) ? toupper(c) : c;
15013 #endif /* !_amigados */
15021 if ((ret = (char *) malloc(strlen(s) + 1)))
15023 safeStrCpy(ret, s, strlen(s)+1);
15029 StrSavePtr(s, savePtr)
15030 char *s, **savePtr;
15035 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
15036 safeStrCpy(*savePtr, s, strlen(s)+1);
15048 clock = time((time_t *)NULL);
15049 tm = localtime(&clock);
15050 snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
15051 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
15052 return StrSave(buf);
15057 PositionToFEN(move, overrideCastling)
15059 char *overrideCastling;
15061 int i, j, fromX, fromY, toX, toY;
15068 whiteToPlay = (gameMode == EditPosition) ?
15069 !blackPlaysFirst : (move % 2 == 0);
15072 /* Piece placement data */
15073 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
15075 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
15076 if (boards[move][i][j] == EmptySquare) {
15078 } else { ChessSquare piece = boards[move][i][j];
15079 if (emptycount > 0) {
15080 if(emptycount<10) /* [HGM] can be >= 10 */
15081 *p++ = '0' + emptycount;
15082 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
15085 if(PieceToChar(piece) == '+') {
15086 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
15088 piece = (ChessSquare)(DEMOTED piece);
15090 *p++ = PieceToChar(piece);
15092 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
15093 p[-1] = PieceToChar((ChessSquare)(DEMOTED piece));
15098 if (emptycount > 0) {
15099 if(emptycount<10) /* [HGM] can be >= 10 */
15100 *p++ = '0' + emptycount;
15101 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
15108 /* [HGM] print Crazyhouse or Shogi holdings */
15109 if( gameInfo.holdingsWidth ) {
15110 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
15112 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
15113 piece = boards[move][i][BOARD_WIDTH-1];
15114 if( piece != EmptySquare )
15115 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
15116 *p++ = PieceToChar(piece);
15118 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
15119 piece = boards[move][BOARD_HEIGHT-i-1][0];
15120 if( piece != EmptySquare )
15121 for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
15122 *p++ = PieceToChar(piece);
15125 if( q == p ) *p++ = '-';
15131 *p++ = whiteToPlay ? 'w' : 'b';
15134 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
15135 while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' '; else --p;
15137 if(nrCastlingRights) {
15139 if(gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) {
15140 /* [HGM] write directly from rights */
15141 if(boards[move][CASTLING][2] != NoRights &&
15142 boards[move][CASTLING][0] != NoRights )
15143 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
15144 if(boards[move][CASTLING][2] != NoRights &&
15145 boards[move][CASTLING][1] != NoRights )
15146 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
15147 if(boards[move][CASTLING][5] != NoRights &&
15148 boards[move][CASTLING][3] != NoRights )
15149 *p++ = boards[move][CASTLING][3] + AAA;
15150 if(boards[move][CASTLING][5] != NoRights &&
15151 boards[move][CASTLING][4] != NoRights )
15152 *p++ = boards[move][CASTLING][4] + AAA;
15155 /* [HGM] write true castling rights */
15156 if( nrCastlingRights == 6 ) {
15157 if(boards[move][CASTLING][0] == BOARD_RGHT-1 &&
15158 boards[move][CASTLING][2] != NoRights ) *p++ = 'K';
15159 if(boards[move][CASTLING][1] == BOARD_LEFT &&
15160 boards[move][CASTLING][2] != NoRights ) *p++ = 'Q';
15161 if(boards[move][CASTLING][3] == BOARD_RGHT-1 &&
15162 boards[move][CASTLING][5] != NoRights ) *p++ = 'k';
15163 if(boards[move][CASTLING][4] == BOARD_LEFT &&
15164 boards[move][CASTLING][5] != NoRights ) *p++ = 'q';
15167 if (q == p) *p++ = '-'; /* No castling rights */
15171 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
15172 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
15173 /* En passant target square */
15174 if (move > backwardMostMove) {
15175 fromX = moveList[move - 1][0] - AAA;
15176 fromY = moveList[move - 1][1] - ONE;
15177 toX = moveList[move - 1][2] - AAA;
15178 toY = moveList[move - 1][3] - ONE;
15179 if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
15180 toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
15181 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
15183 /* 2-square pawn move just happened */
15185 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
15189 } else if(move == backwardMostMove) {
15190 // [HGM] perhaps we should always do it like this, and forget the above?
15191 if((signed char)boards[move][EP_STATUS] >= 0) {
15192 *p++ = boards[move][EP_STATUS] + AAA;
15193 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
15204 /* [HGM] find reversible plies */
15205 { int i = 0, j=move;
15207 if (appData.debugMode) { int k;
15208 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
15209 for(k=backwardMostMove; k<=forwardMostMove; k++)
15210 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
15214 while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
15215 if( j == backwardMostMove ) i += initialRulePlies;
15216 sprintf(p, "%d ", i);
15217 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
15219 /* Fullmove number */
15220 sprintf(p, "%d", (move / 2) + 1);
15222 return StrSave(buf);
15226 ParseFEN(board, blackPlaysFirst, fen)
15228 int *blackPlaysFirst;
15238 /* [HGM] by default clear Crazyhouse holdings, if present */
15239 if(gameInfo.holdingsWidth) {
15240 for(i=0; i<BOARD_HEIGHT; i++) {
15241 board[i][0] = EmptySquare; /* black holdings */
15242 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
15243 board[i][1] = (ChessSquare) 0; /* black counts */
15244 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
15248 /* Piece placement data */
15249 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
15252 if (*p == '/' || *p == ' ' || (*p == '[' && i == 0) ) {
15253 if (*p == '/') p++;
15254 emptycount = gameInfo.boardWidth - j;
15255 while (emptycount--)
15256 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
15258 #if(BOARD_FILES >= 10)
15259 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
15260 p++; emptycount=10;
15261 if (j + emptycount > gameInfo.boardWidth) return FALSE;
15262 while (emptycount--)
15263 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
15265 } else if (isdigit(*p)) {
15266 emptycount = *p++ - '0';
15267 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
15268 if (j + emptycount > gameInfo.boardWidth) return FALSE;
15269 while (emptycount--)
15270 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
15271 } else if (*p == '+' || isalpha(*p)) {
15272 if (j >= gameInfo.boardWidth) return FALSE;
15274 piece = CharToPiece(*++p);
15275 if(piece == EmptySquare) return FALSE; /* unknown piece */
15276 piece = (ChessSquare) (PROMOTED piece ); p++;
15277 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
15278 } else piece = CharToPiece(*p++);
15280 if(piece==EmptySquare) return FALSE; /* unknown piece */
15281 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
15282 piece = (ChessSquare) (PROMOTED piece);
15283 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
15286 board[i][(j++)+gameInfo.holdingsWidth] = piece;
15292 while (*p == '/' || *p == ' ') p++;
15294 /* [HGM] look for Crazyhouse holdings here */
15295 while(*p==' ') p++;
15296 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
15298 if(*p == '-' ) p++; /* empty holdings */ else {
15299 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
15300 /* if we would allow FEN reading to set board size, we would */
15301 /* have to add holdings and shift the board read so far here */
15302 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
15304 if((int) piece >= (int) BlackPawn ) {
15305 i = (int)piece - (int)BlackPawn;
15306 i = PieceToNumber((ChessSquare)i);
15307 if( i >= gameInfo.holdingsSize ) return FALSE;
15308 board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
15309 board[BOARD_HEIGHT-1-i][1]++; /* black counts */
15311 i = (int)piece - (int)WhitePawn;
15312 i = PieceToNumber((ChessSquare)i);
15313 if( i >= gameInfo.holdingsSize ) return FALSE;
15314 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
15315 board[i][BOARD_WIDTH-2]++; /* black holdings */
15322 while(*p == ' ') p++;
15326 if(appData.colorNickNames) {
15327 if( c == appData.colorNickNames[0] ) c = 'w'; else
15328 if( c == appData.colorNickNames[1] ) c = 'b';
15332 *blackPlaysFirst = FALSE;
15335 *blackPlaysFirst = TRUE;
15341 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
15342 /* return the extra info in global variiables */
15344 /* set defaults in case FEN is incomplete */
15345 board[EP_STATUS] = EP_UNKNOWN;
15346 for(i=0; i<nrCastlingRights; i++ ) {
15347 board[CASTLING][i] =
15348 gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom ? NoRights : initialRights[i];
15349 } /* assume possible unless obviously impossible */
15350 if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
15351 if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
15352 if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
15353 && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
15354 if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
15355 if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
15356 if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
15357 && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
15360 while(*p==' ') p++;
15361 if(nrCastlingRights) {
15362 if(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-') {
15363 /* castling indicator present, so default becomes no castlings */
15364 for(i=0; i<nrCastlingRights; i++ ) {
15365 board[CASTLING][i] = NoRights;
15368 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
15369 (gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) &&
15370 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
15371 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
15372 char c = *p++; int whiteKingFile=NoRights, blackKingFile=NoRights;
15374 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
15375 if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
15376 if(board[0 ][i] == WhiteKing) whiteKingFile = i;
15378 if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
15379 whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
15380 if(whiteKingFile == NoRights || board[0][whiteKingFile] != WhiteUnicorn
15381 && board[0][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
15382 if(blackKingFile == NoRights || board[BOARD_HEIGHT-1][blackKingFile] != BlackUnicorn
15383 && board[BOARD_HEIGHT-1][blackKingFile] != BlackKing) blackKingFile = NoRights;
15386 for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
15387 board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
15388 board[CASTLING][2] = whiteKingFile;
15391 for(i=BOARD_LEFT; i<BOARD_RGHT && board[0][i]!=WhiteRook && i<whiteKingFile; i++);
15392 board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
15393 board[CASTLING][2] = whiteKingFile;
15396 for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
15397 board[CASTLING][3] = i != blackKingFile ? i : NoRights;
15398 board[CASTLING][5] = blackKingFile;
15401 for(i=BOARD_LEFT; i<BOARD_RGHT && board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
15402 board[CASTLING][4] = i != blackKingFile ? i : NoRights;
15403 board[CASTLING][5] = blackKingFile;
15406 default: /* FRC castlings */
15407 if(c >= 'a') { /* black rights */
15408 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
15409 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
15410 if(i == BOARD_RGHT) break;
15411 board[CASTLING][5] = i;
15413 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
15414 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
15416 board[CASTLING][3] = c;
15418 board[CASTLING][4] = c;
15419 } else { /* white rights */
15420 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
15421 if(board[0][i] == WhiteKing) break;
15422 if(i == BOARD_RGHT) break;
15423 board[CASTLING][2] = i;
15424 c -= AAA - 'a' + 'A';
15425 if(board[0][c] >= WhiteKing) break;
15427 board[CASTLING][0] = c;
15429 board[CASTLING][1] = c;
15433 for(i=0; i<nrCastlingRights; i++)
15434 if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
15435 if (appData.debugMode) {
15436 fprintf(debugFP, "FEN castling rights:");
15437 for(i=0; i<nrCastlingRights; i++)
15438 fprintf(debugFP, " %d", board[CASTLING][i]);
15439 fprintf(debugFP, "\n");
15442 while(*p==' ') p++;
15445 /* read e.p. field in games that know e.p. capture */
15446 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
15447 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
15449 p++; board[EP_STATUS] = EP_NONE;
15451 char c = *p++ - AAA;
15453 if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
15454 if(*p >= '0' && *p <='9') p++;
15455 board[EP_STATUS] = c;
15460 if(sscanf(p, "%d", &i) == 1) {
15461 FENrulePlies = i; /* 50-move ply counter */
15462 /* (The move number is still ignored) */
15469 EditPositionPasteFEN(char *fen)
15472 Board initial_position;
15474 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
15475 DisplayError(_("Bad FEN position in clipboard"), 0);
15478 int savedBlackPlaysFirst = blackPlaysFirst;
15479 EditPositionEvent();
15480 blackPlaysFirst = savedBlackPlaysFirst;
15481 CopyBoard(boards[0], initial_position);
15482 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
15483 EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
15484 DisplayBothClocks();
15485 DrawPosition(FALSE, boards[currentMove]);
15490 static char cseq[12] = "\\ ";
15492 Boolean set_cont_sequence(char *new_seq)
15497 // handle bad attempts to set the sequence
15499 return 0; // acceptable error - no debug
15501 len = strlen(new_seq);
15502 ret = (len > 0) && (len < sizeof(cseq));
15504 safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
15505 else if (appData.debugMode)
15506 fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
15511 reformat a source message so words don't cross the width boundary. internal
15512 newlines are not removed. returns the wrapped size (no null character unless
15513 included in source message). If dest is NULL, only calculate the size required
15514 for the dest buffer. lp argument indicats line position upon entry, and it's
15515 passed back upon exit.
15517 int wrap(char *dest, char *src, int count, int width, int *lp)
15519 int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
15521 cseq_len = strlen(cseq);
15522 old_line = line = *lp;
15523 ansi = len = clen = 0;
15525 for (i=0; i < count; i++)
15527 if (src[i] == '\033')
15530 // if we hit the width, back up
15531 if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
15533 // store i & len in case the word is too long
15534 old_i = i, old_len = len;
15536 // find the end of the last word
15537 while (i && src[i] != ' ' && src[i] != '\n')
15543 // word too long? restore i & len before splitting it
15544 if ((old_i-i+clen) >= width)
15551 if (i && src[i-1] == ' ')
15554 if (src[i] != ' ' && src[i] != '\n')
15561 // now append the newline and continuation sequence
15566 strncpy(dest+len, cseq, cseq_len);
15574 dest[len] = src[i];
15578 if (src[i] == '\n')
15583 if (dest && appData.debugMode)
15585 fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
15586 count, width, line, len, *lp);
15587 show_bytes(debugFP, src, count);
15588 fprintf(debugFP, "\ndest: ");
15589 show_bytes(debugFP, dest, len);
15590 fprintf(debugFP, "\n");
15592 *lp = dest ? line : old_line;
15597 // [HGM] vari: routines for shelving variations
15600 PushTail(int firstMove, int lastMove)
15602 int i, j, nrMoves = lastMove - firstMove;
15604 if(appData.icsActive) { // only in local mode
15605 forwardMostMove = currentMove; // mimic old ICS behavior
15608 if(storedGames >= MAX_VARIATIONS-1) return;
15610 // push current tail of game on stack
15611 savedResult[storedGames] = gameInfo.result;
15612 savedDetails[storedGames] = gameInfo.resultDetails;
15613 gameInfo.resultDetails = NULL;
15614 savedFirst[storedGames] = firstMove;
15615 savedLast [storedGames] = lastMove;
15616 savedFramePtr[storedGames] = framePtr;
15617 framePtr -= nrMoves; // reserve space for the boards
15618 for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
15619 CopyBoard(boards[framePtr+i], boards[firstMove+i]);
15620 for(j=0; j<MOVE_LEN; j++)
15621 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
15622 for(j=0; j<2*MOVE_LEN; j++)
15623 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
15624 timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
15625 timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
15626 pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
15627 pvInfoList[firstMove+i-1].depth = 0;
15628 commentList[framePtr+i] = commentList[firstMove+i];
15629 commentList[firstMove+i] = NULL;
15633 forwardMostMove = firstMove; // truncate game so we can start variation
15634 if(storedGames == 1) GreyRevert(FALSE);
15638 PopTail(Boolean annotate)
15641 char buf[8000], moveBuf[20];
15643 if(appData.icsActive) return FALSE; // only in local mode
15644 if(!storedGames) return FALSE; // sanity
15645 CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
15648 ToNrEvent(savedFirst[storedGames]); // sets currentMove
15649 nrMoves = savedLast[storedGames] - currentMove;
15652 if(!WhiteOnMove(currentMove))
15653 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
15654 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
15655 for(i=currentMove; i<forwardMostMove; i++) {
15657 snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
15658 else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
15659 strcat(buf, moveBuf);
15660 if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
15661 if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
15665 for(i=1; i<=nrMoves; i++) { // copy last variation back
15666 CopyBoard(boards[currentMove+i], boards[framePtr+i]);
15667 for(j=0; j<MOVE_LEN; j++)
15668 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
15669 for(j=0; j<2*MOVE_LEN; j++)
15670 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
15671 timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
15672 timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
15673 pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
15674 if(commentList[currentMove+i]) free(commentList[currentMove+i]);
15675 commentList[currentMove+i] = commentList[framePtr+i];
15676 commentList[framePtr+i] = NULL;
15678 if(annotate) AppendComment(currentMove+1, buf, FALSE);
15679 framePtr = savedFramePtr[storedGames];
15680 gameInfo.result = savedResult[storedGames];
15681 if(gameInfo.resultDetails != NULL) {
15682 free(gameInfo.resultDetails);
15684 gameInfo.resultDetails = savedDetails[storedGames];
15685 forwardMostMove = currentMove + nrMoves;
15686 if(storedGames == 0) GreyRevert(TRUE);
15692 { // remove all shelved variations
15694 for(i=0; i<storedGames; i++) {
15695 if(savedDetails[i])
15696 free(savedDetails[i]);
15697 savedDetails[i] = NULL;
15699 for(i=framePtr; i<MAX_MOVES; i++) {
15700 if(commentList[i]) free(commentList[i]);
15701 commentList[i] = NULL;
15703 framePtr = MAX_MOVES-1;
15708 LoadVariation(int index, char *text)
15709 { // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
15710 char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
15711 int level = 0, move;
15713 if(gameMode != EditGame && gameMode != AnalyzeMode) return;
15714 // first find outermost bracketing variation
15715 while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
15716 if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
15717 if(*p == '{') wait = '}'; else
15718 if(*p == '[') wait = ']'; else
15719 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
15720 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
15722 if(*p == wait) wait = NULLCHAR; // closing ]} found
15725 if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
15726 if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
15727 end[1] = NULLCHAR; // clip off comment beyond variation
15728 ToNrEvent(currentMove-1);
15729 PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
15730 // kludge: use ParsePV() to append variation to game
15731 move = currentMove;
15732 ParsePV(start, TRUE);
15733 forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
15734 ClearPremoveHighlights();
15736 ToNrEvent(currentMove+1);