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, 2012 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 int flock(int f, int code);
75 #include <sys/types.h>
84 #else /* not STDC_HEADERS */
87 # else /* not HAVE_STRING_H */
89 # endif /* not HAVE_STRING_H */
90 #endif /* not STDC_HEADERS */
93 # include <sys/fcntl.h>
94 #else /* not HAVE_SYS_FCNTL_H */
97 # endif /* HAVE_FCNTL_H */
98 #endif /* not HAVE_SYS_FCNTL_H */
100 #if TIME_WITH_SYS_TIME
101 # include <sys/time.h>
105 # include <sys/time.h>
111 #if defined(_amigados) && !defined(__GNUC__)
116 extern int gettimeofday(struct timeval *, struct timezone *);
124 #include "frontend.h"
131 #include "backendz.h"
135 # define _(s) gettext (s)
136 # define N_(s) gettext_noop (s)
137 # define T_(s) gettext(s)
150 int establish P((void));
151 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
152 char *buf, int count, int error));
153 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
154 char *buf, int count, int error));
155 void SendToICS P((char *s));
156 void SendToICSDelayed P((char *s, long msdelay));
157 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar));
158 void HandleMachineMove P((char *message, ChessProgramState *cps));
159 int AutoPlayOneMove P((void));
160 int LoadGameOneMove P((ChessMove readAhead));
161 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
162 int LoadPositionFromFile P((char *filename, int n, char *title));
163 int SavePositionToFile P((char *filename));
164 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
165 void ShowMove P((int fromX, int fromY, int toX, int toY));
166 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
167 /*char*/int promoChar));
168 void BackwardInner P((int target));
169 void ForwardInner P((int target));
170 int Adjudicate P((ChessProgramState *cps));
171 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
172 void EditPositionDone P((Boolean fakeRights));
173 void PrintOpponents P((FILE *fp));
174 void PrintPosition P((FILE *fp, int move));
175 void StartChessProgram P((ChessProgramState *cps));
176 void SendToProgram P((char *message, ChessProgramState *cps));
177 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
178 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
179 char *buf, int count, int error));
180 void SendTimeControl P((ChessProgramState *cps,
181 int mps, long tc, int inc, int sd, int st));
182 char *TimeControlTagValue P((void));
183 void Attention P((ChessProgramState *cps));
184 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
185 int ResurrectChessProgram P((void));
186 void DisplayComment P((int moveNumber, char *text));
187 void DisplayMove P((int moveNumber));
189 void ParseGameHistory P((char *game));
190 void ParseBoard12 P((char *string));
191 void KeepAlive P((void));
192 void StartClocks P((void));
193 void SwitchClocks P((int nr));
194 void StopClocks P((void));
195 void ResetClocks P((void));
196 char *PGNDate P((void));
197 void SetGameInfo P((void));
198 int RegisterMove P((void));
199 void MakeRegisteredMove P((void));
200 void TruncateGame P((void));
201 int looking_at P((char *, int *, char *));
202 void CopyPlayerNameIntoFileName P((char **, char *));
203 char *SavePart P((char *));
204 int SaveGameOldStyle P((FILE *));
205 int SaveGamePGN P((FILE *));
206 int CheckFlags P((void));
207 long NextTickLength P((long));
208 void CheckTimeControl P((void));
209 void show_bytes P((FILE *, char *, int));
210 int string_to_rating P((char *str));
211 void ParseFeatures P((char* args, ChessProgramState *cps));
212 void InitBackEnd3 P((void));
213 void FeatureDone P((ChessProgramState* cps, int val));
214 void InitChessProgram P((ChessProgramState *cps, int setup));
215 void OutputKibitz(int window, char *text);
216 int PerpetualChase(int first, int last);
217 int EngineOutputIsUp();
218 void InitDrawingSizes(int x, int y);
219 void NextMatchGame P((void));
220 int NextTourneyGame P((int nr, int *swap));
221 int Pairing P((int nr, int nPlayers, int *w, int *b, int *sync));
222 FILE *WriteTourneyFile P((char *results, FILE *f));
223 void DisplayTwoMachinesTitle P(());
224 static void ExcludeClick P((int index));
225 void ToggleSecond P((void));
228 extern void ConsoleCreate();
231 ChessProgramState *WhitePlayer();
232 void InsertIntoMemo P((int which, char *text)); // [HGM] kibitz: in engineo.c
233 int VerifyDisplayMode P(());
235 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
236 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
237 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
238 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
239 void ics_update_width P((int new_width));
240 extern char installDir[MSG_SIZ];
241 VariantClass startVariant; /* [HGM] nicks: initial variant */
244 extern int tinyLayout, smallLayout;
245 ChessProgramStats programStats;
246 char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
248 static int exiting = 0; /* [HGM] moved to top */
249 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
250 int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
251 Board partnerBoard; /* [HGM] bughouse: for peeking at partner game */
252 int partnerHighlight[2];
253 Boolean partnerBoardValid = 0;
254 char partnerStatus[MSG_SIZ];
256 Boolean originalFlip;
257 Boolean twoBoards = 0;
258 char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
259 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
260 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
261 int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
262 Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing */
263 int opponentKibitzes;
264 int lastSavedGame; /* [HGM] save: ID of game */
265 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
266 extern int chatCount;
268 char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
269 char lastMsg[MSG_SIZ];
270 ChessSquare pieceSweep = EmptySquare;
271 ChessSquare promoSweep = EmptySquare, defaultPromoChoice;
272 int promoDefaultAltered;
273 int keepInfo = 0; /* [HGM] to protect PGN tags in auto-step game analysis */
275 /* States for ics_getting_history */
277 #define H_REQUESTED 1
278 #define H_GOT_REQ_HEADER 2
279 #define H_GOT_UNREQ_HEADER 3
280 #define H_GETTING_MOVES 4
281 #define H_GOT_UNWANTED_HEADER 5
283 /* whosays values for GameEnds */
292 /* Maximum number of games in a cmail message */
293 #define CMAIL_MAX_GAMES 20
295 /* Different types of move when calling RegisterMove */
297 #define CMAIL_RESIGN 1
299 #define CMAIL_ACCEPT 3
301 /* Different types of result to remember for each game */
302 #define CMAIL_NOT_RESULT 0
303 #define CMAIL_OLD_RESULT 1
304 #define CMAIL_NEW_RESULT 2
306 /* Telnet protocol constants */
317 safeStrCpy (char *dst, const char *src, size_t count)
320 assert( dst != NULL );
321 assert( src != NULL );
324 for(i=0; i<count; i++) if((dst[i] = src[i]) == NULLCHAR) break;
325 if( i == count && dst[count-1] != NULLCHAR)
327 dst[ count-1 ] = '\0'; // make sure incomplete copy still null-terminated
328 if(appData.debugMode)
329 fprintf(debugFP, "safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst, (int)count);
335 /* Some compiler can't cast u64 to double
336 * This function do the job for us:
338 * We use the highest bit for cast, this only
339 * works if the highest bit is not
340 * in use (This should not happen)
342 * We used this for all compiler
345 u64ToDouble (u64 value)
348 u64 tmp = value & u64Const(0x7fffffffffffffff);
349 r = (double)(s64)tmp;
350 if (value & u64Const(0x8000000000000000))
351 r += 9.2233720368547758080e18; /* 2^63 */
355 /* Fake up flags for now, as we aren't keeping track of castling
356 availability yet. [HGM] Change of logic: the flag now only
357 indicates the type of castlings allowed by the rule of the game.
358 The actual rights themselves are maintained in the array
359 castlingRights, as part of the game history, and are not probed
365 int flags = F_ALL_CASTLE_OK;
366 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
367 switch (gameInfo.variant) {
369 flags &= ~F_ALL_CASTLE_OK;
370 case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
371 flags |= F_IGNORE_CHECK;
373 flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
376 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
378 case VariantKriegspiel:
379 flags |= F_KRIEGSPIEL_CAPTURE;
381 case VariantCapaRandom:
382 case VariantFischeRandom:
383 flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
384 case VariantNoCastle:
385 case VariantShatranj:
389 flags &= ~F_ALL_CASTLE_OK;
397 FILE *gameFileFP, *debugFP, *serverFP;
398 char *currentDebugFile; // [HGM] debug split: to remember name
401 [AS] Note: sometimes, the sscanf() function is used to parse the input
402 into a fixed-size buffer. Because of this, we must be prepared to
403 receive strings as long as the size of the input buffer, which is currently
404 set to 4K for Windows and 8K for the rest.
405 So, we must either allocate sufficiently large buffers here, or
406 reduce the size of the input buffer in the input reading part.
409 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
410 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
411 char thinkOutput1[MSG_SIZ*10];
413 ChessProgramState first, second, pairing;
415 /* premove variables */
418 int premoveFromX = 0;
419 int premoveFromY = 0;
420 int premovePromoChar = 0;
422 Boolean alarmSounded;
423 /* end premove variables */
425 char *ics_prefix = "$";
426 enum ICS_TYPE ics_type = ICS_GENERIC;
428 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
429 int pauseExamForwardMostMove = 0;
430 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
431 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
432 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
433 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
434 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
435 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
436 int whiteFlag = FALSE, blackFlag = FALSE;
437 int userOfferedDraw = FALSE;
438 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
439 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
440 int cmailMoveType[CMAIL_MAX_GAMES];
441 long ics_clock_paused = 0;
442 ProcRef icsPR = NoProc, cmailPR = NoProc;
443 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
444 GameMode gameMode = BeginningOfGame;
445 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
446 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
447 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
448 int hiddenThinkOutputState = 0; /* [AS] */
449 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
450 int adjudicateLossPlies = 6;
451 char white_holding[64], black_holding[64];
452 TimeMark lastNodeCountTime;
453 long lastNodeCount=0;
454 int shiftKey, controlKey; // [HGM] set by mouse handler
456 int have_sent_ICS_logon = 0;
458 int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
459 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack, activePartnerTime;
460 Boolean adjustedClock;
461 long timeControl_2; /* [AS] Allow separate time controls */
462 char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC, activePartner; /* [HGM] secondary TC: merge of MPS, TC and inc */
463 long timeRemaining[2][MAX_MOVES];
464 int matchGame = 0, nextGame = 0, roundNr = 0;
465 Boolean waitingForGame = FALSE;
466 TimeMark programStartTime, pauseStart;
467 char ics_handle[MSG_SIZ];
468 int have_set_title = 0;
470 /* animateTraining preserves the state of appData.animate
471 * when Training mode is activated. This allows the
472 * response to be animated when appData.animate == TRUE and
473 * appData.animateDragging == TRUE.
475 Boolean animateTraining;
481 Board boards[MAX_MOVES];
482 /* [HGM] Following 7 needed for accurate legality tests: */
483 signed char castlingRank[BOARD_FILES]; // and corresponding ranks
484 signed char initialRights[BOARD_FILES];
485 int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
486 int initialRulePlies, FENrulePlies;
487 FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
489 Boolean shuffleOpenings;
490 int mute; // mute all sounds
492 // [HGM] vari: next 12 to save and restore variations
493 #define MAX_VARIATIONS 10
494 int framePtr = MAX_MOVES-1; // points to free stack entry
496 int savedFirst[MAX_VARIATIONS];
497 int savedLast[MAX_VARIATIONS];
498 int savedFramePtr[MAX_VARIATIONS];
499 char *savedDetails[MAX_VARIATIONS];
500 ChessMove savedResult[MAX_VARIATIONS];
502 void PushTail P((int firstMove, int lastMove));
503 Boolean PopTail P((Boolean annotate));
504 void PushInner P((int firstMove, int lastMove));
505 void PopInner P((Boolean annotate));
506 void CleanupTail P((void));
508 ChessSquare FIDEArray[2][BOARD_FILES] = {
509 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
510 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
511 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
512 BlackKing, BlackBishop, BlackKnight, BlackRook }
515 ChessSquare twoKingsArray[2][BOARD_FILES] = {
516 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
517 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
518 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
519 BlackKing, BlackKing, BlackKnight, BlackRook }
522 ChessSquare KnightmateArray[2][BOARD_FILES] = {
523 { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
524 WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
525 { BlackRook, BlackMan, BlackBishop, BlackQueen,
526 BlackUnicorn, BlackBishop, BlackMan, BlackRook }
529 ChessSquare SpartanArray[2][BOARD_FILES] = {
530 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
531 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
532 { BlackAlfil, BlackMarshall, BlackKing, BlackDragon,
533 BlackDragon, BlackKing, BlackAngel, BlackAlfil }
536 ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
537 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
538 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
539 { BlackCardinal, BlackAlfil, BlackMarshall, BlackAngel,
540 BlackKing, BlackMarshall, BlackAlfil, BlackCardinal }
543 ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
544 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
545 WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
546 { BlackRook, BlackKnight, BlackAlfil, BlackKing,
547 BlackFerz, BlackAlfil, BlackKnight, BlackRook }
550 ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
551 { WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
552 WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
553 { BlackRook, BlackKnight, BlackMan, BlackFerz,
554 BlackKing, BlackMan, BlackKnight, BlackRook }
558 #if (BOARD_FILES>=10)
559 ChessSquare ShogiArray[2][BOARD_FILES] = {
560 { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
561 WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
562 { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
563 BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
566 ChessSquare XiangqiArray[2][BOARD_FILES] = {
567 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
568 WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
569 { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
570 BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
573 ChessSquare CapablancaArray[2][BOARD_FILES] = {
574 { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
575 WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
576 { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
577 BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
580 ChessSquare GreatArray[2][BOARD_FILES] = {
581 { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
582 WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
583 { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
584 BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
587 ChessSquare JanusArray[2][BOARD_FILES] = {
588 { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
589 WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
590 { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
591 BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
594 ChessSquare GrandArray[2][BOARD_FILES] = {
595 { EmptySquare, WhiteKnight, WhiteBishop, WhiteQueen, WhiteKing,
596 WhiteMarshall, WhiteAngel, WhiteBishop, WhiteKnight, EmptySquare },
597 { EmptySquare, BlackKnight, BlackBishop, BlackQueen, BlackKing,
598 BlackMarshall, BlackAngel, BlackBishop, BlackKnight, EmptySquare }
602 ChessSquare GothicArray[2][BOARD_FILES] = {
603 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
604 WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
605 { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
606 BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
609 #define GothicArray CapablancaArray
613 ChessSquare FalconArray[2][BOARD_FILES] = {
614 { WhiteRook, WhiteKnight, WhiteBishop, WhiteFalcon, WhiteQueen,
615 WhiteKing, WhiteFalcon, WhiteBishop, WhiteKnight, WhiteRook },
616 { BlackRook, BlackKnight, BlackBishop, BlackFalcon, BlackQueen,
617 BlackKing, BlackFalcon, BlackBishop, BlackKnight, BlackRook }
620 #define FalconArray CapablancaArray
623 #else // !(BOARD_FILES>=10)
624 #define XiangqiPosition FIDEArray
625 #define CapablancaArray FIDEArray
626 #define GothicArray FIDEArray
627 #define GreatArray FIDEArray
628 #endif // !(BOARD_FILES>=10)
630 #if (BOARD_FILES>=12)
631 ChessSquare CourierArray[2][BOARD_FILES] = {
632 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
633 WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
634 { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
635 BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
637 #else // !(BOARD_FILES>=12)
638 #define CourierArray CapablancaArray
639 #endif // !(BOARD_FILES>=12)
642 Board initialPosition;
645 /* Convert str to a rating. Checks for special cases of "----",
647 "++++", etc. Also strips ()'s */
649 string_to_rating (char *str)
651 while(*str && !isdigit(*str)) ++str;
653 return 0; /* One of the special "no rating" cases */
661 /* Init programStats */
662 programStats.movelist[0] = 0;
663 programStats.depth = 0;
664 programStats.nr_moves = 0;
665 programStats.moves_left = 0;
666 programStats.nodes = 0;
667 programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
668 programStats.score = 0;
669 programStats.got_only_move = 0;
670 programStats.got_fail = 0;
671 programStats.line_is_book = 0;
676 { // [HGM] moved some code here from InitBackend1 that has to be done after both engines have contributed their settings
677 if (appData.firstPlaysBlack) {
678 first.twoMachinesColor = "black\n";
679 second.twoMachinesColor = "white\n";
681 first.twoMachinesColor = "white\n";
682 second.twoMachinesColor = "black\n";
685 first.other = &second;
686 second.other = &first;
689 if(appData.timeOddsMode) {
690 norm = appData.timeOdds[0];
691 if(norm > appData.timeOdds[1]) norm = appData.timeOdds[1];
693 first.timeOdds = appData.timeOdds[0]/norm;
694 second.timeOdds = appData.timeOdds[1]/norm;
697 if(programVersion) free(programVersion);
698 if (appData.noChessProgram) {
699 programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
700 sprintf(programVersion, "%s", PACKAGE_STRING);
702 /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
703 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
704 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
709 UnloadEngine (ChessProgramState *cps)
711 /* Kill off first chess program */
712 if (cps->isr != NULL)
713 RemoveInputSource(cps->isr);
716 if (cps->pr != NoProc) {
718 DoSleep( appData.delayBeforeQuit );
719 SendToProgram("quit\n", cps);
720 DoSleep( appData.delayAfterQuit );
721 DestroyChildProcess(cps->pr, cps->useSigterm);
724 if(appData.debugMode) fprintf(debugFP, "Unload %s\n", cps->which);
728 ClearOptions (ChessProgramState *cps)
731 cps->nrOptions = cps->comboCnt = 0;
732 for(i=0; i<MAX_OPTIONS; i++) {
733 cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
734 cps->option[i].textValue = 0;
738 char *engineNames[] = {
739 /* TRANSLATORS: "first" is the first of possible two chess engines. It is inserted into strings
740 such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
742 /* TRANSLATORS: "second" is the second of possible two chess engines. It is inserted into strings
743 such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
748 InitEngine (ChessProgramState *cps, int n)
749 { // [HGM] all engine initialiation put in a function that does one engine
753 cps->which = engineNames[n];
754 cps->maybeThinking = FALSE;
758 cps->sendDrawOffers = 1;
760 cps->program = appData.chessProgram[n];
761 cps->host = appData.host[n];
762 cps->dir = appData.directory[n];
763 cps->initString = appData.engInitString[n];
764 cps->computerString = appData.computerString[n];
765 cps->useSigint = TRUE;
766 cps->useSigterm = TRUE;
767 cps->reuse = appData.reuse[n];
768 cps->nps = appData.NPS[n]; // [HGM] nps: copy nodes per second
769 cps->useSetboard = FALSE;
771 cps->usePing = FALSE;
774 cps->usePlayother = FALSE;
775 cps->useColors = TRUE;
776 cps->useUsermove = FALSE;
777 cps->sendICS = FALSE;
778 cps->sendName = appData.icsActive;
779 cps->sdKludge = FALSE;
780 cps->stKludge = FALSE;
781 TidyProgramName(cps->program, cps->host, cps->tidy);
783 safeStrCpy(cps->variants, appData.variant, MSG_SIZ);
784 cps->analysisSupport = 2; /* detect */
785 cps->analyzing = FALSE;
786 cps->initDone = FALSE;
788 /* New features added by Tord: */
789 cps->useFEN960 = FALSE;
790 cps->useOOCastle = TRUE;
791 /* End of new features added by Tord. */
792 cps->fenOverride = appData.fenOverride[n];
794 /* [HGM] time odds: set factor for each machine */
795 cps->timeOdds = appData.timeOdds[n];
797 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
798 cps->accumulateTC = appData.accumulateTC[n];
799 cps->maxNrOfSessions = 1;
804 cps->supportsNPS = UNKNOWN;
805 cps->memSize = FALSE;
806 cps->maxCores = FALSE;
807 cps->egtFormats[0] = NULLCHAR;
810 cps->optionSettings = appData.engOptions[n];
812 cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
813 cps->isUCI = appData.isUCI[n]; /* [AS] */
814 cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
816 if (appData.protocolVersion[n] > PROTOVER
817 || appData.protocolVersion[n] < 1)
822 len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
823 appData.protocolVersion[n]);
824 if( (len >= MSG_SIZ) && appData.debugMode )
825 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
827 DisplayFatalError(buf, 0, 2);
831 cps->protocolVersion = appData.protocolVersion[n];
834 InitEngineUCI( installDir, cps ); // [HGM] moved here from winboard.c, to make available in xboard
835 ParseFeatures(appData.featureDefaults, cps);
838 ChessProgramState *savCps;
844 if(WaitForEngine(savCps, LoadEngine)) return;
845 CommonEngineInit(); // recalculate time odds
846 if(gameInfo.variant != StringToVariant(appData.variant)) {
847 // we changed variant when loading the engine; this forces us to reset
848 Reset(TRUE, savCps != &first);
849 EditGameEvent(); // for consistency with other path, as Reset changes mode
851 InitChessProgram(savCps, FALSE);
852 SendToProgram("force\n", savCps);
853 DisplayMessage("", "");
854 if (startedFromSetupPosition) SendBoard(savCps, backwardMostMove);
855 for (i = backwardMostMove; i < currentMove; i++) SendMoveToProgram(i, savCps);
861 ReplaceEngine (ChessProgramState *cps, int n)
865 appData.noChessProgram = FALSE;
866 appData.clockMode = TRUE;
869 if(n) return; // only startup first engine immediately; second can wait
870 savCps = cps; // parameter to LoadEngine passed as globals, to allow scheduled calling :-(
874 extern char *engineName, *engineDir, *engineChoice, *engineLine, *nickName, *params;
875 extern Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick;
877 static char resetOptions[] =
878 "-reuse -firstIsUCI false -firstHasOwnBookUCI true -firstTimeOdds 1 "
879 "-firstInitString \"" INIT_STRING "\" -firstComputerString \"" COMPUTER_STRING "\" "
880 "-firstFeatures \"\" -firstLogo \"\" -firstAccumulateTC 1 "
881 "-firstOptions \"\" -firstNPS -1 -fn \"\" -firstScoreAbs false";
884 FloatToFront(char **list, char *engineLine)
886 char buf[MSG_SIZ], tidy[MSG_SIZ], *p = buf, *q, *r = buf;
888 if(appData.recentEngines <= 0) return;
889 TidyProgramName(engineLine, "localhost", tidy+1);
890 tidy[0] = buf[0] = '\n'; strcat(tidy, "\n");
891 strncpy(buf+1, *list, MSG_SIZ-50);
892 if(p = strstr(buf, tidy)) { // tidy name appears in list
893 q = strchr(++p, '\n'); if(q == NULL) return; // malformed, don't touch
894 while(*p++ = *++q); // squeeze out
896 strcat(tidy, buf+1); // put list behind tidy name
897 p = tidy + 1; while(q = strchr(p, '\n')) i++, r = p, p = q + 1; // count entries in new list
898 if(i > appData.recentEngines) *r = NULLCHAR; // if maximum rached, strip off last
899 ASSIGN(*list, tidy+1);
902 char *insert, *wbOptions; // point in ChessProgramNames were we should insert new engine
905 Load (ChessProgramState *cps, int i)
907 char *p, *q, buf[MSG_SIZ], command[MSG_SIZ], buf2[MSG_SIZ];
908 if(engineLine && engineLine[0]) { // an engine was selected from the combo box
909 snprintf(buf, MSG_SIZ, "-fcp %s", engineLine);
910 SwapEngines(i); // kludge to parse -f* / -first* like it is -s* / -second*
911 ParseArgsFromString(resetOptions); appData.pvSAN[0] = FALSE;
912 FREE(appData.fenOverride[0]); appData.fenOverride[0] = NULL;
913 appData.firstProtocolVersion = PROTOVER;
914 ParseArgsFromString(buf);
916 ReplaceEngine(cps, i);
917 FloatToFront(&appData.recentEngineList, engineLine);
921 while(q = strchr(p, SLASH)) p = q+1;
922 if(*p== NULLCHAR) { DisplayError(_("You did not specify the engine executable"), 0); return; }
923 if(engineDir[0] != NULLCHAR) {
924 ASSIGN(appData.directory[i], engineDir); p = engineName;
925 } else if(p != engineName) { // derive directory from engine path, when not given
927 ASSIGN(appData.directory[i], engineName);
929 if(SLASH == '/' && p - engineName > 1) *(p -= 2) = '.'; // for XBoard use ./exeName as command after split!
930 } else { ASSIGN(appData.directory[i], "."); }
932 if(strchr(p, ' ') && !strchr(p, '"')) snprintf(buf2, MSG_SIZ, "\"%s\"", p), p = buf2; // quote if it contains spaces
933 snprintf(command, MSG_SIZ, "%s %s", p, params);
936 ASSIGN(appData.chessProgram[i], p);
937 appData.isUCI[i] = isUCI;
938 appData.protocolVersion[i] = v1 ? 1 : PROTOVER;
939 appData.hasOwnBookUCI[i] = hasBook;
940 if(!nickName[0]) useNick = FALSE;
941 if(useNick) ASSIGN(appData.pgnName[i], nickName);
945 q = firstChessProgramNames;
946 if(nickName[0]) snprintf(buf, MSG_SIZ, "\"%s\" -fcp ", nickName); else buf[0] = NULLCHAR;
947 quote = strchr(p, '"') ? '\'' : '"'; // use single quotes around engine command if it contains double quotes
948 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), "%c%s%c -fd \"%s\"%s%s%s%s%s%s%s%s\n",
949 quote, p, quote, appData.directory[i],
950 useNick ? " -fn \"" : "",
951 useNick ? nickName : "",
953 v1 ? " -firstProtocolVersion 1" : "",
954 hasBook ? "" : " -fNoOwnBookUCI",
955 isUCI ? (isUCI == TRUE ? " -fUCI" : gameInfo.variant == VariantShogi ? " -fUSI" : " -fUCCI") : "",
956 storeVariant ? " -variant " : "",
957 storeVariant ? VariantName(gameInfo.variant) : "");
958 if(wbOptions && wbOptions[0]) snprintf(buf+strlen(buf)-1, MSG_SIZ-strlen(buf), " %s\n", wbOptions);
959 firstChessProgramNames = malloc(len = strlen(q) + strlen(buf) + 1);
960 if(insert != q) insert[-1] = NULLCHAR;
961 snprintf(firstChessProgramNames, len, "%s\n%s%s", q, buf, insert);
963 FloatToFront(&appData.recentEngineList, buf);
965 ReplaceEngine(cps, i);
971 int matched, min, sec;
973 * Parse timeControl resource
975 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
976 appData.movesPerSession)) {
978 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
979 DisplayFatalError(buf, 0, 2);
983 * Parse searchTime resource
985 if (*appData.searchTime != NULLCHAR) {
986 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
988 searchTime = min * 60;
989 } else if (matched == 2) {
990 searchTime = min * 60 + sec;
993 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
994 DisplayFatalError(buf, 0, 2);
1003 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
1004 startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
1006 GetTimeMark(&programStartTime);
1007 srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
1008 appData.seedBase = random() + (random()<<15);
1009 pauseStart = programStartTime; pauseStart.sec -= 100; // [HGM] matchpause: fake a pause that has long since ended
1011 ClearProgramStats();
1012 programStats.ok_to_send = 1;
1013 programStats.seen_stat = 0;
1016 * Initialize game list
1022 * Internet chess server status
1024 if (appData.icsActive) {
1025 appData.matchMode = FALSE;
1026 appData.matchGames = 0;
1028 appData.noChessProgram = !appData.zippyPlay;
1030 appData.zippyPlay = FALSE;
1031 appData.zippyTalk = FALSE;
1032 appData.noChessProgram = TRUE;
1034 if (*appData.icsHelper != NULLCHAR) {
1035 appData.useTelnet = TRUE;
1036 appData.telnetProgram = appData.icsHelper;
1039 appData.zippyTalk = appData.zippyPlay = FALSE;
1042 /* [AS] Initialize pv info list [HGM] and game state */
1046 for( i=0; i<=framePtr; i++ ) {
1047 pvInfoList[i].depth = -1;
1048 boards[i][EP_STATUS] = EP_NONE;
1049 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
1055 /* [AS] Adjudication threshold */
1056 adjudicateLossThreshold = appData.adjudicateLossThreshold;
1058 InitEngine(&first, 0);
1059 InitEngine(&second, 1);
1062 pairing.which = "pairing"; // pairing engine
1063 pairing.pr = NoProc;
1065 pairing.program = appData.pairingEngine;
1066 pairing.host = "localhost";
1069 if (appData.icsActive) {
1070 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
1071 } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
1072 appData.clockMode = FALSE;
1073 first.sendTime = second.sendTime = 0;
1077 /* Override some settings from environment variables, for backward
1078 compatibility. Unfortunately it's not feasible to have the env
1079 vars just set defaults, at least in xboard. Ugh.
1081 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
1086 if (!appData.icsActive) {
1090 /* Check for variants that are supported only in ICS mode,
1091 or not at all. Some that are accepted here nevertheless
1092 have bugs; see comments below.
1094 VariantClass variant = StringToVariant(appData.variant);
1096 case VariantBughouse: /* need four players and two boards */
1097 case VariantKriegspiel: /* need to hide pieces and move details */
1098 /* case VariantFischeRandom: (Fabien: moved below) */
1099 len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
1100 if( (len >= MSG_SIZ) && appData.debugMode )
1101 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1103 DisplayFatalError(buf, 0, 2);
1106 case VariantUnknown:
1107 case VariantLoadable:
1117 len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
1118 if( (len >= MSG_SIZ) && appData.debugMode )
1119 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1121 DisplayFatalError(buf, 0, 2);
1124 case VariantXiangqi: /* [HGM] repetition rules not implemented */
1125 case VariantFairy: /* [HGM] TestLegality definitely off! */
1126 case VariantGothic: /* [HGM] should work */
1127 case VariantCapablanca: /* [HGM] should work */
1128 case VariantCourier: /* [HGM] initial forced moves not implemented */
1129 case VariantShogi: /* [HGM] could still mate with pawn drop */
1130 case VariantKnightmate: /* [HGM] should work */
1131 case VariantCylinder: /* [HGM] untested */
1132 case VariantFalcon: /* [HGM] untested */
1133 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
1134 offboard interposition not understood */
1135 case VariantNormal: /* definitely works! */
1136 case VariantWildCastle: /* pieces not automatically shuffled */
1137 case VariantNoCastle: /* pieces not automatically shuffled */
1138 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
1139 case VariantLosers: /* should work except for win condition,
1140 and doesn't know captures are mandatory */
1141 case VariantSuicide: /* should work except for win condition,
1142 and doesn't know captures are mandatory */
1143 case VariantGiveaway: /* should work except for win condition,
1144 and doesn't know captures are mandatory */
1145 case VariantTwoKings: /* should work */
1146 case VariantAtomic: /* should work except for win condition */
1147 case Variant3Check: /* should work except for win condition */
1148 case VariantShatranj: /* should work except for all win conditions */
1149 case VariantMakruk: /* should work except for draw countdown */
1150 case VariantBerolina: /* might work if TestLegality is off */
1151 case VariantCapaRandom: /* should work */
1152 case VariantJanus: /* should work */
1153 case VariantSuper: /* experimental */
1154 case VariantGreat: /* experimental, requires legality testing to be off */
1155 case VariantSChess: /* S-Chess, should work */
1156 case VariantGrand: /* should work */
1157 case VariantSpartan: /* should work */
1165 NextIntegerFromString (char ** str, long * value)
1170 while( *s == ' ' || *s == '\t' ) {
1176 if( *s >= '0' && *s <= '9' ) {
1177 while( *s >= '0' && *s <= '9' ) {
1178 *value = *value * 10 + (*s - '0');
1191 NextTimeControlFromString (char ** str, long * value)
1194 int result = NextIntegerFromString( str, &temp );
1197 *value = temp * 60; /* Minutes */
1198 if( **str == ':' ) {
1200 result = NextIntegerFromString( str, &temp );
1201 *value += temp; /* Seconds */
1209 NextSessionFromString (char ** str, int *moves, long * tc, long *inc, int *incType)
1210 { /* [HGM] routine added to read '+moves/time' for secondary time control. */
1211 int result = -1, type = 0; long temp, temp2;
1213 if(**str != ':') return -1; // old params remain in force!
1215 if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
1216 if( NextIntegerFromString( str, &temp ) ) return -1;
1217 if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
1220 /* time only: incremental or sudden-death time control */
1221 if(**str == '+') { /* increment follows; read it */
1223 if(**str == '!') type = *(*str)++; // Bronstein TC
1224 if(result = NextIntegerFromString( str, &temp2)) return -1;
1225 *inc = temp2 * 1000;
1226 if(**str == '.') { // read fraction of increment
1227 char *start = ++(*str);
1228 if(result = NextIntegerFromString( str, &temp2)) return -1;
1230 while(start++ < *str) temp2 /= 10;
1234 *moves = 0; *tc = temp * 1000; *incType = type;
1238 (*str)++; /* classical time control */
1239 result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
1251 GetTimeQuota (int movenr, int lastUsed, char *tcString)
1252 { /* [HGM] get time to add from the multi-session time-control string */
1253 int incType, moves=1; /* kludge to force reading of first session */
1254 long time, increment;
1257 if(!s || !*s) return 0; // empty TC string means we ran out of the last sudden-death version
1259 if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
1260 nextSession = s; suddenDeath = moves == 0 && increment == 0;
1261 if(movenr == -1) return time; /* last move before new session */
1262 if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
1263 if(incType == '!' && lastUsed < increment) increment = lastUsed;
1264 if(!moves) return increment; /* current session is incremental */
1265 if(movenr >= 0) movenr -= moves; /* we already finished this session */
1266 } while(movenr >= -1); /* try again for next session */
1268 return 0; // no new time quota on this move
1272 ParseTimeControl (char *tc, float ti, int mps)
1276 char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
1279 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1280 if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
1281 sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
1285 snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
1287 snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
1290 snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
1292 snprintf(buf, MSG_SIZ, ":%s", mytc);
1294 fullTimeControlString = StrSave(buf); // this should now be in PGN format
1296 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1301 /* Parse second time control */
1304 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1312 timeControl_2 = tc2 * 1000;
1322 timeControl = tc1 * 1000;
1325 timeIncrement = ti * 1000; /* convert to ms */
1326 movesPerSession = 0;
1329 movesPerSession = mps;
1337 if (appData.debugMode) {
1338 fprintf(debugFP, "%s\n", programVersion);
1340 ASSIGN(currentDebugFile, appData.nameOfDebugFile); // [HGM] debug split: remember initial name in use
1342 set_cont_sequence(appData.wrapContSeq);
1343 if (appData.matchGames > 0) {
1344 appData.matchMode = TRUE;
1345 } else if (appData.matchMode) {
1346 appData.matchGames = 1;
1348 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1349 appData.matchGames = appData.sameColorGames;
1350 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1351 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1352 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1355 if (appData.noChessProgram || first.protocolVersion == 1) {
1358 /* kludge: allow timeout for initial "feature" commands */
1360 DisplayMessage("", _("Starting chess program"));
1361 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1366 CalculateIndex (int index, int gameNr)
1367 { // [HGM] autoinc: absolute way to determine load index from game number (taking auto-inc and rewind into account)
1369 if(index > 0) return index; // fixed nmber
1370 if(index == 0) return 1;
1371 res = (index == -1 ? gameNr : (gameNr-1)/2 + 1); // autoinc
1372 if(appData.rewindIndex > 0) res = (res-1) % appData.rewindIndex + 1; // rewind
1377 LoadGameOrPosition (int gameNr)
1378 { // [HGM] taken out of MatchEvent and NextMatchGame (to combine it)
1379 if (*appData.loadGameFile != NULLCHAR) {
1380 if (!LoadGameFromFile(appData.loadGameFile,
1381 CalculateIndex(appData.loadGameIndex, gameNr),
1382 appData.loadGameFile, FALSE)) {
1383 DisplayFatalError(_("Bad game file"), 0, 1);
1386 } else if (*appData.loadPositionFile != NULLCHAR) {
1387 if (!LoadPositionFromFile(appData.loadPositionFile,
1388 CalculateIndex(appData.loadPositionIndex, gameNr),
1389 appData.loadPositionFile)) {
1390 DisplayFatalError(_("Bad position file"), 0, 1);
1398 ReserveGame (int gameNr, char resChar)
1400 FILE *tf = fopen(appData.tourneyFile, "r+");
1401 char *p, *q, c, buf[MSG_SIZ];
1402 if(tf == NULL) { nextGame = appData.matchGames + 1; return; } // kludge to terminate match
1403 safeStrCpy(buf, lastMsg, MSG_SIZ);
1404 DisplayMessage(_("Pick new game"), "");
1405 flock(fileno(tf), LOCK_EX); // lock the tourney file while we are messing with it
1406 ParseArgsFromFile(tf);
1407 p = q = appData.results;
1408 if(appData.debugMode) {
1409 char *r = appData.participants;
1410 fprintf(debugFP, "results = '%s'\n", p);
1411 while(*r) fprintf(debugFP, *r >= ' ' ? "%c" : "\\%03o", *r), r++;
1412 fprintf(debugFP, "\n");
1414 while(*q && *q != ' ') q++; // get first un-played game (could be beyond end!)
1416 q = malloc(strlen(p) + 2); // could be arbitrary long, but allow to extend by one!
1417 safeStrCpy(q, p, strlen(p) + 2);
1418 if(gameNr >= 0) q[gameNr] = resChar; // replace '*' with result
1419 if(appData.debugMode) fprintf(debugFP, "pick next game from '%s': %d\n", q, nextGame);
1420 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch) { // reserve next game if tourney not yet done
1421 if(q[nextGame] == NULLCHAR) q[nextGame+1] = NULLCHAR; // append one char
1424 fseek(tf, -(strlen(p)+4), SEEK_END);
1426 if(c != '"') // depending on DOS or Unix line endings we can be one off
1427 fseek(tf, -(strlen(p)+2), SEEK_END);
1428 else fseek(tf, -(strlen(p)+3), SEEK_END);
1429 fprintf(tf, "%s\"\n", q); fclose(tf); // update, and flush by closing
1430 DisplayMessage(buf, "");
1431 free(p); appData.results = q;
1432 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch &&
1433 (gameNr < 0 || nextGame / appData.defaultMatchGames != gameNr / appData.defaultMatchGames)) {
1434 int round = appData.defaultMatchGames * appData.tourneyType;
1435 if(gameNr < 0 || appData.tourneyType < 1 || // gauntlet engine can always stay loaded as first engine
1436 appData.tourneyType > 1 && nextGame/round != gameNr/round) // in multi-gauntlet change only after round
1437 UnloadEngine(&first); // next game belongs to other pairing;
1438 UnloadEngine(&second); // already unload the engines, so TwoMachinesEvent will load new ones.
1440 if(appData.debugMode) fprintf(debugFP, "Reserved, next=%d, nr=%d\n", nextGame, gameNr);
1444 MatchEvent (int mode)
1445 { // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
1447 if(matchMode) { // already in match mode: switch it off
1449 if(!appData.tourneyFile[0]) appData.matchGames = matchGame; // kludge to let match terminate after next game.
1452 // if(gameMode != BeginningOfGame) {
1453 // DisplayError(_("You can only start a match from the initial position."), 0);
1457 if(mode == 2) appData.matchGames = appData.defaultMatchGames;
1458 /* Set up machine vs. machine match */
1460 NextTourneyGame(-1, &dummy); // sets appData.matchGames if this is tourney, to make sure ReserveGame knows it
1461 if(appData.tourneyFile[0]) {
1463 if(nextGame > appData.matchGames) {
1465 if(strchr(appData.results, '*') == NULL) {
1467 appData.tourneyCycles++;
1468 if(f = WriteTourneyFile(appData.results, NULL)) { // make a tourney file with increased number of cycles
1470 NextTourneyGame(-1, &dummy);
1472 if(nextGame <= appData.matchGames) {
1473 DisplayNote(_("You restarted an already completed tourney\nOne more cycle will now be added to it\nGames commence in 10 sec"));
1475 ScheduleDelayedEvent(NextMatchGame, 10000);
1480 snprintf(buf, MSG_SIZ, _("All games in tourney '%s' are already played or playing"), appData.tourneyFile);
1481 DisplayError(buf, 0);
1482 appData.tourneyFile[0] = 0;
1486 if (appData.noChessProgram) { // [HGM] in tourney engines are loaded automatically
1487 DisplayFatalError(_("Can't have a match with no chess programs"),
1492 matchGame = roundNr = 1;
1493 first.matchWins = second.matchWins = 0; // [HGM] match: needed in later matches
1497 char *comboLine = NULL; // [HGM] recent: WinBoard's first-engine combobox line
1500 InitBackEnd3 P((void))
1502 GameMode initialMode;
1506 InitChessProgram(&first, startedFromSetupPosition);
1508 if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
1509 free(programVersion);
1510 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1511 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1512 FloatToFront(&appData.recentEngineList, comboLine ? comboLine : appData.firstChessProgram);
1515 if (appData.icsActive) {
1517 /* [DM] Make a console window if needed [HGM] merged ifs */
1523 if (*appData.icsCommPort != NULLCHAR)
1524 len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1525 appData.icsCommPort);
1527 len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1528 appData.icsHost, appData.icsPort);
1530 if( (len >= MSG_SIZ) && appData.debugMode )
1531 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1533 DisplayFatalError(buf, err, 1);
1538 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1540 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1541 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1542 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1543 } else if (appData.noChessProgram) {
1549 if (*appData.cmailGameName != NULLCHAR) {
1551 OpenLoopback(&cmailPR);
1553 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1557 DisplayMessage("", "");
1558 if (StrCaseCmp(appData.initialMode, "") == 0) {
1559 initialMode = BeginningOfGame;
1560 if(!appData.icsActive && appData.noChessProgram) { // [HGM] could be fall-back
1561 gameMode = MachinePlaysBlack; // "Machine Black" might have been implicitly highlighted
1562 ModeHighlight(); // make sure XBoard knows it is highlighted, so it will un-highlight it
1563 gameMode = BeginningOfGame; // in case BeginningOfGame now means "Edit Position"
1566 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1567 initialMode = TwoMachinesPlay;
1568 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1569 initialMode = AnalyzeFile;
1570 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1571 initialMode = AnalyzeMode;
1572 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1573 initialMode = MachinePlaysWhite;
1574 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1575 initialMode = MachinePlaysBlack;
1576 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1577 initialMode = EditGame;
1578 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1579 initialMode = EditPosition;
1580 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1581 initialMode = Training;
1583 len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1584 if( (len >= MSG_SIZ) && appData.debugMode )
1585 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1587 DisplayFatalError(buf, 0, 2);
1591 if (appData.matchMode) {
1592 if(appData.tourneyFile[0]) { // start tourney from command line
1594 if(f = fopen(appData.tourneyFile, "r")) {
1595 ParseArgsFromFile(f); // make sure tourney parmeters re known
1597 appData.clockMode = TRUE;
1599 } else appData.tourneyFile[0] = NULLCHAR; // for now ignore bad tourney file
1602 } else if (*appData.cmailGameName != NULLCHAR) {
1603 /* Set up cmail mode */
1604 ReloadCmailMsgEvent(TRUE);
1606 /* Set up other modes */
1607 if (initialMode == AnalyzeFile) {
1608 if (*appData.loadGameFile == NULLCHAR) {
1609 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1613 if (*appData.loadGameFile != NULLCHAR) {
1614 (void) LoadGameFromFile(appData.loadGameFile,
1615 appData.loadGameIndex,
1616 appData.loadGameFile, TRUE);
1617 } else if (*appData.loadPositionFile != NULLCHAR) {
1618 (void) LoadPositionFromFile(appData.loadPositionFile,
1619 appData.loadPositionIndex,
1620 appData.loadPositionFile);
1621 /* [HGM] try to make self-starting even after FEN load */
1622 /* to allow automatic setup of fairy variants with wtm */
1623 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1624 gameMode = BeginningOfGame;
1625 setboardSpoiledMachineBlack = 1;
1627 /* [HGM] loadPos: make that every new game uses the setup */
1628 /* from file as long as we do not switch variant */
1629 if(!blackPlaysFirst) {
1630 startedFromPositionFile = TRUE;
1631 CopyBoard(filePosition, boards[0]);
1634 if (initialMode == AnalyzeMode) {
1635 if (appData.noChessProgram) {
1636 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1639 if (appData.icsActive) {
1640 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1644 } else if (initialMode == AnalyzeFile) {
1645 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1646 ShowThinkingEvent();
1648 AnalysisPeriodicEvent(1);
1649 } else if (initialMode == MachinePlaysWhite) {
1650 if (appData.noChessProgram) {
1651 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1655 if (appData.icsActive) {
1656 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1660 MachineWhiteEvent();
1661 } else if (initialMode == MachinePlaysBlack) {
1662 if (appData.noChessProgram) {
1663 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1667 if (appData.icsActive) {
1668 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1672 MachineBlackEvent();
1673 } else if (initialMode == TwoMachinesPlay) {
1674 if (appData.noChessProgram) {
1675 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1679 if (appData.icsActive) {
1680 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1685 } else if (initialMode == EditGame) {
1687 } else if (initialMode == EditPosition) {
1688 EditPositionEvent();
1689 } else if (initialMode == Training) {
1690 if (*appData.loadGameFile == NULLCHAR) {
1691 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1700 HistorySet (char movelist[][2*MOVE_LEN], int first, int last, int current)
1702 DisplayBook(current+1);
1704 MoveHistorySet( movelist, first, last, current, pvInfoList );
1706 EvalGraphSet( first, last, current, pvInfoList );
1708 MakeEngineOutputTitle();
1712 * Establish will establish a contact to a remote host.port.
1713 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1714 * used to talk to the host.
1715 * Returns 0 if okay, error code if not.
1722 if (*appData.icsCommPort != NULLCHAR) {
1723 /* Talk to the host through a serial comm port */
1724 return OpenCommPort(appData.icsCommPort, &icsPR);
1726 } else if (*appData.gateway != NULLCHAR) {
1727 if (*appData.remoteShell == NULLCHAR) {
1728 /* Use the rcmd protocol to run telnet program on a gateway host */
1729 snprintf(buf, sizeof(buf), "%s %s %s",
1730 appData.telnetProgram, appData.icsHost, appData.icsPort);
1731 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1734 /* Use the rsh program to run telnet program on a gateway host */
1735 if (*appData.remoteUser == NULLCHAR) {
1736 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1737 appData.gateway, appData.telnetProgram,
1738 appData.icsHost, appData.icsPort);
1740 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1741 appData.remoteShell, appData.gateway,
1742 appData.remoteUser, appData.telnetProgram,
1743 appData.icsHost, appData.icsPort);
1745 return StartChildProcess(buf, "", &icsPR);
1748 } else if (appData.useTelnet) {
1749 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1752 /* TCP socket interface differs somewhat between
1753 Unix and NT; handle details in the front end.
1755 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1760 EscapeExpand (char *p, char *q)
1761 { // [HGM] initstring: routine to shape up string arguments
1762 while(*p++ = *q++) if(p[-1] == '\\')
1764 case 'n': p[-1] = '\n'; break;
1765 case 'r': p[-1] = '\r'; break;
1766 case 't': p[-1] = '\t'; break;
1767 case '\\': p[-1] = '\\'; break;
1768 case 0: *p = 0; return;
1769 default: p[-1] = q[-1]; break;
1774 show_bytes (FILE *fp, char *buf, int count)
1777 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1778 fprintf(fp, "\\%03o", *buf & 0xff);
1787 /* Returns an errno value */
1789 OutputMaybeTelnet (ProcRef pr, char *message, int count, int *outError)
1791 char buf[8192], *p, *q, *buflim;
1792 int left, newcount, outcount;
1794 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1795 *appData.gateway != NULLCHAR) {
1796 if (appData.debugMode) {
1797 fprintf(debugFP, ">ICS: ");
1798 show_bytes(debugFP, message, count);
1799 fprintf(debugFP, "\n");
1801 return OutputToProcess(pr, message, count, outError);
1804 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1811 if (appData.debugMode) {
1812 fprintf(debugFP, ">ICS: ");
1813 show_bytes(debugFP, buf, newcount);
1814 fprintf(debugFP, "\n");
1816 outcount = OutputToProcess(pr, buf, newcount, outError);
1817 if (outcount < newcount) return -1; /* to be sure */
1824 } else if (((unsigned char) *p) == TN_IAC) {
1825 *q++ = (char) TN_IAC;
1832 if (appData.debugMode) {
1833 fprintf(debugFP, ">ICS: ");
1834 show_bytes(debugFP, buf, newcount);
1835 fprintf(debugFP, "\n");
1837 outcount = OutputToProcess(pr, buf, newcount, outError);
1838 if (outcount < newcount) return -1; /* to be sure */
1843 read_from_player (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
1845 int outError, outCount;
1846 static int gotEof = 0;
1848 /* Pass data read from player on to ICS */
1851 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1852 if (outCount < count) {
1853 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1855 } else if (count < 0) {
1856 RemoveInputSource(isr);
1857 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1858 } else if (gotEof++ > 0) {
1859 RemoveInputSource(isr);
1860 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1866 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1867 if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
1868 connectionAlive = FALSE; // only sticks if no response to 'date' command.
1869 SendToICS("date\n");
1870 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1873 /* added routine for printf style output to ics */
1875 ics_printf (char *format, ...)
1877 char buffer[MSG_SIZ];
1880 va_start(args, format);
1881 vsnprintf(buffer, sizeof(buffer), format, args);
1882 buffer[sizeof(buffer)-1] = '\0';
1890 int count, outCount, outError;
1892 if (icsPR == NoProc) return;
1895 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
1896 if (outCount < count) {
1897 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1901 /* This is used for sending logon scripts to the ICS. Sending
1902 without a delay causes problems when using timestamp on ICC
1903 (at least on my machine). */
1905 SendToICSDelayed (char *s, long msdelay)
1907 int count, outCount, outError;
1909 if (icsPR == NoProc) return;
1912 if (appData.debugMode) {
1913 fprintf(debugFP, ">ICS: ");
1914 show_bytes(debugFP, s, count);
1915 fprintf(debugFP, "\n");
1917 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
1919 if (outCount < count) {
1920 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1925 /* Remove all highlighting escape sequences in s
1926 Also deletes any suffix starting with '('
1929 StripHighlightAndTitle (char *s)
1931 static char retbuf[MSG_SIZ];
1934 while (*s != NULLCHAR) {
1935 while (*s == '\033') {
1936 while (*s != NULLCHAR && !isalpha(*s)) s++;
1937 if (*s != NULLCHAR) s++;
1939 while (*s != NULLCHAR && *s != '\033') {
1940 if (*s == '(' || *s == '[') {
1951 /* Remove all highlighting escape sequences in s */
1953 StripHighlight (char *s)
1955 static char retbuf[MSG_SIZ];
1958 while (*s != NULLCHAR) {
1959 while (*s == '\033') {
1960 while (*s != NULLCHAR && !isalpha(*s)) s++;
1961 if (*s != NULLCHAR) s++;
1963 while (*s != NULLCHAR && *s != '\033') {
1971 char *variantNames[] = VARIANT_NAMES;
1973 VariantName (VariantClass v)
1975 return variantNames[v];
1979 /* Identify a variant from the strings the chess servers use or the
1980 PGN Variant tag names we use. */
1982 StringToVariant (char *e)
1986 VariantClass v = VariantNormal;
1987 int i, found = FALSE;
1993 /* [HGM] skip over optional board-size prefixes */
1994 if( sscanf(e, "%dx%d_", &i, &i) == 2 ||
1995 sscanf(e, "%dx%d+%d_", &i, &i, &i) == 3 ) {
1996 while( *e++ != '_');
1999 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
2003 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
2004 if (StrCaseStr(e, variantNames[i])) {
2005 v = (VariantClass) i;
2012 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
2013 || StrCaseStr(e, "wild/fr")
2014 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
2015 v = VariantFischeRandom;
2016 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
2017 (i = 1, p = StrCaseStr(e, "w"))) {
2019 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
2026 case 0: /* FICS only, actually */
2028 /* Castling legal even if K starts on d-file */
2029 v = VariantWildCastle;
2034 /* Castling illegal even if K & R happen to start in
2035 normal positions. */
2036 v = VariantNoCastle;
2049 /* Castling legal iff K & R start in normal positions */
2055 /* Special wilds for position setup; unclear what to do here */
2056 v = VariantLoadable;
2059 /* Bizarre ICC game */
2060 v = VariantTwoKings;
2063 v = VariantKriegspiel;
2069 v = VariantFischeRandom;
2072 v = VariantCrazyhouse;
2075 v = VariantBughouse;
2081 /* Not quite the same as FICS suicide! */
2082 v = VariantGiveaway;
2088 v = VariantShatranj;
2091 /* Temporary names for future ICC types. The name *will* change in
2092 the next xboard/WinBoard release after ICC defines it. */
2130 v = VariantCapablanca;
2133 v = VariantKnightmate;
2139 v = VariantCylinder;
2145 v = VariantCapaRandom;
2148 v = VariantBerolina;
2160 /* Found "wild" or "w" in the string but no number;
2161 must assume it's normal chess. */
2165 len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
2166 if( (len >= MSG_SIZ) && appData.debugMode )
2167 fprintf(debugFP, "StringToVariant: buffer truncated.\n");
2169 DisplayError(buf, 0);
2175 if (appData.debugMode) {
2176 fprintf(debugFP, _("recognized '%s' (%d) as variant %s\n"),
2177 e, wnum, VariantName(v));
2182 static int leftover_start = 0, leftover_len = 0;
2183 char star_match[STAR_MATCH_N][MSG_SIZ];
2185 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
2186 advance *index beyond it, and set leftover_start to the new value of
2187 *index; else return FALSE. If pattern contains the character '*', it
2188 matches any sequence of characters not containing '\r', '\n', or the
2189 character following the '*' (if any), and the matched sequence(s) are
2190 copied into star_match.
2193 looking_at ( char *buf, int *index, char *pattern)
2195 char *bufp = &buf[*index], *patternp = pattern;
2197 char *matchp = star_match[0];
2200 if (*patternp == NULLCHAR) {
2201 *index = leftover_start = bufp - buf;
2205 if (*bufp == NULLCHAR) return FALSE;
2206 if (*patternp == '*') {
2207 if (*bufp == *(patternp + 1)) {
2209 matchp = star_match[++star_count];
2213 } else if (*bufp == '\n' || *bufp == '\r') {
2215 if (*patternp == NULLCHAR)
2220 *matchp++ = *bufp++;
2224 if (*patternp != *bufp) return FALSE;
2231 SendToPlayer (char *data, int length)
2233 int error, outCount;
2234 outCount = OutputToProcess(NoProc, data, length, &error);
2235 if (outCount < length) {
2236 DisplayFatalError(_("Error writing to display"), error, 1);
2241 PackHolding (char packed[], char *holding)
2251 switch (runlength) {
2262 sprintf(q, "%d", runlength);
2274 /* Telnet protocol requests from the front end */
2276 TelnetRequest (unsigned char ddww, unsigned char option)
2278 unsigned char msg[3];
2279 int outCount, outError;
2281 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
2283 if (appData.debugMode) {
2284 char buf1[8], buf2[8], *ddwwStr, *optionStr;
2300 snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2309 snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2312 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2317 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2319 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2326 if (!appData.icsActive) return;
2327 TelnetRequest(TN_DO, TN_ECHO);
2333 if (!appData.icsActive) return;
2334 TelnetRequest(TN_DONT, TN_ECHO);
2338 CopyHoldings (Board board, char *holdings, ChessSquare lowestPiece)
2340 /* put the holdings sent to us by the server on the board holdings area */
2341 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2345 if(gameInfo.holdingsWidth < 2) return;
2346 if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2347 return; // prevent overwriting by pre-board holdings
2349 if( (int)lowestPiece >= BlackPawn ) {
2352 holdingsStartRow = BOARD_HEIGHT-1;
2355 holdingsColumn = BOARD_WIDTH-1;
2356 countsColumn = BOARD_WIDTH-2;
2357 holdingsStartRow = 0;
2361 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
2362 board[i][holdingsColumn] = EmptySquare;
2363 board[i][countsColumn] = (ChessSquare) 0;
2365 while( (p=*holdings++) != NULLCHAR ) {
2366 piece = CharToPiece( ToUpper(p) );
2367 if(piece == EmptySquare) continue;
2368 /*j = (int) piece - (int) WhitePawn;*/
2369 j = PieceToNumber(piece);
2370 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2371 if(j < 0) continue; /* should not happen */
2372 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2373 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2374 board[holdingsStartRow+j*direction][countsColumn]++;
2380 VariantSwitch (Board board, VariantClass newVariant)
2382 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2383 static Board oldBoard;
2385 startedFromPositionFile = FALSE;
2386 if(gameInfo.variant == newVariant) return;
2388 /* [HGM] This routine is called each time an assignment is made to
2389 * gameInfo.variant during a game, to make sure the board sizes
2390 * are set to match the new variant. If that means adding or deleting
2391 * holdings, we shift the playing board accordingly
2392 * This kludge is needed because in ICS observe mode, we get boards
2393 * of an ongoing game without knowing the variant, and learn about the
2394 * latter only later. This can be because of the move list we requested,
2395 * in which case the game history is refilled from the beginning anyway,
2396 * but also when receiving holdings of a crazyhouse game. In the latter
2397 * case we want to add those holdings to the already received position.
2401 if (appData.debugMode) {
2402 fprintf(debugFP, "Switch board from %s to %s\n",
2403 VariantName(gameInfo.variant), VariantName(newVariant));
2404 setbuf(debugFP, NULL);
2406 shuffleOpenings = 0; /* [HGM] shuffle */
2407 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2411 newWidth = 9; newHeight = 9;
2412 gameInfo.holdingsSize = 7;
2413 case VariantBughouse:
2414 case VariantCrazyhouse:
2415 newHoldingsWidth = 2; break;
2419 newHoldingsWidth = 2;
2420 gameInfo.holdingsSize = 8;
2423 case VariantCapablanca:
2424 case VariantCapaRandom:
2427 newHoldingsWidth = gameInfo.holdingsSize = 0;
2430 if(newWidth != gameInfo.boardWidth ||
2431 newHeight != gameInfo.boardHeight ||
2432 newHoldingsWidth != gameInfo.holdingsWidth ) {
2434 /* shift position to new playing area, if needed */
2435 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2436 for(i=0; i<BOARD_HEIGHT; i++)
2437 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2438 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2440 for(i=0; i<newHeight; i++) {
2441 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2442 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2444 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2445 for(i=0; i<BOARD_HEIGHT; i++)
2446 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2447 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2450 board[HOLDINGS_SET] = 0;
2451 gameInfo.boardWidth = newWidth;
2452 gameInfo.boardHeight = newHeight;
2453 gameInfo.holdingsWidth = newHoldingsWidth;
2454 gameInfo.variant = newVariant;
2455 InitDrawingSizes(-2, 0);
2456 } else gameInfo.variant = newVariant;
2457 CopyBoard(oldBoard, board); // remember correctly formatted board
2458 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2459 DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2462 static int loggedOn = FALSE;
2464 /*-- Game start info cache: --*/
2466 char gs_kind[MSG_SIZ];
2467 static char player1Name[128] = "";
2468 static char player2Name[128] = "";
2469 static char cont_seq[] = "\n\\ ";
2470 static int player1Rating = -1;
2471 static int player2Rating = -1;
2472 /*----------------------------*/
2474 ColorClass curColor = ColorNormal;
2475 int suppressKibitz = 0;
2478 Boolean soughtPending = FALSE;
2479 Boolean seekGraphUp;
2480 #define MAX_SEEK_ADS 200
2482 char *seekAdList[MAX_SEEK_ADS];
2483 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2484 float tcList[MAX_SEEK_ADS];
2485 char colorList[MAX_SEEK_ADS];
2486 int nrOfSeekAds = 0;
2487 int minRating = 1010, maxRating = 2800;
2488 int hMargin = 10, vMargin = 20, h, w;
2489 extern int squareSize, lineGap;
2494 int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2495 xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2496 if(r < minRating+100 && r >=0 ) r = minRating+100;
2497 if(r > maxRating) r = maxRating;
2498 if(tc < 1.f) tc = 1.f;
2499 if(tc > 95.f) tc = 95.f;
2500 x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2501 y = ((double)r - minRating)/(maxRating - minRating)
2502 * (h-vMargin-squareSize/8-1) + vMargin;
2503 if(ratingList[i] < 0) y = vMargin + squareSize/4;
2504 if(strstr(seekAdList[i], " u ")) color = 1;
2505 if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2506 !strstr(seekAdList[i], "bullet") &&
2507 !strstr(seekAdList[i], "blitz") &&
2508 !strstr(seekAdList[i], "standard") ) color = 2;
2509 if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2510 DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2514 AddAd (char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
2516 char buf[MSG_SIZ], *ext = "";
2517 VariantClass v = StringToVariant(type);
2518 if(strstr(type, "wild")) {
2519 ext = type + 4; // append wild number
2520 if(v == VariantFischeRandom) type = "chess960"; else
2521 if(v == VariantLoadable) type = "setup"; else
2522 type = VariantName(v);
2524 snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2525 if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2526 if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2527 ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2528 sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2529 tcList[nrOfSeekAds] = base + (2./3.)*inc;
2530 seekNrList[nrOfSeekAds] = nr;
2531 zList[nrOfSeekAds] = 0;
2532 seekAdList[nrOfSeekAds++] = StrSave(buf);
2533 if(plot) PlotSeekAd(nrOfSeekAds-1);
2538 EraseSeekDot (int i)
2540 int x = xList[i], y = yList[i], d=squareSize/4, k;
2541 DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2542 if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2543 // now replot every dot that overlapped
2544 for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2545 int xx = xList[k], yy = yList[k];
2546 if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2547 DrawSeekDot(xx, yy, colorList[k]);
2552 RemoveSeekAd (int nr)
2555 for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2557 if(seekAdList[i]) free(seekAdList[i]);
2558 seekAdList[i] = seekAdList[--nrOfSeekAds];
2559 seekNrList[i] = seekNrList[nrOfSeekAds];
2560 ratingList[i] = ratingList[nrOfSeekAds];
2561 colorList[i] = colorList[nrOfSeekAds];
2562 tcList[i] = tcList[nrOfSeekAds];
2563 xList[i] = xList[nrOfSeekAds];
2564 yList[i] = yList[nrOfSeekAds];
2565 zList[i] = zList[nrOfSeekAds];
2566 seekAdList[nrOfSeekAds] = NULL;
2572 MatchSoughtLine (char *line)
2574 char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2575 int nr, base, inc, u=0; char dummy;
2577 if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2578 sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2580 (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2581 sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
2582 // match: compact and save the line
2583 AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2593 if(!seekGraphUp) return FALSE;
2594 h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap;
2595 w = BOARD_WIDTH * (squareSize + lineGap) + lineGap;
2597 DrawSeekBackground(0, 0, w, h);
2598 DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2599 DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2600 for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2601 int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2603 DrawSeekAxis(hMargin+5*(i%500==0), yy, hMargin-5, yy); // rating ticks
2606 snprintf(buf, MSG_SIZ, "%d", i);
2607 DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2610 DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2611 for(i=1; i<100; i+=(i<10?1:5)) {
2612 int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2613 DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2614 if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2616 snprintf(buf, MSG_SIZ, "%d", i);
2617 DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2620 for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2625 SeekGraphClick (ClickType click, int x, int y, int moving)
2627 static int lastDown = 0, displayed = 0, lastSecond;
2628 if(y < 0) return FALSE;
2629 if(!(appData.seekGraph && appData.icsActive && loggedOn &&
2630 (gameMode == BeginningOfGame || gameMode == IcsIdle))) {
2631 if(!seekGraphUp) return FALSE;
2632 seekGraphUp = FALSE; // seek graph is up when it shouldn't be: take it down
2633 DrawPosition(TRUE, NULL);
2636 if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2637 if(click == Release || moving) return FALSE;
2639 soughtPending = TRUE;
2640 SendToICS(ics_prefix);
2641 SendToICS("sought\n"); // should this be "sought all"?
2642 } else { // issue challenge based on clicked ad
2643 int dist = 10000; int i, closest = 0, second = 0;
2644 for(i=0; i<nrOfSeekAds; i++) {
2645 int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
2646 if(d < dist) { dist = d; closest = i; }
2647 second += (d - zList[i] < 120); // count in-range ads
2648 if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2652 second = (second > 1);
2653 if(displayed != closest || second != lastSecond) {
2654 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2655 lastSecond = second; displayed = closest;
2657 if(click == Press) {
2658 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2661 } // on press 'hit', only show info
2662 if(moving == 2) return TRUE; // ignore right up-clicks on dot
2663 snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2664 SendToICS(ics_prefix);
2666 return TRUE; // let incoming board of started game pop down the graph
2667 } else if(click == Release) { // release 'miss' is ignored
2668 zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2669 if(moving == 2) { // right up-click
2670 nrOfSeekAds = 0; // refresh graph
2671 soughtPending = TRUE;
2672 SendToICS(ics_prefix);
2673 SendToICS("sought\n"); // should this be "sought all"?
2676 } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2677 // press miss or release hit 'pop down' seek graph
2678 seekGraphUp = FALSE;
2679 DrawPosition(TRUE, NULL);
2685 read_from_ics (InputSourceRef isr, VOIDSTAR closure, char *data, int count, int error)
2687 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2688 #define STARTED_NONE 0
2689 #define STARTED_MOVES 1
2690 #define STARTED_BOARD 2
2691 #define STARTED_OBSERVE 3
2692 #define STARTED_HOLDINGS 4
2693 #define STARTED_CHATTER 5
2694 #define STARTED_COMMENT 6
2695 #define STARTED_MOVES_NOHIDE 7
2697 static int started = STARTED_NONE;
2698 static char parse[20000];
2699 static int parse_pos = 0;
2700 static char buf[BUF_SIZE + 1];
2701 static int firstTime = TRUE, intfSet = FALSE;
2702 static ColorClass prevColor = ColorNormal;
2703 static int savingComment = FALSE;
2704 static int cmatch = 0; // continuation sequence match
2711 int backup; /* [DM] For zippy color lines */
2713 char talker[MSG_SIZ]; // [HGM] chat
2716 connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2718 if (appData.debugMode) {
2720 fprintf(debugFP, "<ICS: ");
2721 show_bytes(debugFP, data, count);
2722 fprintf(debugFP, "\n");
2726 if (appData.debugMode) { int f = forwardMostMove;
2727 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2728 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2729 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2732 /* If last read ended with a partial line that we couldn't parse,
2733 prepend it to the new read and try again. */
2734 if (leftover_len > 0) {
2735 for (i=0; i<leftover_len; i++)
2736 buf[i] = buf[leftover_start + i];
2739 /* copy new characters into the buffer */
2740 bp = buf + leftover_len;
2741 buf_len=leftover_len;
2742 for (i=0; i<count; i++)
2745 if (data[i] == '\r')
2748 // join lines split by ICS?
2749 if (!appData.noJoin)
2752 Joining just consists of finding matches against the
2753 continuation sequence, and discarding that sequence
2754 if found instead of copying it. So, until a match
2755 fails, there's nothing to do since it might be the
2756 complete sequence, and thus, something we don't want
2759 if (data[i] == cont_seq[cmatch])
2762 if (cmatch == strlen(cont_seq))
2764 cmatch = 0; // complete match. just reset the counter
2767 it's possible for the ICS to not include the space
2768 at the end of the last word, making our [correct]
2769 join operation fuse two separate words. the server
2770 does this when the space occurs at the width setting.
2772 if (!buf_len || buf[buf_len-1] != ' ')
2783 match failed, so we have to copy what matched before
2784 falling through and copying this character. In reality,
2785 this will only ever be just the newline character, but
2786 it doesn't hurt to be precise.
2788 strncpy(bp, cont_seq, cmatch);
2800 buf[buf_len] = NULLCHAR;
2801 // next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2806 while (i < buf_len) {
2807 /* Deal with part of the TELNET option negotiation
2808 protocol. We refuse to do anything beyond the
2809 defaults, except that we allow the WILL ECHO option,
2810 which ICS uses to turn off password echoing when we are
2811 directly connected to it. We reject this option
2812 if localLineEditing mode is on (always on in xboard)
2813 and we are talking to port 23, which might be a real
2814 telnet server that will try to keep WILL ECHO on permanently.
2816 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2817 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2818 unsigned char option;
2820 switch ((unsigned char) buf[++i]) {
2822 if (appData.debugMode)
2823 fprintf(debugFP, "\n<WILL ");
2824 switch (option = (unsigned char) buf[++i]) {
2826 if (appData.debugMode)
2827 fprintf(debugFP, "ECHO ");
2828 /* Reply only if this is a change, according
2829 to the protocol rules. */
2830 if (remoteEchoOption) break;
2831 if (appData.localLineEditing &&
2832 atoi(appData.icsPort) == TN_PORT) {
2833 TelnetRequest(TN_DONT, TN_ECHO);
2836 TelnetRequest(TN_DO, TN_ECHO);
2837 remoteEchoOption = TRUE;
2841 if (appData.debugMode)
2842 fprintf(debugFP, "%d ", option);
2843 /* Whatever this is, we don't want it. */
2844 TelnetRequest(TN_DONT, option);
2849 if (appData.debugMode)
2850 fprintf(debugFP, "\n<WONT ");
2851 switch (option = (unsigned char) buf[++i]) {
2853 if (appData.debugMode)
2854 fprintf(debugFP, "ECHO ");
2855 /* Reply only if this is a change, according
2856 to the protocol rules. */
2857 if (!remoteEchoOption) break;
2859 TelnetRequest(TN_DONT, TN_ECHO);
2860 remoteEchoOption = FALSE;
2863 if (appData.debugMode)
2864 fprintf(debugFP, "%d ", (unsigned char) option);
2865 /* Whatever this is, it must already be turned
2866 off, because we never agree to turn on
2867 anything non-default, so according to the
2868 protocol rules, we don't reply. */
2873 if (appData.debugMode)
2874 fprintf(debugFP, "\n<DO ");
2875 switch (option = (unsigned char) buf[++i]) {
2877 /* Whatever this is, we refuse to do it. */
2878 if (appData.debugMode)
2879 fprintf(debugFP, "%d ", option);
2880 TelnetRequest(TN_WONT, option);
2885 if (appData.debugMode)
2886 fprintf(debugFP, "\n<DONT ");
2887 switch (option = (unsigned char) buf[++i]) {
2889 if (appData.debugMode)
2890 fprintf(debugFP, "%d ", option);
2891 /* Whatever this is, we are already not doing
2892 it, because we never agree to do anything
2893 non-default, so according to the protocol
2894 rules, we don't reply. */
2899 if (appData.debugMode)
2900 fprintf(debugFP, "\n<IAC ");
2901 /* Doubled IAC; pass it through */
2905 if (appData.debugMode)
2906 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
2907 /* Drop all other telnet commands on the floor */
2910 if (oldi > next_out)
2911 SendToPlayer(&buf[next_out], oldi - next_out);
2917 /* OK, this at least will *usually* work */
2918 if (!loggedOn && looking_at(buf, &i, "ics%")) {
2922 if (loggedOn && !intfSet) {
2923 if (ics_type == ICS_ICC) {
2924 snprintf(str, MSG_SIZ,
2925 "/set-quietly interface %s\n/set-quietly style 12\n",
2927 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2928 strcat(str, "/set-2 51 1\n/set seek 1\n");
2929 } else if (ics_type == ICS_CHESSNET) {
2930 snprintf(str, MSG_SIZ, "/style 12\n");
2932 safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
2933 strcat(str, programVersion);
2934 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
2935 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
2936 strcat(str, "$iset seekremove 1\n$set seek 1\n");
2938 strcat(str, "$iset nohighlight 1\n");
2940 strcat(str, "$iset lock 1\n$style 12\n");
2943 NotifyFrontendLogin();
2947 if (started == STARTED_COMMENT) {
2948 /* Accumulate characters in comment */
2949 parse[parse_pos++] = buf[i];
2950 if (buf[i] == '\n') {
2951 parse[parse_pos] = NULLCHAR;
2952 if(chattingPartner>=0) {
2954 snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
2955 OutputChatMessage(chattingPartner, mess);
2956 chattingPartner = -1;
2957 next_out = i+1; // [HGM] suppress printing in ICS window
2959 if(!suppressKibitz) // [HGM] kibitz
2960 AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
2961 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
2962 int nrDigit = 0, nrAlph = 0, j;
2963 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
2964 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
2965 parse[parse_pos] = NULLCHAR;
2966 // try to be smart: if it does not look like search info, it should go to
2967 // ICS interaction window after all, not to engine-output window.
2968 for(j=0; j<parse_pos; j++) { // count letters and digits
2969 nrDigit += (parse[j] >= '0' && parse[j] <= '9');
2970 nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
2971 nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
2973 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
2974 int depth=0; float score;
2975 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
2976 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
2977 pvInfoList[forwardMostMove-1].depth = depth;
2978 pvInfoList[forwardMostMove-1].score = 100*score;
2980 OutputKibitz(suppressKibitz, parse);
2983 if(gameMode == IcsObserving) // restore original ICS messages
2984 snprintf(tmp, MSG_SIZ, "%s kibitzes: %s", star_match[0], parse);
2986 snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
2987 SendToPlayer(tmp, strlen(tmp));
2989 next_out = i+1; // [HGM] suppress printing in ICS window
2991 started = STARTED_NONE;
2993 /* Don't match patterns against characters in comment */
2998 if (started == STARTED_CHATTER) {
2999 if (buf[i] != '\n') {
3000 /* Don't match patterns against characters in chatter */
3004 started = STARTED_NONE;
3005 if(suppressKibitz) next_out = i+1;
3008 /* Kludge to deal with rcmd protocol */
3009 if (firstTime && looking_at(buf, &i, "\001*")) {
3010 DisplayFatalError(&buf[1], 0, 1);
3016 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
3019 if (appData.debugMode)
3020 fprintf(debugFP, "ics_type %d\n", ics_type);
3023 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
3024 ics_type = ICS_FICS;
3026 if (appData.debugMode)
3027 fprintf(debugFP, "ics_type %d\n", ics_type);
3030 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
3031 ics_type = ICS_CHESSNET;
3033 if (appData.debugMode)
3034 fprintf(debugFP, "ics_type %d\n", ics_type);
3039 (looking_at(buf, &i, "\"*\" is *a registered name") ||
3040 looking_at(buf, &i, "Logging you in as \"*\"") ||
3041 looking_at(buf, &i, "will be \"*\""))) {
3042 safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
3046 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
3048 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
3049 DisplayIcsInteractionTitle(buf);
3050 have_set_title = TRUE;
3053 /* skip finger notes */
3054 if (started == STARTED_NONE &&
3055 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
3056 (buf[i] == '1' && buf[i+1] == '0')) &&
3057 buf[i+2] == ':' && buf[i+3] == ' ') {
3058 started = STARTED_CHATTER;
3064 // [HGM] seekgraph: recognize sought lines and end-of-sought message
3065 if(appData.seekGraph) {
3066 if(soughtPending && MatchSoughtLine(buf+i)) {
3067 i = strstr(buf+i, "rated") - buf;
3068 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3069 next_out = leftover_start = i;
3070 started = STARTED_CHATTER;
3071 suppressKibitz = TRUE;
3074 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
3075 && looking_at(buf, &i, "* ads displayed")) {
3076 soughtPending = FALSE;
3081 if(appData.autoRefresh) {
3082 if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
3083 int s = (ics_type == ICS_ICC); // ICC format differs
3085 AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
3086 star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
3087 looking_at(buf, &i, "*% "); // eat prompt
3088 if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
3089 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3090 next_out = i; // suppress
3093 if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
3094 char *p = star_match[0];
3096 if(seekGraphUp) RemoveSeekAd(atoi(p));
3097 while(*p && *p++ != ' '); // next
3099 looking_at(buf, &i, "*% "); // eat prompt
3100 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3107 /* skip formula vars */
3108 if (started == STARTED_NONE &&
3109 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
3110 started = STARTED_CHATTER;
3115 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
3116 if (appData.autoKibitz && started == STARTED_NONE &&
3117 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
3118 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
3119 if((looking_at(buf, &i, "\n* kibitzes: ") || looking_at(buf, &i, "\n* whispers: ") ||
3120 looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
3121 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
3122 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
3123 suppressKibitz = TRUE;
3124 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3126 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
3127 && (gameMode == IcsPlayingWhite)) ||
3128 (StrStr(star_match[0], gameInfo.black) == star_match[0]
3129 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
3130 started = STARTED_CHATTER; // own kibitz we simply discard
3132 started = STARTED_COMMENT; // make sure it will be collected in parse[]
3133 parse_pos = 0; parse[0] = NULLCHAR;
3134 savingComment = TRUE;
3135 suppressKibitz = gameMode != IcsObserving ? 2 :
3136 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
3140 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
3141 looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
3142 && atoi(star_match[0])) {
3143 // suppress the acknowledgements of our own autoKibitz
3145 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3146 if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
3147 SendToPlayer(star_match[0], strlen(star_match[0]));
3148 if(looking_at(buf, &i, "*% ")) // eat prompt
3149 suppressKibitz = FALSE;
3153 } // [HGM] kibitz: end of patch
3155 if(looking_at(buf, &i, "* rating adjustment: * --> *\n")) continue;
3157 // [HGM] chat: intercept tells by users for which we have an open chat window
3159 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
3160 looking_at(buf, &i, "* whispers:") ||
3161 looking_at(buf, &i, "* kibitzes:") ||
3162 looking_at(buf, &i, "* shouts:") ||
3163 looking_at(buf, &i, "* c-shouts:") ||
3164 looking_at(buf, &i, "--> * ") ||
3165 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
3166 looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
3167 looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
3168 looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
3170 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
3171 chattingPartner = -1;
3173 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
3174 for(p=0; p<MAX_CHAT; p++) {
3175 if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
3176 talker[0] = '['; strcat(talker, "] ");
3177 Colorize(channel == 1 ? ColorChannel1 : ColorChannel, FALSE);
3178 chattingPartner = p; break;
3181 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
3182 for(p=0; p<MAX_CHAT; p++) {
3183 if(!strcmp("kibitzes", chatPartner[p])) {
3184 talker[0] = '['; strcat(talker, "] ");
3185 chattingPartner = p; break;
3188 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
3189 for(p=0; p<MAX_CHAT; p++) {
3190 if(!strcmp("whispers", chatPartner[p])) {
3191 talker[0] = '['; strcat(talker, "] ");
3192 chattingPartner = p; break;
3195 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
3196 if(buf[i-8] == '-' && buf[i-3] == 't')
3197 for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
3198 if(!strcmp("c-shouts", chatPartner[p])) {
3199 talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
3200 chattingPartner = p; break;
3203 if(chattingPartner < 0)
3204 for(p=0; p<MAX_CHAT; p++) {
3205 if(!strcmp("shouts", chatPartner[p])) {
3206 if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
3207 else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
3208 else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
3209 chattingPartner = p; break;
3213 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
3214 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
3215 talker[0] = 0; Colorize(ColorTell, FALSE);
3216 chattingPartner = p; break;
3218 if(chattingPartner<0) i = oldi; else {
3219 Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
3220 if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
3221 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3222 started = STARTED_COMMENT;
3223 parse_pos = 0; parse[0] = NULLCHAR;
3224 savingComment = 3 + chattingPartner; // counts as TRUE
3225 suppressKibitz = TRUE;
3228 } // [HGM] chat: end of patch
3231 if (appData.zippyTalk || appData.zippyPlay) {
3232 /* [DM] Backup address for color zippy lines */
3234 if (loggedOn == TRUE)
3235 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
3236 (appData.zippyPlay && ZippyMatch(buf, &backup)));
3238 } // [DM] 'else { ' deleted
3240 /* Regular tells and says */
3241 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
3242 looking_at(buf, &i, "* (your partner) tells you: ") ||
3243 looking_at(buf, &i, "* says: ") ||
3244 /* Don't color "message" or "messages" output */
3245 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
3246 looking_at(buf, &i, "*. * at *:*: ") ||
3247 looking_at(buf, &i, "--* (*:*): ") ||
3248 /* Message notifications (same color as tells) */
3249 looking_at(buf, &i, "* has left a message ") ||
3250 looking_at(buf, &i, "* just sent you a message:\n") ||
3251 /* Whispers and kibitzes */
3252 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
3253 looking_at(buf, &i, "* kibitzes: ") ||
3255 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
3257 if (tkind == 1 && strchr(star_match[0], ':')) {
3258 /* Avoid "tells you:" spoofs in channels */
3261 if (star_match[0][0] == NULLCHAR ||
3262 strchr(star_match[0], ' ') ||
3263 (tkind == 3 && strchr(star_match[1], ' '))) {
3264 /* Reject bogus matches */
3267 if (appData.colorize) {
3268 if (oldi > next_out) {
3269 SendToPlayer(&buf[next_out], oldi - next_out);
3274 Colorize(ColorTell, FALSE);
3275 curColor = ColorTell;
3278 Colorize(ColorKibitz, FALSE);
3279 curColor = ColorKibitz;
3282 p = strrchr(star_match[1], '(');
3289 Colorize(ColorChannel1, FALSE);
3290 curColor = ColorChannel1;
3292 Colorize(ColorChannel, FALSE);
3293 curColor = ColorChannel;
3297 curColor = ColorNormal;
3301 if (started == STARTED_NONE && appData.autoComment &&
3302 (gameMode == IcsObserving ||
3303 gameMode == IcsPlayingWhite ||
3304 gameMode == IcsPlayingBlack)) {
3305 parse_pos = i - oldi;
3306 memcpy(parse, &buf[oldi], parse_pos);
3307 parse[parse_pos] = NULLCHAR;
3308 started = STARTED_COMMENT;
3309 savingComment = TRUE;
3311 started = STARTED_CHATTER;
3312 savingComment = FALSE;
3319 if (looking_at(buf, &i, "* s-shouts: ") ||
3320 looking_at(buf, &i, "* c-shouts: ")) {
3321 if (appData.colorize) {
3322 if (oldi > next_out) {
3323 SendToPlayer(&buf[next_out], oldi - next_out);
3326 Colorize(ColorSShout, FALSE);
3327 curColor = ColorSShout;
3330 started = STARTED_CHATTER;
3334 if (looking_at(buf, &i, "--->")) {
3339 if (looking_at(buf, &i, "* shouts: ") ||
3340 looking_at(buf, &i, "--> ")) {
3341 if (appData.colorize) {
3342 if (oldi > next_out) {
3343 SendToPlayer(&buf[next_out], oldi - next_out);
3346 Colorize(ColorShout, FALSE);
3347 curColor = ColorShout;
3350 started = STARTED_CHATTER;
3354 if (looking_at( buf, &i, "Challenge:")) {
3355 if (appData.colorize) {
3356 if (oldi > next_out) {
3357 SendToPlayer(&buf[next_out], oldi - next_out);
3360 Colorize(ColorChallenge, FALSE);
3361 curColor = ColorChallenge;
3367 if (looking_at(buf, &i, "* offers you") ||
3368 looking_at(buf, &i, "* offers to be") ||
3369 looking_at(buf, &i, "* would like to") ||
3370 looking_at(buf, &i, "* requests to") ||
3371 looking_at(buf, &i, "Your opponent offers") ||
3372 looking_at(buf, &i, "Your opponent requests")) {
3374 if (appData.colorize) {
3375 if (oldi > next_out) {
3376 SendToPlayer(&buf[next_out], oldi - next_out);
3379 Colorize(ColorRequest, FALSE);
3380 curColor = ColorRequest;
3385 if (looking_at(buf, &i, "* (*) seeking")) {
3386 if (appData.colorize) {
3387 if (oldi > next_out) {
3388 SendToPlayer(&buf[next_out], oldi - next_out);
3391 Colorize(ColorSeek, FALSE);
3392 curColor = ColorSeek;
3397 if(i < backup) { i = backup; continue; } // [HGM] for if ZippyControl matches, but the colorie code doesn't
3399 if (looking_at(buf, &i, "\\ ")) {
3400 if (prevColor != ColorNormal) {
3401 if (oldi > next_out) {
3402 SendToPlayer(&buf[next_out], oldi - next_out);
3405 Colorize(prevColor, TRUE);
3406 curColor = prevColor;
3408 if (savingComment) {
3409 parse_pos = i - oldi;
3410 memcpy(parse, &buf[oldi], parse_pos);
3411 parse[parse_pos] = NULLCHAR;
3412 started = STARTED_COMMENT;
3413 if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3414 chattingPartner = savingComment - 3; // kludge to remember the box
3416 started = STARTED_CHATTER;
3421 if (looking_at(buf, &i, "Black Strength :") ||
3422 looking_at(buf, &i, "<<< style 10 board >>>") ||
3423 looking_at(buf, &i, "<10>") ||
3424 looking_at(buf, &i, "#@#")) {
3425 /* Wrong board style */
3427 SendToICS(ics_prefix);
3428 SendToICS("set style 12\n");
3429 SendToICS(ics_prefix);
3430 SendToICS("refresh\n");
3434 if (!have_sent_ICS_logon && looking_at(buf, &i, "login:")) {
3436 have_sent_ICS_logon = 1;
3440 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3441 (looking_at(buf, &i, "\n<12> ") ||
3442 looking_at(buf, &i, "<12> "))) {
3444 if (oldi > next_out) {
3445 SendToPlayer(&buf[next_out], oldi - next_out);
3448 started = STARTED_BOARD;
3453 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3454 looking_at(buf, &i, "<b1> ")) {
3455 if (oldi > next_out) {
3456 SendToPlayer(&buf[next_out], oldi - next_out);
3459 started = STARTED_HOLDINGS;
3464 if (looking_at(buf, &i, "* *vs. * *--- *")) {
3466 /* Header for a move list -- first line */
3468 switch (ics_getting_history) {
3472 case BeginningOfGame:
3473 /* User typed "moves" or "oldmoves" while we
3474 were idle. Pretend we asked for these
3475 moves and soak them up so user can step
3476 through them and/or save them.
3479 gameMode = IcsObserving;
3482 ics_getting_history = H_GOT_UNREQ_HEADER;
3484 case EditGame: /*?*/
3485 case EditPosition: /*?*/
3486 /* Should above feature work in these modes too? */
3487 /* For now it doesn't */
3488 ics_getting_history = H_GOT_UNWANTED_HEADER;
3491 ics_getting_history = H_GOT_UNWANTED_HEADER;
3496 /* Is this the right one? */
3497 if (gameInfo.white && gameInfo.black &&
3498 strcmp(gameInfo.white, star_match[0]) == 0 &&
3499 strcmp(gameInfo.black, star_match[2]) == 0) {
3501 ics_getting_history = H_GOT_REQ_HEADER;
3504 case H_GOT_REQ_HEADER:
3505 case H_GOT_UNREQ_HEADER:
3506 case H_GOT_UNWANTED_HEADER:
3507 case H_GETTING_MOVES:
3508 /* Should not happen */
3509 DisplayError(_("Error gathering move list: two headers"), 0);
3510 ics_getting_history = H_FALSE;
3514 /* Save player ratings into gameInfo if needed */
3515 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3516 ics_getting_history == H_GOT_UNREQ_HEADER) &&
3517 (gameInfo.whiteRating == -1 ||
3518 gameInfo.blackRating == -1)) {
3520 gameInfo.whiteRating = string_to_rating(star_match[1]);
3521 gameInfo.blackRating = string_to_rating(star_match[3]);
3522 if (appData.debugMode)
3523 fprintf(debugFP, _("Ratings from header: W %d, B %d\n"),
3524 gameInfo.whiteRating, gameInfo.blackRating);
3529 if (looking_at(buf, &i,
3530 "* * match, initial time: * minute*, increment: * second")) {
3531 /* Header for a move list -- second line */
3532 /* Initial board will follow if this is a wild game */
3533 if (gameInfo.event != NULL) free(gameInfo.event);
3534 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3535 gameInfo.event = StrSave(str);
3536 /* [HGM] we switched variant. Translate boards if needed. */
3537 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3541 if (looking_at(buf, &i, "Move ")) {
3542 /* Beginning of a move list */
3543 switch (ics_getting_history) {
3545 /* Normally should not happen */
3546 /* Maybe user hit reset while we were parsing */
3549 /* Happens if we are ignoring a move list that is not
3550 * the one we just requested. Common if the user
3551 * tries to observe two games without turning off
3554 case H_GETTING_MOVES:
3555 /* Should not happen */
3556 DisplayError(_("Error gathering move list: nested"), 0);
3557 ics_getting_history = H_FALSE;
3559 case H_GOT_REQ_HEADER:
3560 ics_getting_history = H_GETTING_MOVES;
3561 started = STARTED_MOVES;
3563 if (oldi > next_out) {
3564 SendToPlayer(&buf[next_out], oldi - next_out);
3567 case H_GOT_UNREQ_HEADER:
3568 ics_getting_history = H_GETTING_MOVES;
3569 started = STARTED_MOVES_NOHIDE;
3572 case H_GOT_UNWANTED_HEADER:
3573 ics_getting_history = H_FALSE;
3579 if (looking_at(buf, &i, "% ") ||
3580 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3581 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3582 if(soughtPending && nrOfSeekAds) { // [HGM] seekgraph: on ICC sought-list has no termination line
3583 soughtPending = FALSE;
3587 if(suppressKibitz) next_out = i;
3588 savingComment = FALSE;
3592 case STARTED_MOVES_NOHIDE:
3593 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3594 parse[parse_pos + i - oldi] = NULLCHAR;
3595 ParseGameHistory(parse);
3597 if (appData.zippyPlay && first.initDone) {
3598 FeedMovesToProgram(&first, forwardMostMove);
3599 if (gameMode == IcsPlayingWhite) {
3600 if (WhiteOnMove(forwardMostMove)) {
3601 if (first.sendTime) {
3602 if (first.useColors) {
3603 SendToProgram("black\n", &first);
3605 SendTimeRemaining(&first, TRUE);
3607 if (first.useColors) {
3608 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3610 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3611 first.maybeThinking = TRUE;
3613 if (first.usePlayother) {
3614 if (first.sendTime) {
3615 SendTimeRemaining(&first, TRUE);
3617 SendToProgram("playother\n", &first);
3623 } else if (gameMode == IcsPlayingBlack) {
3624 if (!WhiteOnMove(forwardMostMove)) {
3625 if (first.sendTime) {
3626 if (first.useColors) {
3627 SendToProgram("white\n", &first);
3629 SendTimeRemaining(&first, FALSE);
3631 if (first.useColors) {
3632 SendToProgram("black\n", &first);
3634 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3635 first.maybeThinking = TRUE;
3637 if (first.usePlayother) {
3638 if (first.sendTime) {
3639 SendTimeRemaining(&first, FALSE);
3641 SendToProgram("playother\n", &first);
3650 if (gameMode == IcsObserving && ics_gamenum == -1) {
3651 /* Moves came from oldmoves or moves command
3652 while we weren't doing anything else.
3654 currentMove = forwardMostMove;
3655 ClearHighlights();/*!!could figure this out*/
3656 flipView = appData.flipView;
3657 DrawPosition(TRUE, boards[currentMove]);
3658 DisplayBothClocks();
3659 snprintf(str, MSG_SIZ, "%s %s %s",
3660 gameInfo.white, _("vs."), gameInfo.black);
3664 /* Moves were history of an active game */
3665 if (gameInfo.resultDetails != NULL) {
3666 free(gameInfo.resultDetails);
3667 gameInfo.resultDetails = NULL;
3670 HistorySet(parseList, backwardMostMove,
3671 forwardMostMove, currentMove-1);
3672 DisplayMove(currentMove - 1);
3673 if (started == STARTED_MOVES) next_out = i;
3674 started = STARTED_NONE;
3675 ics_getting_history = H_FALSE;
3678 case STARTED_OBSERVE:
3679 started = STARTED_NONE;
3680 SendToICS(ics_prefix);
3681 SendToICS("refresh\n");
3687 if(bookHit) { // [HGM] book: simulate book reply
3688 static char bookMove[MSG_SIZ]; // a bit generous?
3690 programStats.nodes = programStats.depth = programStats.time =
3691 programStats.score = programStats.got_only_move = 0;
3692 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3694 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3695 strcat(bookMove, bookHit);
3696 HandleMachineMove(bookMove, &first);
3701 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3702 started == STARTED_HOLDINGS ||
3703 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3704 /* Accumulate characters in move list or board */
3705 parse[parse_pos++] = buf[i];
3708 /* Start of game messages. Mostly we detect start of game
3709 when the first board image arrives. On some versions
3710 of the ICS, though, we need to do a "refresh" after starting
3711 to observe in order to get the current board right away. */
3712 if (looking_at(buf, &i, "Adding game * to observation list")) {
3713 started = STARTED_OBSERVE;
3717 /* Handle auto-observe */
3718 if (appData.autoObserve &&
3719 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3720 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3722 /* Choose the player that was highlighted, if any. */
3723 if (star_match[0][0] == '\033' ||
3724 star_match[1][0] != '\033') {
3725 player = star_match[0];
3727 player = star_match[2];
3729 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3730 ics_prefix, StripHighlightAndTitle(player));
3733 /* Save ratings from notify string */
3734 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3735 player1Rating = string_to_rating(star_match[1]);
3736 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3737 player2Rating = string_to_rating(star_match[3]);
3739 if (appData.debugMode)
3741 "Ratings from 'Game notification:' %s %d, %s %d\n",
3742 player1Name, player1Rating,
3743 player2Name, player2Rating);
3748 /* Deal with automatic examine mode after a game,
3749 and with IcsObserving -> IcsExamining transition */
3750 if (looking_at(buf, &i, "Entering examine mode for game *") ||
3751 looking_at(buf, &i, "has made you an examiner of game *")) {
3753 int gamenum = atoi(star_match[0]);
3754 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3755 gamenum == ics_gamenum) {
3756 /* We were already playing or observing this game;
3757 no need to refetch history */
3758 gameMode = IcsExamining;
3760 pauseExamForwardMostMove = forwardMostMove;
3761 } else if (currentMove < forwardMostMove) {
3762 ForwardInner(forwardMostMove);
3765 /* I don't think this case really can happen */
3766 SendToICS(ics_prefix);
3767 SendToICS("refresh\n");
3772 /* Error messages */
3773 // if (ics_user_moved) {
3774 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3775 if (looking_at(buf, &i, "Illegal move") ||
3776 looking_at(buf, &i, "Not a legal move") ||
3777 looking_at(buf, &i, "Your king is in check") ||
3778 looking_at(buf, &i, "It isn't your turn") ||
3779 looking_at(buf, &i, "It is not your move")) {
3781 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3782 currentMove = forwardMostMove-1;
3783 DisplayMove(currentMove - 1); /* before DMError */
3784 DrawPosition(FALSE, boards[currentMove]);
3785 SwitchClocks(forwardMostMove-1); // [HGM] race
3786 DisplayBothClocks();
3788 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3794 if (looking_at(buf, &i, "still have time") ||
3795 looking_at(buf, &i, "not out of time") ||
3796 looking_at(buf, &i, "either player is out of time") ||
3797 looking_at(buf, &i, "has timeseal; checking")) {
3798 /* We must have called his flag a little too soon */
3799 whiteFlag = blackFlag = FALSE;
3803 if (looking_at(buf, &i, "added * seconds to") ||
3804 looking_at(buf, &i, "seconds were added to")) {
3805 /* Update the clocks */
3806 SendToICS(ics_prefix);
3807 SendToICS("refresh\n");
3811 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3812 ics_clock_paused = TRUE;
3817 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3818 ics_clock_paused = FALSE;
3823 /* Grab player ratings from the Creating: message.
3824 Note we have to check for the special case when
3825 the ICS inserts things like [white] or [black]. */
3826 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3827 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3829 0 player 1 name (not necessarily white)
3831 2 empty, white, or black (IGNORED)
3832 3 player 2 name (not necessarily black)
3835 The names/ratings are sorted out when the game
3836 actually starts (below).
3838 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
3839 player1Rating = string_to_rating(star_match[1]);
3840 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
3841 player2Rating = string_to_rating(star_match[4]);
3843 if (appData.debugMode)
3845 "Ratings from 'Creating:' %s %d, %s %d\n",
3846 player1Name, player1Rating,
3847 player2Name, player2Rating);
3852 /* Improved generic start/end-of-game messages */
3853 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
3854 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
3855 /* If tkind == 0: */
3856 /* star_match[0] is the game number */
3857 /* [1] is the white player's name */
3858 /* [2] is the black player's name */
3859 /* For end-of-game: */
3860 /* [3] is the reason for the game end */
3861 /* [4] is a PGN end game-token, preceded by " " */
3862 /* For start-of-game: */
3863 /* [3] begins with "Creating" or "Continuing" */
3864 /* [4] is " *" or empty (don't care). */
3865 int gamenum = atoi(star_match[0]);
3866 char *whitename, *blackname, *why, *endtoken;
3867 ChessMove endtype = EndOfFile;
3870 whitename = star_match[1];
3871 blackname = star_match[2];
3872 why = star_match[3];
3873 endtoken = star_match[4];
3875 whitename = star_match[1];
3876 blackname = star_match[3];
3877 why = star_match[5];
3878 endtoken = star_match[6];
3881 /* Game start messages */
3882 if (strncmp(why, "Creating ", 9) == 0 ||
3883 strncmp(why, "Continuing ", 11) == 0) {
3884 gs_gamenum = gamenum;
3885 safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
3886 if(ics_gamenum == -1) // [HGM] only if we are not already involved in a game (because gin=1 sends us such messages)
3887 VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
3889 if (appData.zippyPlay) {
3890 ZippyGameStart(whitename, blackname);
3893 partnerBoardValid = FALSE; // [HGM] bughouse
3897 /* Game end messages */
3898 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
3899 ics_gamenum != gamenum) {
3902 while (endtoken[0] == ' ') endtoken++;
3903 switch (endtoken[0]) {
3906 endtype = GameUnfinished;
3909 endtype = BlackWins;
3912 if (endtoken[1] == '/')
3913 endtype = GameIsDrawn;
3915 endtype = WhiteWins;
3918 GameEnds(endtype, why, GE_ICS);
3920 if (appData.zippyPlay && first.initDone) {
3921 ZippyGameEnd(endtype, why);
3922 if (first.pr == NoProc) {
3923 /* Start the next process early so that we'll
3924 be ready for the next challenge */
3925 StartChessProgram(&first);
3927 /* Send "new" early, in case this command takes
3928 a long time to finish, so that we'll be ready
3929 for the next challenge. */
3930 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
3934 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
3938 if (looking_at(buf, &i, "Removing game * from observation") ||
3939 looking_at(buf, &i, "no longer observing game *") ||
3940 looking_at(buf, &i, "Game * (*) has no examiners")) {
3941 if (gameMode == IcsObserving &&
3942 atoi(star_match[0]) == ics_gamenum)
3944 /* icsEngineAnalyze */
3945 if (appData.icsEngineAnalyze) {
3952 ics_user_moved = FALSE;
3957 if (looking_at(buf, &i, "no longer examining game *")) {
3958 if (gameMode == IcsExamining &&
3959 atoi(star_match[0]) == ics_gamenum)
3963 ics_user_moved = FALSE;
3968 /* Advance leftover_start past any newlines we find,
3969 so only partial lines can get reparsed */
3970 if (looking_at(buf, &i, "\n")) {
3971 prevColor = curColor;
3972 if (curColor != ColorNormal) {
3973 if (oldi > next_out) {
3974 SendToPlayer(&buf[next_out], oldi - next_out);
3977 Colorize(ColorNormal, FALSE);
3978 curColor = ColorNormal;
3980 if (started == STARTED_BOARD) {
3981 started = STARTED_NONE;
3982 parse[parse_pos] = NULLCHAR;
3983 ParseBoard12(parse);
3986 /* Send premove here */
3987 if (appData.premove) {
3989 if (currentMove == 0 &&
3990 gameMode == IcsPlayingWhite &&
3991 appData.premoveWhite) {
3992 snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
3993 if (appData.debugMode)
3994 fprintf(debugFP, "Sending premove:\n");
3996 } else if (currentMove == 1 &&
3997 gameMode == IcsPlayingBlack &&
3998 appData.premoveBlack) {
3999 snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
4000 if (appData.debugMode)
4001 fprintf(debugFP, "Sending premove:\n");
4003 } else if (gotPremove) {
4005 ClearPremoveHighlights();
4006 if (appData.debugMode)
4007 fprintf(debugFP, "Sending premove:\n");
4008 UserMoveEvent(premoveFromX, premoveFromY,
4009 premoveToX, premoveToY,
4014 /* Usually suppress following prompt */
4015 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
4016 while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
4017 if (looking_at(buf, &i, "*% ")) {
4018 savingComment = FALSE;
4023 } else if (started == STARTED_HOLDINGS) {
4025 char new_piece[MSG_SIZ];
4026 started = STARTED_NONE;
4027 parse[parse_pos] = NULLCHAR;
4028 if (appData.debugMode)
4029 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
4030 parse, currentMove);
4031 if (sscanf(parse, " game %d", &gamenum) == 1) {
4032 if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
4033 if (gameInfo.variant == VariantNormal) {
4034 /* [HGM] We seem to switch variant during a game!
4035 * Presumably no holdings were displayed, so we have
4036 * to move the position two files to the right to
4037 * create room for them!
4039 VariantClass newVariant;
4040 switch(gameInfo.boardWidth) { // base guess on board width
4041 case 9: newVariant = VariantShogi; break;
4042 case 10: newVariant = VariantGreat; break;
4043 default: newVariant = VariantCrazyhouse; break;
4045 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4046 /* Get a move list just to see the header, which
4047 will tell us whether this is really bug or zh */
4048 if (ics_getting_history == H_FALSE) {
4049 ics_getting_history = H_REQUESTED;
4050 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4054 new_piece[0] = NULLCHAR;
4055 sscanf(parse, "game %d white [%s black [%s <- %s",
4056 &gamenum, white_holding, black_holding,
4058 white_holding[strlen(white_holding)-1] = NULLCHAR;
4059 black_holding[strlen(black_holding)-1] = NULLCHAR;
4060 /* [HGM] copy holdings to board holdings area */
4061 CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
4062 CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
4063 boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
4065 if (appData.zippyPlay && first.initDone) {
4066 ZippyHoldings(white_holding, black_holding,
4070 if (tinyLayout || smallLayout) {
4071 char wh[16], bh[16];
4072 PackHolding(wh, white_holding);
4073 PackHolding(bh, black_holding);
4074 snprintf(str, MSG_SIZ, "[%s-%s] %s-%s", wh, bh,
4075 gameInfo.white, gameInfo.black);
4077 snprintf(str, MSG_SIZ, "%s [%s] %s %s [%s]",
4078 gameInfo.white, white_holding, _("vs."),
4079 gameInfo.black, black_holding);
4081 if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
4082 DrawPosition(FALSE, boards[currentMove]);
4084 } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
4085 sscanf(parse, "game %d white [%s black [%s <- %s",
4086 &gamenum, white_holding, black_holding,
4088 white_holding[strlen(white_holding)-1] = NULLCHAR;
4089 black_holding[strlen(black_holding)-1] = NULLCHAR;
4090 /* [HGM] copy holdings to partner-board holdings area */
4091 CopyHoldings(partnerBoard, white_holding, WhitePawn);
4092 CopyHoldings(partnerBoard, black_holding, BlackPawn);
4093 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
4094 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4095 if(twoBoards) { partnerUp = 0; flipView = !flipView; }
4098 /* Suppress following prompt */
4099 if (looking_at(buf, &i, "*% ")) {
4100 if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
4101 savingComment = FALSE;
4109 i++; /* skip unparsed character and loop back */
4112 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
4113 // started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
4114 // SendToPlayer(&buf[next_out], i - next_out);
4115 started != STARTED_HOLDINGS && leftover_start > next_out) {
4116 SendToPlayer(&buf[next_out], leftover_start - next_out);
4120 leftover_len = buf_len - leftover_start;
4121 /* if buffer ends with something we couldn't parse,
4122 reparse it after appending the next read */
4124 } else if (count == 0) {
4125 RemoveInputSource(isr);
4126 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
4128 DisplayFatalError(_("Error reading from ICS"), error, 1);
4133 /* Board style 12 looks like this:
4135 <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
4137 * The "<12> " is stripped before it gets to this routine. The two
4138 * trailing 0's (flip state and clock ticking) are later addition, and
4139 * some chess servers may not have them, or may have only the first.
4140 * Additional trailing fields may be added in the future.
4143 #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"
4145 #define RELATION_OBSERVING_PLAYED 0
4146 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
4147 #define RELATION_PLAYING_MYMOVE 1
4148 #define RELATION_PLAYING_NOTMYMOVE -1
4149 #define RELATION_EXAMINING 2
4150 #define RELATION_ISOLATED_BOARD -3
4151 #define RELATION_STARTING_POSITION -4 /* FICS only */
4154 ParseBoard12 (char *string)
4156 GameMode newGameMode;
4157 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0, i;
4158 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time, takeback;
4159 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
4160 char to_play, board_chars[200];
4161 char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
4162 char black[32], white[32];
4164 int prevMove = currentMove;
4167 int fromX, fromY, toX, toY;
4169 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
4170 char *bookHit = NULL; // [HGM] book
4171 Boolean weird = FALSE, reqFlag = FALSE;
4173 fromX = fromY = toX = toY = -1;
4177 if (appData.debugMode)
4178 fprintf(debugFP, _("Parsing board: %s\n"), string);
4180 move_str[0] = NULLCHAR;
4181 elapsed_time[0] = NULLCHAR;
4182 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
4184 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
4185 if(string[i] == ' ') { ranks++; files = 0; }
4187 if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
4190 for(j = 0; j <i; j++) board_chars[j] = string[j];
4191 board_chars[i] = '\0';
4194 n = sscanf(string, PATTERN, &to_play, &double_push,
4195 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
4196 &gamenum, white, black, &relation, &basetime, &increment,
4197 &white_stren, &black_stren, &white_time, &black_time,
4198 &moveNum, str, elapsed_time, move_str, &ics_flip,
4202 snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
4203 DisplayError(str, 0);
4207 /* Convert the move number to internal form */
4208 moveNum = (moveNum - 1) * 2;
4209 if (to_play == 'B') moveNum++;
4210 if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
4211 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
4217 case RELATION_OBSERVING_PLAYED:
4218 case RELATION_OBSERVING_STATIC:
4219 if (gamenum == -1) {
4220 /* Old ICC buglet */
4221 relation = RELATION_OBSERVING_STATIC;
4223 newGameMode = IcsObserving;
4225 case RELATION_PLAYING_MYMOVE:
4226 case RELATION_PLAYING_NOTMYMOVE:
4228 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
4229 IcsPlayingWhite : IcsPlayingBlack;
4230 soughtPending =FALSE; // [HGM] seekgraph: solve race condition
4232 case RELATION_EXAMINING:
4233 newGameMode = IcsExamining;
4235 case RELATION_ISOLATED_BOARD:
4237 /* Just display this board. If user was doing something else,
4238 we will forget about it until the next board comes. */
4239 newGameMode = IcsIdle;
4241 case RELATION_STARTING_POSITION:
4242 newGameMode = gameMode;
4246 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
4247 gameMode == IcsObserving && appData.dualBoard) // also allow use of second board for observing two games
4248 && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
4249 // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
4250 int fac = strchr(elapsed_time, '.') ? 1 : 1000;
4251 static int lastBgGame = -1;
4253 for (k = 0; k < ranks; k++) {
4254 for (j = 0; j < files; j++)
4255 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4256 if(gameInfo.holdingsWidth > 1) {
4257 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4258 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4261 CopyBoard(partnerBoard, board);
4262 if(toSqr = strchr(str, '/')) { // extract highlights from long move
4263 partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
4264 partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
4265 } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
4266 if(toSqr = strchr(str, '-')) {
4267 partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
4268 partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
4269 } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
4270 if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
4271 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
4272 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4274 DisplayWhiteClock(white_time*fac, to_play == 'W');
4275 DisplayBlackClock(black_time*fac, to_play != 'W');
4276 activePartner = to_play;
4277 if(gamenum != lastBgGame) {
4279 snprintf(buf, MSG_SIZ, "%s %s %s", white, _("vs."), black);
4282 lastBgGame = gamenum;
4283 activePartnerTime = to_play == 'W' ? white_time*fac : black_time*fac;
4284 partnerUp = 0; flipView = !flipView; } // [HGM] dual
4285 snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time*fac/60000, (white_time*fac%60000)/1000,
4286 (black_time*fac/60000), (black_time*fac%60000)/1000, white_stren, black_stren, to_play);
4287 DisplayMessage(partnerStatus, "");
4288 partnerBoardValid = TRUE;
4292 if(appData.dualBoard && appData.bgObserve) {
4293 if((newGameMode == IcsPlayingWhite || newGameMode == IcsPlayingBlack) && moveNum == 1)
4294 SendToICS(ics_prefix), SendToICS("pobserve\n");
4295 else if(newGameMode == IcsObserving && (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
4297 snprintf(buf, MSG_SIZ, "%spobserve %s\n", ics_prefix, white);
4302 /* Modify behavior for initial board display on move listing
4305 switch (ics_getting_history) {
4309 case H_GOT_REQ_HEADER:
4310 case H_GOT_UNREQ_HEADER:
4311 /* This is the initial position of the current game */
4312 gamenum = ics_gamenum;
4313 moveNum = 0; /* old ICS bug workaround */
4314 if (to_play == 'B') {
4315 startedFromSetupPosition = TRUE;
4316 blackPlaysFirst = TRUE;
4318 if (forwardMostMove == 0) forwardMostMove = 1;
4319 if (backwardMostMove == 0) backwardMostMove = 1;
4320 if (currentMove == 0) currentMove = 1;
4322 newGameMode = gameMode;
4323 relation = RELATION_STARTING_POSITION; /* ICC needs this */
4325 case H_GOT_UNWANTED_HEADER:
4326 /* This is an initial board that we don't want */
4328 case H_GETTING_MOVES:
4329 /* Should not happen */
4330 DisplayError(_("Error gathering move list: extra board"), 0);
4331 ics_getting_history = H_FALSE;
4335 if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4336 move_str[1] == '@' && !gameInfo.holdingsWidth ||
4337 weird && (int)gameInfo.variant < (int)VariantShogi) {
4338 /* [HGM] We seem to have switched variant unexpectedly
4339 * Try to guess new variant from board size
4341 VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4342 if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4343 if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4344 if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4345 if(ranks == 9 && files == 9) newVariant = VariantShogi; else
4346 if(ranks == 10 && files == 10) newVariant = VariantGrand; else
4347 if(!weird) newVariant = move_str[1] == '@' ? VariantCrazyhouse : VariantNormal;
4348 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4349 /* Get a move list just to see the header, which
4350 will tell us whether this is really bug or zh */
4351 if (ics_getting_history == H_FALSE) {
4352 ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4353 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4358 /* Take action if this is the first board of a new game, or of a
4359 different game than is currently being displayed. */
4360 if (gamenum != ics_gamenum || newGameMode != gameMode ||
4361 relation == RELATION_ISOLATED_BOARD) {
4363 /* Forget the old game and get the history (if any) of the new one */
4364 if (gameMode != BeginningOfGame) {
4368 if (appData.autoRaiseBoard) BoardToTop();
4370 if (gamenum == -1) {
4371 newGameMode = IcsIdle;
4372 } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4373 appData.getMoveList && !reqFlag) {
4374 /* Need to get game history */
4375 ics_getting_history = H_REQUESTED;
4376 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4380 /* Initially flip the board to have black on the bottom if playing
4381 black or if the ICS flip flag is set, but let the user change
4382 it with the Flip View button. */
4383 flipView = appData.autoFlipView ?
4384 (newGameMode == IcsPlayingBlack) || ics_flip :
4387 /* Done with values from previous mode; copy in new ones */
4388 gameMode = newGameMode;
4390 ics_gamenum = gamenum;
4391 if (gamenum == gs_gamenum) {
4392 int klen = strlen(gs_kind);
4393 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4394 snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4395 gameInfo.event = StrSave(str);
4397 gameInfo.event = StrSave("ICS game");
4399 gameInfo.site = StrSave(appData.icsHost);
4400 gameInfo.date = PGNDate();
4401 gameInfo.round = StrSave("-");
4402 gameInfo.white = StrSave(white);
4403 gameInfo.black = StrSave(black);
4404 timeControl = basetime * 60 * 1000;
4406 timeIncrement = increment * 1000;
4407 movesPerSession = 0;
4408 gameInfo.timeControl = TimeControlTagValue();
4409 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4410 if (appData.debugMode) {
4411 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4412 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4413 setbuf(debugFP, NULL);
4416 gameInfo.outOfBook = NULL;
4418 /* Do we have the ratings? */
4419 if (strcmp(player1Name, white) == 0 &&
4420 strcmp(player2Name, black) == 0) {
4421 if (appData.debugMode)
4422 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4423 player1Rating, player2Rating);
4424 gameInfo.whiteRating = player1Rating;
4425 gameInfo.blackRating = player2Rating;
4426 } else if (strcmp(player2Name, white) == 0 &&
4427 strcmp(player1Name, black) == 0) {
4428 if (appData.debugMode)
4429 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4430 player2Rating, player1Rating);
4431 gameInfo.whiteRating = player2Rating;
4432 gameInfo.blackRating = player1Rating;
4434 player1Name[0] = player2Name[0] = NULLCHAR;
4436 /* Silence shouts if requested */
4437 if (appData.quietPlay &&
4438 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4439 SendToICS(ics_prefix);
4440 SendToICS("set shout 0\n");
4444 /* Deal with midgame name changes */
4446 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4447 if (gameInfo.white) free(gameInfo.white);
4448 gameInfo.white = StrSave(white);
4450 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4451 if (gameInfo.black) free(gameInfo.black);
4452 gameInfo.black = StrSave(black);
4456 /* Throw away game result if anything actually changes in examine mode */
4457 if (gameMode == IcsExamining && !newGame) {
4458 gameInfo.result = GameUnfinished;
4459 if (gameInfo.resultDetails != NULL) {
4460 free(gameInfo.resultDetails);
4461 gameInfo.resultDetails = NULL;
4465 /* In pausing && IcsExamining mode, we ignore boards coming
4466 in if they are in a different variation than we are. */
4467 if (pauseExamInvalid) return;
4468 if (pausing && gameMode == IcsExamining) {
4469 if (moveNum <= pauseExamForwardMostMove) {
4470 pauseExamInvalid = TRUE;
4471 forwardMostMove = pauseExamForwardMostMove;
4476 if (appData.debugMode) {
4477 fprintf(debugFP, "load %dx%d board\n", files, ranks);
4479 /* Parse the board */
4480 for (k = 0; k < ranks; k++) {
4481 for (j = 0; j < files; j++)
4482 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4483 if(gameInfo.holdingsWidth > 1) {
4484 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4485 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4488 if(moveNum==0 && gameInfo.variant == VariantSChess) {
4489 board[5][BOARD_RGHT+1] = WhiteAngel;
4490 board[6][BOARD_RGHT+1] = WhiteMarshall;
4491 board[1][0] = BlackMarshall;
4492 board[2][0] = BlackAngel;
4493 board[1][1] = board[2][1] = board[5][BOARD_RGHT] = board[6][BOARD_RGHT] = 1;
4495 CopyBoard(boards[moveNum], board);
4496 boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4498 startedFromSetupPosition =
4499 !CompareBoards(board, initialPosition);
4500 if(startedFromSetupPosition)
4501 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4504 /* [HGM] Set castling rights. Take the outermost Rooks,
4505 to make it also work for FRC opening positions. Note that board12
4506 is really defective for later FRC positions, as it has no way to
4507 indicate which Rook can castle if they are on the same side of King.
4508 For the initial position we grant rights to the outermost Rooks,
4509 and remember thos rights, and we then copy them on positions
4510 later in an FRC game. This means WB might not recognize castlings with
4511 Rooks that have moved back to their original position as illegal,
4512 but in ICS mode that is not its job anyway.
4514 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4515 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4517 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4518 if(board[0][i] == WhiteRook) j = i;
4519 initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4520 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4521 if(board[0][i] == WhiteRook) j = i;
4522 initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4523 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4524 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4525 initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4526 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4527 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4528 initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4530 boards[moveNum][CASTLING][2] = boards[moveNum][CASTLING][5] = NoRights;
4531 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4532 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4533 if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4534 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4535 if(board[BOARD_HEIGHT-1][k] == bKing)
4536 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4537 if(gameInfo.variant == VariantTwoKings) {
4538 // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4539 if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4540 if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4543 r = boards[moveNum][CASTLING][0] = initialRights[0];
4544 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4545 r = boards[moveNum][CASTLING][1] = initialRights[1];
4546 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4547 r = boards[moveNum][CASTLING][3] = initialRights[3];
4548 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4549 r = boards[moveNum][CASTLING][4] = initialRights[4];
4550 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4551 /* wildcastle kludge: always assume King has rights */
4552 r = boards[moveNum][CASTLING][2] = initialRights[2];
4553 r = boards[moveNum][CASTLING][5] = initialRights[5];
4555 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4556 boards[moveNum][EP_STATUS] = EP_NONE;
4557 if(str[0] == 'P') boards[moveNum][EP_STATUS] = EP_PAWN_MOVE;
4558 if(strchr(move_str, 'x')) boards[moveNum][EP_STATUS] = EP_CAPTURE;
4559 if(double_push != -1) boards[moveNum][EP_STATUS] = double_push + BOARD_LEFT;
4562 if (ics_getting_history == H_GOT_REQ_HEADER ||
4563 ics_getting_history == H_GOT_UNREQ_HEADER) {
4564 /* This was an initial position from a move list, not
4565 the current position */
4569 /* Update currentMove and known move number limits */
4570 newMove = newGame || moveNum > forwardMostMove;
4573 forwardMostMove = backwardMostMove = currentMove = moveNum;
4574 if (gameMode == IcsExamining && moveNum == 0) {
4575 /* Workaround for ICS limitation: we are not told the wild
4576 type when starting to examine a game. But if we ask for
4577 the move list, the move list header will tell us */
4578 ics_getting_history = H_REQUESTED;
4579 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4582 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4583 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4585 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4586 /* [HGM] applied this also to an engine that is silently watching */
4587 if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4588 (gameMode == IcsObserving || gameMode == IcsExamining) &&
4589 gameInfo.variant == currentlyInitializedVariant) {
4590 takeback = forwardMostMove - moveNum;
4591 for (i = 0; i < takeback; i++) {
4592 if (appData.debugMode) fprintf(debugFP, "take back move\n");
4593 SendToProgram("undo\n", &first);
4598 forwardMostMove = moveNum;
4599 if (!pausing || currentMove > forwardMostMove)
4600 currentMove = forwardMostMove;
4602 /* New part of history that is not contiguous with old part */
4603 if (pausing && gameMode == IcsExamining) {
4604 pauseExamInvalid = TRUE;
4605 forwardMostMove = pauseExamForwardMostMove;
4608 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4610 if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4611 // [HGM] when we will receive the move list we now request, it will be
4612 // fed to the engine from the first move on. So if the engine is not
4613 // in the initial position now, bring it there.
4614 InitChessProgram(&first, 0);
4617 ics_getting_history = H_REQUESTED;
4618 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4621 forwardMostMove = backwardMostMove = currentMove = moveNum;
4624 /* Update the clocks */
4625 if (strchr(elapsed_time, '.')) {
4627 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4628 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4630 /* Time is in seconds */
4631 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4632 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4637 if (appData.zippyPlay && newGame &&
4638 gameMode != IcsObserving && gameMode != IcsIdle &&
4639 gameMode != IcsExamining)
4640 ZippyFirstBoard(moveNum, basetime, increment);
4643 /* Put the move on the move list, first converting
4644 to canonical algebraic form. */
4646 if (appData.debugMode) {
4647 if (appData.debugMode) { int f = forwardMostMove;
4648 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4649 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4650 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4652 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4653 fprintf(debugFP, "moveNum = %d\n", moveNum);
4654 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4655 setbuf(debugFP, NULL);
4657 if (moveNum <= backwardMostMove) {
4658 /* We don't know what the board looked like before
4660 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4661 strcat(parseList[moveNum - 1], " ");
4662 strcat(parseList[moveNum - 1], elapsed_time);
4663 moveList[moveNum - 1][0] = NULLCHAR;
4664 } else if (strcmp(move_str, "none") == 0) {
4665 // [HGM] long SAN: swapped order; test for 'none' before parsing move
4666 /* Again, we don't know what the board looked like;
4667 this is really the start of the game. */
4668 parseList[moveNum - 1][0] = NULLCHAR;
4669 moveList[moveNum - 1][0] = NULLCHAR;
4670 backwardMostMove = moveNum;
4671 startedFromSetupPosition = TRUE;
4672 fromX = fromY = toX = toY = -1;
4674 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4675 // So we parse the long-algebraic move string in stead of the SAN move
4676 int valid; char buf[MSG_SIZ], *prom;
4678 if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4679 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4680 // str looks something like "Q/a1-a2"; kill the slash
4682 snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4683 else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4684 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4685 strcat(buf, prom); // long move lacks promo specification!
4686 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4687 if(appData.debugMode)
4688 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4689 safeStrCpy(move_str, buf, MSG_SIZ);
4691 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4692 &fromX, &fromY, &toX, &toY, &promoChar)
4693 || ParseOneMove(buf, moveNum - 1, &moveType,
4694 &fromX, &fromY, &toX, &toY, &promoChar);
4695 // end of long SAN patch
4697 (void) CoordsToAlgebraic(boards[moveNum - 1],
4698 PosFlags(moveNum - 1),
4699 fromY, fromX, toY, toX, promoChar,
4700 parseList[moveNum-1]);
4701 switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4707 if(gameInfo.variant != VariantShogi)
4708 strcat(parseList[moveNum - 1], "+");
4711 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4712 strcat(parseList[moveNum - 1], "#");
4715 strcat(parseList[moveNum - 1], " ");
4716 strcat(parseList[moveNum - 1], elapsed_time);
4717 /* currentMoveString is set as a side-effect of ParseOneMove */
4718 if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4719 safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4720 strcat(moveList[moveNum - 1], "\n");
4722 if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper && gameInfo.variant != VariantGreat
4723 && gameInfo.variant != VariantGrand&& gameInfo.variant != VariantSChess) // inherit info that ICS does not give from previous board
4724 for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4725 ChessSquare old, new = boards[moveNum][k][j];
4726 if(fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4727 old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4728 if(old == new) continue;
4729 if(old == PROMOTED new) boards[moveNum][k][j] = old; // prevent promoted pieces to revert to primordial ones
4730 else if(new == WhiteWazir || new == BlackWazir) {
4731 if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4732 boards[moveNum][k][j] = PROMOTED old; // choose correct type of Gold in promotion
4733 else boards[moveNum][k][j] = old; // preserve type of Gold
4734 } else if((old == WhitePawn || old == BlackPawn) && new != EmptySquare) // Pawn promotions (but not e.p.capture!)
4735 boards[moveNum][k][j] = PROMOTED new; // use non-primordial representation of chosen piece
4738 /* Move from ICS was illegal!? Punt. */
4739 if (appData.debugMode) {
4740 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4741 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4743 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4744 strcat(parseList[moveNum - 1], " ");
4745 strcat(parseList[moveNum - 1], elapsed_time);
4746 moveList[moveNum - 1][0] = NULLCHAR;
4747 fromX = fromY = toX = toY = -1;
4750 if (appData.debugMode) {
4751 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4752 setbuf(debugFP, NULL);
4756 /* Send move to chess program (BEFORE animating it). */
4757 if (appData.zippyPlay && !newGame && newMove &&
4758 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4760 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4761 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4762 if (moveList[moveNum - 1][0] == NULLCHAR) {
4763 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4765 DisplayError(str, 0);
4767 if (first.sendTime) {
4768 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4770 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4771 if (firstMove && !bookHit) {
4773 if (first.useColors) {
4774 SendToProgram(gameMode == IcsPlayingWhite ?
4776 "black\ngo\n", &first);
4778 SendToProgram("go\n", &first);
4780 first.maybeThinking = TRUE;
4783 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4784 if (moveList[moveNum - 1][0] == NULLCHAR) {
4785 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4786 DisplayError(str, 0);
4788 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4789 SendMoveToProgram(moveNum - 1, &first);
4796 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
4797 /* If move comes from a remote source, animate it. If it
4798 isn't remote, it will have already been animated. */
4799 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
4800 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
4802 if (!pausing && appData.highlightLastMove) {
4803 SetHighlights(fromX, fromY, toX, toY);
4807 /* Start the clocks */
4808 whiteFlag = blackFlag = FALSE;
4809 appData.clockMode = !(basetime == 0 && increment == 0);
4811 ics_clock_paused = TRUE;
4813 } else if (ticking == 1) {
4814 ics_clock_paused = FALSE;
4816 if (gameMode == IcsIdle ||
4817 relation == RELATION_OBSERVING_STATIC ||
4818 relation == RELATION_EXAMINING ||
4820 DisplayBothClocks();
4824 /* Display opponents and material strengths */
4825 if (gameInfo.variant != VariantBughouse &&
4826 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
4827 if (tinyLayout || smallLayout) {
4828 if(gameInfo.variant == VariantNormal)
4829 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
4830 gameInfo.white, white_stren, gameInfo.black, black_stren,
4831 basetime, increment);
4833 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
4834 gameInfo.white, white_stren, gameInfo.black, black_stren,
4835 basetime, increment, (int) gameInfo.variant);
4837 if(gameInfo.variant == VariantNormal)
4838 snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d}",
4839 gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
4840 basetime, increment);
4842 snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d %s}",
4843 gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
4844 basetime, increment, VariantName(gameInfo.variant));
4847 if (appData.debugMode) {
4848 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
4853 /* Display the board */
4854 if (!pausing && !appData.noGUI) {
4856 if (appData.premove)
4858 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
4859 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
4860 ClearPremoveHighlights();
4862 j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
4863 if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
4864 DrawPosition(j, boards[currentMove]);
4866 DisplayMove(moveNum - 1);
4867 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
4868 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
4869 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
4870 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
4874 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
4876 if(bookHit) { // [HGM] book: simulate book reply
4877 static char bookMove[MSG_SIZ]; // a bit generous?
4879 programStats.nodes = programStats.depth = programStats.time =
4880 programStats.score = programStats.got_only_move = 0;
4881 sprintf(programStats.movelist, "%s (xbook)", bookHit);
4883 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
4884 strcat(bookMove, bookHit);
4885 HandleMachineMove(bookMove, &first);
4894 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
4895 ics_getting_history = H_REQUESTED;
4896 snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
4902 SendToBoth (char *msg)
4903 { // to make it easy to keep two engines in step in dual analysis
4904 SendToProgram(msg, &first);
4905 if(second.analyzing) SendToProgram(msg, &second);
4909 AnalysisPeriodicEvent (int force)
4911 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
4912 && !force) || !appData.periodicUpdates)
4915 /* Send . command to Crafty to collect stats */
4918 /* Don't send another until we get a response (this makes
4919 us stop sending to old Crafty's which don't understand
4920 the "." command (sending illegal cmds resets node count & time,
4921 which looks bad)) */
4922 programStats.ok_to_send = 0;
4926 ics_update_width (int new_width)
4928 ics_printf("set width %d\n", new_width);
4932 SendMoveToProgram (int moveNum, ChessProgramState *cps)
4936 if(moveList[moveNum][1] == '@' && moveList[moveNum][0] == '@') {
4937 // null move in variant where engine does not understand it (for analysis purposes)
4938 SendBoard(cps, moveNum + 1); // send position after move in stead.
4941 if (cps->useUsermove) {
4942 SendToProgram("usermove ", cps);
4946 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
4947 int len = space - parseList[moveNum];
4948 memcpy(buf, parseList[moveNum], len);
4950 buf[len] = NULLCHAR;
4952 snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
4954 SendToProgram(buf, cps);
4956 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
4957 AlphaRank(moveList[moveNum], 4);
4958 SendToProgram(moveList[moveNum], cps);
4959 AlphaRank(moveList[moveNum], 4); // and back
4961 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
4962 * the engine. It would be nice to have a better way to identify castle
4964 if((gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom)
4965 && cps->useOOCastle) {
4966 int fromX = moveList[moveNum][0] - AAA;
4967 int fromY = moveList[moveNum][1] - ONE;
4968 int toX = moveList[moveNum][2] - AAA;
4969 int toY = moveList[moveNum][3] - ONE;
4970 if((boards[moveNum][fromY][fromX] == WhiteKing
4971 && boards[moveNum][toY][toX] == WhiteRook)
4972 || (boards[moveNum][fromY][fromX] == BlackKing
4973 && boards[moveNum][toY][toX] == BlackRook)) {
4974 if(toX > fromX) SendToProgram("O-O\n", cps);
4975 else SendToProgram("O-O-O\n", cps);
4977 else SendToProgram(moveList[moveNum], cps);
4979 if(BOARD_HEIGHT > 10) { // [HGM] big: convert ranks to double-digit where needed
4980 if(moveList[moveNum][1] == '@' && (BOARD_HEIGHT < 16 || moveList[moveNum][0] <= 'Z')) { // drop move
4981 if(moveList[moveNum][0]== '@') snprintf(buf, MSG_SIZ, "@@@@\n"); else
4982 snprintf(buf, MSG_SIZ, "%c@%c%d%s", moveList[moveNum][0],
4983 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
4985 snprintf(buf, MSG_SIZ, "%c%d%c%d%s", moveList[moveNum][0], moveList[moveNum][1] - '0',
4986 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
4987 SendToProgram(buf, cps);
4989 else SendToProgram(moveList[moveNum], cps);
4990 /* End of additions by Tord */
4993 /* [HGM] setting up the opening has brought engine in force mode! */
4994 /* Send 'go' if we are in a mode where machine should play. */
4995 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
4996 (gameMode == TwoMachinesPlay ||
4998 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
5000 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
5001 SendToProgram("go\n", cps);
5002 if (appData.debugMode) {
5003 fprintf(debugFP, "(extra)\n");
5006 setboardSpoiledMachineBlack = 0;
5010 SendMoveToICS (ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar)
5012 char user_move[MSG_SIZ];
5015 if(gameInfo.variant == VariantSChess && promoChar) {
5016 snprintf(suffix, 4, "=%c", toX == BOARD_WIDTH<<1 ? ToUpper(promoChar) : ToLower(promoChar));
5017 if(moveType == NormalMove) moveType = WhitePromotion; // kludge to do gating
5018 } else suffix[0] = NULLCHAR;
5022 snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
5023 (int)moveType, fromX, fromY, toX, toY);
5024 DisplayError(user_move + strlen("say "), 0);
5026 case WhiteKingSideCastle:
5027 case BlackKingSideCastle:
5028 case WhiteQueenSideCastleWild:
5029 case BlackQueenSideCastleWild:
5031 case WhiteHSideCastleFR:
5032 case BlackHSideCastleFR:
5034 snprintf(user_move, MSG_SIZ, "o-o%s\n", suffix);
5036 case WhiteQueenSideCastle:
5037 case BlackQueenSideCastle:
5038 case WhiteKingSideCastleWild:
5039 case BlackKingSideCastleWild:
5041 case WhiteASideCastleFR:
5042 case BlackASideCastleFR:
5044 snprintf(user_move, MSG_SIZ, "o-o-o%s\n",suffix);
5046 case WhiteNonPromotion:
5047 case BlackNonPromotion:
5048 sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5050 case WhitePromotion:
5051 case BlackPromotion:
5052 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
5053 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5054 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5055 PieceToChar(WhiteFerz));
5056 else if(gameInfo.variant == VariantGreat)
5057 snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
5058 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5059 PieceToChar(WhiteMan));
5061 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5062 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5068 snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
5069 ToUpper(PieceToChar((ChessSquare) fromX)),
5070 AAA + toX, ONE + toY);
5072 case IllegalMove: /* could be a variant we don't quite understand */
5073 if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
5075 case WhiteCapturesEnPassant:
5076 case BlackCapturesEnPassant:
5077 snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
5078 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5081 SendToICS(user_move);
5082 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
5083 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
5088 { // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
5089 int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
5090 static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
5091 if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
5092 DisplayError(_("You cannot do this while you are playing or observing"), 0);
5095 if(gameMode != IcsExamining) { // is this ever not the case?
5096 char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
5098 if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
5099 snprintf(command,MSG_SIZ, "match %s", ics_handle);
5100 } else { // on FICS we must first go to general examine mode
5101 safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
5103 if(gameInfo.variant != VariantNormal) {
5104 // try figure out wild number, as xboard names are not always valid on ICS
5105 for(i=1; i<=36; i++) {
5106 snprintf(buf, MSG_SIZ, "wild/%d", i);
5107 if(StringToVariant(buf) == gameInfo.variant) break;
5109 if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
5110 else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
5111 else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
5112 } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
5113 SendToICS(ics_prefix);
5115 if(startedFromSetupPosition || backwardMostMove != 0) {
5116 fen = PositionToFEN(backwardMostMove, NULL);
5117 if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
5118 snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
5120 } else { // FICS: everything has to set by separate bsetup commands
5121 p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
5122 snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
5124 if(!WhiteOnMove(backwardMostMove)) {
5125 SendToICS("bsetup tomove black\n");
5127 i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
5128 snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
5130 i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
5131 snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
5133 i = boards[backwardMostMove][EP_STATUS];
5134 if(i >= 0) { // set e.p.
5135 snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
5141 if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
5142 SendToICS("bsetup done\n"); // switch to normal examining.
5144 for(i = backwardMostMove; i<last; i++) {
5146 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
5147 if((*buf == 'b' || *buf == 'B') && buf[1] == 'x') { // work-around for stupid FICS bug, which thinks bxc3 can be a Bishop move
5148 int len = strlen(moveList[i]);
5149 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s", moveList[i]); // use long algebraic
5150 if(!isdigit(buf[len-2])) snprintf(buf+len-2, 20-len, "=%c\n", ToUpper(buf[len-2])); // promotion must have '=' in ICS format
5154 SendToICS(ics_prefix);
5155 SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
5159 CoordsToComputerAlgebraic (int rf, int ff, int rt, int ft, char promoChar, char move[7])
5161 if (rf == DROP_RANK) {
5162 if(ff == EmptySquare) sprintf(move, "@@@@\n"); else // [HGM] pass
5163 sprintf(move, "%c@%c%c\n",
5164 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
5166 if (promoChar == 'x' || promoChar == NULLCHAR) {
5167 sprintf(move, "%c%c%c%c\n",
5168 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
5170 sprintf(move, "%c%c%c%c%c\n",
5171 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
5177 ProcessICSInitScript (FILE *f)
5181 while (fgets(buf, MSG_SIZ, f)) {
5182 SendToICSDelayed(buf,(long)appData.msLoginDelay);
5189 static int lastX, lastY, selectFlag, dragging;
5194 ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
5195 if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
5196 if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
5197 if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
5198 if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
5199 if(fromY != BOARD_HEIGHT-2 && fromY != 1) pawn = EmptySquare;
5202 if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
5203 else if((int)promoSweep == -1) promoSweep = WhiteKing;
5204 else if(promoSweep == BlackPawn && step < 0) promoSweep = WhitePawn;
5205 else if(promoSweep == WhiteKing && step > 0) promoSweep = BlackKing;
5206 if(!step) step = -1;
5207 } while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' || promoSweep == pawn ||
5208 appData.testLegality && (promoSweep == king ||
5209 gameInfo.variant == VariantShogi && promoSweep != PROMOTED last && last != PROMOTED promoSweep && last != promoSweep));
5211 int victim = boards[currentMove][toY][toX];
5212 boards[currentMove][toY][toX] = promoSweep;
5213 DrawPosition(FALSE, boards[currentMove]);
5214 boards[currentMove][toY][toX] = victim;
5216 ChangeDragPiece(promoSweep);
5220 PromoScroll (int x, int y)
5224 if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
5225 if(abs(x - lastX) < 25 && abs(y - lastY) < 25) return FALSE;
5226 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5227 if(!step) return FALSE;
5228 lastX = x; lastY = y;
5229 if((promoSweep < BlackPawn) == flipView) step = -step;
5230 if(step > 0) selectFlag = 1;
5231 if(!selectFlag) Sweep(step);
5236 NextPiece (int step)
5238 ChessSquare piece = boards[currentMove][toY][toX];
5241 if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
5242 if((int)pieceSweep == -1) pieceSweep = BlackKing;
5243 if(!step) step = -1;
5244 } while(PieceToChar(pieceSweep) == '.');
5245 boards[currentMove][toY][toX] = pieceSweep;
5246 DrawPosition(FALSE, boards[currentMove]);
5247 boards[currentMove][toY][toX] = piece;
5249 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
5251 AlphaRank (char *move, int n)
5253 // char *p = move, c; int x, y;
5255 if (appData.debugMode) {
5256 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
5260 move[2]>='0' && move[2]<='9' &&
5261 move[3]>='a' && move[3]<='x' ) {
5263 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5264 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5266 if(move[0]>='0' && move[0]<='9' &&
5267 move[1]>='a' && move[1]<='x' &&
5268 move[2]>='0' && move[2]<='9' &&
5269 move[3]>='a' && move[3]<='x' ) {
5270 /* input move, Shogi -> normal */
5271 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
5272 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
5273 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5274 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5277 move[3]>='0' && move[3]<='9' &&
5278 move[2]>='a' && move[2]<='x' ) {
5280 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5281 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5284 move[0]>='a' && move[0]<='x' &&
5285 move[3]>='0' && move[3]<='9' &&
5286 move[2]>='a' && move[2]<='x' ) {
5287 /* output move, normal -> Shogi */
5288 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
5289 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
5290 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5291 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5292 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
5294 if (appData.debugMode) {
5295 fprintf(debugFP, " out = '%s'\n", move);
5299 char yy_textstr[8000];
5301 /* Parser for moves from gnuchess, ICS, or user typein box */
5303 ParseOneMove (char *move, int moveNum, ChessMove *moveType, int *fromX, int *fromY, int *toX, int *toY, char *promoChar)
5305 *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
5307 switch (*moveType) {
5308 case WhitePromotion:
5309 case BlackPromotion:
5310 case WhiteNonPromotion:
5311 case BlackNonPromotion:
5313 case WhiteCapturesEnPassant:
5314 case BlackCapturesEnPassant:
5315 case WhiteKingSideCastle:
5316 case WhiteQueenSideCastle:
5317 case BlackKingSideCastle:
5318 case BlackQueenSideCastle:
5319 case WhiteKingSideCastleWild:
5320 case WhiteQueenSideCastleWild:
5321 case BlackKingSideCastleWild:
5322 case BlackQueenSideCastleWild:
5323 /* Code added by Tord: */
5324 case WhiteHSideCastleFR:
5325 case WhiteASideCastleFR:
5326 case BlackHSideCastleFR:
5327 case BlackASideCastleFR:
5328 /* End of code added by Tord */
5329 case IllegalMove: /* bug or odd chess variant */
5330 *fromX = currentMoveString[0] - AAA;
5331 *fromY = currentMoveString[1] - ONE;
5332 *toX = currentMoveString[2] - AAA;
5333 *toY = currentMoveString[3] - ONE;
5334 *promoChar = currentMoveString[4];
5335 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
5336 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
5337 if (appData.debugMode) {
5338 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
5340 *fromX = *fromY = *toX = *toY = 0;
5343 if (appData.testLegality) {
5344 return (*moveType != IllegalMove);
5346 return !(*fromX == *toX && *fromY == *toY) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
5347 WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
5352 *fromX = *moveType == WhiteDrop ?
5353 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5354 (int) CharToPiece(ToLower(currentMoveString[0]));
5356 *toX = currentMoveString[2] - AAA;
5357 *toY = currentMoveString[3] - ONE;
5358 *promoChar = NULLCHAR;
5362 case ImpossibleMove:
5372 if (appData.debugMode) {
5373 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
5376 *fromX = *fromY = *toX = *toY = 0;
5377 *promoChar = NULLCHAR;
5382 Boolean pushed = FALSE;
5383 char *lastParseAttempt;
5386 ParsePV (char *pv, Boolean storeComments, Boolean atEnd)
5387 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
5388 int fromX, fromY, toX, toY; char promoChar;
5393 if (gameMode == AnalyzeMode && currentMove < forwardMostMove) {
5394 PushInner(currentMove, forwardMostMove); // [HGM] engine might not be thinking on forwardMost position!
5397 endPV = forwardMostMove;
5399 while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
5400 if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
5401 lastParseAttempt = pv;
5402 valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
5403 if(!valid && nr == 0 &&
5404 ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
5405 nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
5406 // Hande case where played move is different from leading PV move
5407 CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
5408 CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
5409 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
5410 if(!CompareBoards(boards[endPV], boards[endPV+2])) {
5411 endPV += 2; // if position different, keep this
5412 moveList[endPV-1][0] = fromX + AAA;
5413 moveList[endPV-1][1] = fromY + ONE;
5414 moveList[endPV-1][2] = toX + AAA;
5415 moveList[endPV-1][3] = toY + ONE;
5416 parseList[endPV-1][0] = NULLCHAR;
5417 safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
5420 pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
5421 if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5422 if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5423 if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5424 valid++; // allow comments in PV
5428 if(endPV+1 > framePtr) break; // no space, truncate
5431 CopyBoard(boards[endPV], boards[endPV-1]);
5432 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5433 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, moveList[endPV - 1]);
5434 strncat(moveList[endPV-1], "\n", MOVE_LEN);
5435 CoordsToAlgebraic(boards[endPV - 1],
5436 PosFlags(endPV - 1),
5437 fromY, fromX, toY, toX, promoChar,
5438 parseList[endPV - 1]);
5440 if(atEnd == 2) return; // used hidden, for PV conversion
5441 currentMove = (atEnd || endPV == forwardMostMove) ? endPV : forwardMostMove + 1;
5442 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5443 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5444 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5445 DrawPosition(TRUE, boards[currentMove]);
5449 MultiPV (ChessProgramState *cps)
5450 { // check if engine supports MultiPV, and if so, return the number of the option that sets it
5452 for(i=0; i<cps->nrOptions; i++)
5453 if(!strcmp(cps->option[i].name, "MultiPV") && cps->option[i].type == Spin)
5459 LoadMultiPV (int x, int y, char *buf, int index, int *start, int *end, int pane)
5461 int startPV, multi, lineStart, origIndex = index;
5462 char *p, buf2[MSG_SIZ];
5463 ChessProgramState *cps = (pane ? &second : &first);
5465 if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5466 lastX = x; lastY = y;
5467 while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5468 lineStart = startPV = index;
5469 while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5470 if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5472 do{ while(buf[index] && buf[index] != '\n') index++;
5473 } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5475 if(lineStart == 0 && gameMode == AnalyzeMode && (multi = MultiPV(cps)) >= 0) {
5476 int n = cps->option[multi].value;
5477 if(origIndex > 17 && origIndex < 24) { if(n>1) n--; } else if(origIndex > index - 6) n++;
5478 snprintf(buf2, MSG_SIZ, "option MultiPV=%d\n", n);
5479 if(cps->option[multi].value != n) SendToProgram(buf2, cps);
5480 cps->option[multi].value = n;
5483 } else if(strstr(buf+lineStart, "exclude:") == buf+lineStart) { // exclude moves clicked
5484 ExcludeClick(origIndex - lineStart);
5487 ParsePV(buf+startPV, FALSE, gameMode != AnalyzeMode);
5488 *start = startPV; *end = index-1;
5495 static char buf[10*MSG_SIZ];
5496 int i, k=0, savedEnd=endPV, saveFMM = forwardMostMove;
5498 if(forwardMostMove < endPV) PushInner(forwardMostMove, endPV);
5499 ParsePV(pv, FALSE, 2); // this appends PV to game, suppressing any display of it
5500 for(i = forwardMostMove; i<endPV; i++){
5501 if(i&1) snprintf(buf+k, 10*MSG_SIZ-k, "%s ", parseList[i]);
5502 else snprintf(buf+k, 10*MSG_SIZ-k, "%d. %s ", i/2 + 1, parseList[i]);
5505 snprintf(buf+k, 10*MSG_SIZ-k, "%s", lastParseAttempt); // if we ran into stuff that could not be parsed, print it verbatim
5506 if(forwardMostMove < savedEnd) { PopInner(0); forwardMostMove = saveFMM; } // PopInner would set fmm to endPV!
5512 LoadPV (int x, int y)
5513 { // called on right mouse click to load PV
5514 int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5515 lastX = x; lastY = y;
5516 ParsePV(lastPV[which], FALSE, TRUE); // load the PV of the thinking engine in the boards array.
5523 int oldFMM = forwardMostMove; // N.B.: this was currentMove before PV was loaded!
5524 if(endPV < 0) return;
5525 if(appData.autoCopyPV) CopyFENToClipboard();
5527 if(gameMode == AnalyzeMode && currentMove > forwardMostMove) {
5528 Boolean saveAnimate = appData.animate;
5530 if(shiftKey && storedGames < MAX_VARIATIONS-2) { // wants to start variation, and there is space
5531 if(storedGames == 1) GreyRevert(FALSE); // we already pushed the tail, so just make it official
5532 } else storedGames--; // abandon shelved tail of original game
5535 forwardMostMove = currentMove;
5536 currentMove = oldFMM;
5537 appData.animate = FALSE;
5538 ToNrEvent(forwardMostMove);
5539 appData.animate = saveAnimate;
5541 currentMove = forwardMostMove;
5542 if(pushed) { PopInner(0); pushed = FALSE; } // restore shelved game continuation
5543 ClearPremoveHighlights();
5544 DrawPosition(TRUE, boards[currentMove]);
5548 MovePV (int x, int y, int h)
5549 { // step through PV based on mouse coordinates (called on mouse move)
5550 int margin = h>>3, step = 0, threshold = (pieceSweep == EmptySquare ? 10 : 15);
5552 // we must somehow check if right button is still down (might be released off board!)
5553 if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
5554 if(abs(x - lastX) < threshold && abs(y - lastY) < threshold) return;
5555 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5557 lastX = x; lastY = y;
5559 if(pieceSweep != EmptySquare) { NextPiece(step); return; }
5560 if(endPV < 0) return;
5561 if(y < margin) step = 1; else
5562 if(y > h - margin) step = -1;
5563 if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5564 currentMove += step;
5565 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5566 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5567 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5568 DrawPosition(FALSE, boards[currentMove]);
5572 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5573 // All positions will have equal probability, but the current method will not provide a unique
5574 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5580 int piecesLeft[(int)BlackPawn];
5581 int seed, nrOfShuffles;
5584 GetPositionNumber ()
5585 { // sets global variable seed
5588 seed = appData.defaultFrcPosition;
5589 if(seed < 0) { // randomize based on time for negative FRC position numbers
5590 for(i=0; i<50; i++) seed += random();
5591 seed = random() ^ random() >> 8 ^ random() << 8;
5592 if(seed<0) seed = -seed;
5597 put (Board board, int pieceType, int rank, int n, int shade)
5598 // put the piece on the (n-1)-th empty squares of the given shade
5602 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5603 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5604 board[rank][i] = (ChessSquare) pieceType;
5605 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5607 piecesLeft[pieceType]--;
5616 AddOnePiece (Board board, int pieceType, int rank, int shade)
5617 // calculate where the next piece goes, (any empty square), and put it there
5621 i = seed % squaresLeft[shade];
5622 nrOfShuffles *= squaresLeft[shade];
5623 seed /= squaresLeft[shade];
5624 put(board, pieceType, rank, i, shade);
5628 AddTwoPieces (Board board, int pieceType, int rank)
5629 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5631 int i, n=squaresLeft[ANY], j=n-1, k;
5633 k = n*(n-1)/2; // nr of possibilities, not counting permutations
5634 i = seed % k; // pick one
5637 while(i >= j) i -= j--;
5638 j = n - 1 - j; i += j;
5639 put(board, pieceType, rank, j, ANY);
5640 put(board, pieceType, rank, i, ANY);
5644 SetUpShuffle (Board board, int number)
5648 GetPositionNumber(); nrOfShuffles = 1;
5650 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5651 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
5652 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5654 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5656 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5657 p = (int) board[0][i];
5658 if(p < (int) BlackPawn) piecesLeft[p] ++;
5659 board[0][i] = EmptySquare;
5662 if(PosFlags(0) & F_ALL_CASTLE_OK) {
5663 // shuffles restricted to allow normal castling put KRR first
5664 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5665 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5666 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5667 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5668 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5669 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5670 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
5671 put(board, WhiteRook, 0, 0, ANY);
5672 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
5675 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
5676 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
5677 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
5678 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
5679 while(piecesLeft[p] >= 2) {
5680 AddOnePiece(board, p, 0, LITE);
5681 AddOnePiece(board, p, 0, DARK);
5683 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
5686 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
5687 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
5688 // but we leave King and Rooks for last, to possibly obey FRC restriction
5689 if(p == (int)WhiteRook) continue;
5690 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
5691 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
5694 // now everything is placed, except perhaps King (Unicorn) and Rooks
5696 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
5697 // Last King gets castling rights
5698 while(piecesLeft[(int)WhiteUnicorn]) {
5699 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5700 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5703 while(piecesLeft[(int)WhiteKing]) {
5704 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5705 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5710 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
5711 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
5714 // Only Rooks can be left; simply place them all
5715 while(piecesLeft[(int)WhiteRook]) {
5716 i = put(board, WhiteRook, 0, 0, ANY);
5717 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
5720 initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
5722 initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
5725 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
5726 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
5729 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
5733 SetCharTable (char *table, const char * map)
5734 /* [HGM] moved here from winboard.c because of its general usefulness */
5735 /* Basically a safe strcpy that uses the last character as King */
5737 int result = FALSE; int NrPieces;
5739 if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
5740 && NrPieces >= 12 && !(NrPieces&1)) {
5741 int i; /* [HGM] Accept even length from 12 to 34 */
5743 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
5744 for( i=0; i<NrPieces/2-1; i++ ) {
5746 table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
5748 table[(int) WhiteKing] = map[NrPieces/2-1];
5749 table[(int) BlackKing] = map[NrPieces-1];
5758 Prelude (Board board)
5759 { // [HGM] superchess: random selection of exo-pieces
5760 int i, j, k; ChessSquare p;
5761 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
5763 GetPositionNumber(); // use FRC position number
5765 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
5766 SetCharTable(pieceToChar, appData.pieceToCharTable);
5767 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
5768 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
5771 j = seed%4; seed /= 4;
5772 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5773 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5774 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5775 j = seed%3 + (seed%3 >= j); seed /= 3;
5776 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5777 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5778 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5779 j = seed%3; seed /= 3;
5780 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5781 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5782 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5783 j = seed%2 + (seed%2 >= j); seed /= 2;
5784 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5785 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5786 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5787 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
5788 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
5789 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
5790 put(board, exoPieces[0], 0, 0, ANY);
5791 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
5795 InitPosition (int redraw)
5797 ChessSquare (* pieces)[BOARD_FILES];
5798 int i, j, pawnRow, overrule,
5799 oldx = gameInfo.boardWidth,
5800 oldy = gameInfo.boardHeight,
5801 oldh = gameInfo.holdingsWidth;
5804 if(appData.icsActive) shuffleOpenings = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
5806 /* [AS] Initialize pv info list [HGM] and game status */
5808 for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
5809 pvInfoList[i].depth = 0;
5810 boards[i][EP_STATUS] = EP_NONE;
5811 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
5814 initialRulePlies = 0; /* 50-move counter start */
5816 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
5817 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
5821 /* [HGM] logic here is completely changed. In stead of full positions */
5822 /* the initialized data only consist of the two backranks. The switch */
5823 /* selects which one we will use, which is than copied to the Board */
5824 /* initialPosition, which for the rest is initialized by Pawns and */
5825 /* empty squares. This initial position is then copied to boards[0], */
5826 /* possibly after shuffling, so that it remains available. */
5828 gameInfo.holdingsWidth = 0; /* default board sizes */
5829 gameInfo.boardWidth = 8;
5830 gameInfo.boardHeight = 8;
5831 gameInfo.holdingsSize = 0;
5832 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
5833 for(i=0; i<BOARD_FILES-2; i++)
5834 initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
5835 initialPosition[EP_STATUS] = EP_NONE;
5836 SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
5837 if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
5838 SetCharTable(pieceNickName, appData.pieceNickNames);
5839 else SetCharTable(pieceNickName, "............");
5842 switch (gameInfo.variant) {
5843 case VariantFischeRandom:
5844 shuffleOpenings = TRUE;
5847 case VariantShatranj:
5848 pieces = ShatranjArray;
5849 nrCastlingRights = 0;
5850 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
5853 pieces = makrukArray;
5854 nrCastlingRights = 0;
5855 startedFromSetupPosition = TRUE;
5856 SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
5858 case VariantTwoKings:
5859 pieces = twoKingsArray;
5862 pieces = GrandArray;
5863 nrCastlingRights = 0;
5864 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5865 gameInfo.boardWidth = 10;
5866 gameInfo.boardHeight = 10;
5867 gameInfo.holdingsSize = 7;
5869 case VariantCapaRandom:
5870 shuffleOpenings = TRUE;
5871 case VariantCapablanca:
5872 pieces = CapablancaArray;
5873 gameInfo.boardWidth = 10;
5874 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5877 pieces = GothicArray;
5878 gameInfo.boardWidth = 10;
5879 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
5882 SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
5883 gameInfo.holdingsSize = 7;
5884 for(i=0; i<BOARD_FILES; i++) initialPosition[VIRGIN][i] = VIRGIN_W | VIRGIN_B;
5887 pieces = JanusArray;
5888 gameInfo.boardWidth = 10;
5889 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
5890 nrCastlingRights = 6;
5891 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
5892 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
5893 initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
5894 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
5895 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
5896 initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
5899 pieces = FalconArray;
5900 gameInfo.boardWidth = 10;
5901 SetCharTable(pieceToChar, "PNBRQ.............FKpnbrq.............fk");
5903 case VariantXiangqi:
5904 pieces = XiangqiArray;
5905 gameInfo.boardWidth = 9;
5906 gameInfo.boardHeight = 10;
5907 nrCastlingRights = 0;
5908 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
5911 pieces = ShogiArray;
5912 gameInfo.boardWidth = 9;
5913 gameInfo.boardHeight = 9;
5914 gameInfo.holdingsSize = 7;
5915 nrCastlingRights = 0;
5916 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
5918 case VariantCourier:
5919 pieces = CourierArray;
5920 gameInfo.boardWidth = 12;
5921 nrCastlingRights = 0;
5922 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
5924 case VariantKnightmate:
5925 pieces = KnightmateArray;
5926 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
5928 case VariantSpartan:
5929 pieces = SpartanArray;
5930 SetCharTable(pieceToChar, "PNBRQ................K......lwg.....c...h..k");
5933 pieces = fairyArray;
5934 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
5937 pieces = GreatArray;
5938 gameInfo.boardWidth = 10;
5939 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
5940 gameInfo.holdingsSize = 8;
5944 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
5945 gameInfo.holdingsSize = 8;
5946 startedFromSetupPosition = TRUE;
5948 case VariantCrazyhouse:
5949 case VariantBughouse:
5951 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
5952 gameInfo.holdingsSize = 5;
5954 case VariantWildCastle:
5956 /* !!?shuffle with kings guaranteed to be on d or e file */
5957 shuffleOpenings = 1;
5959 case VariantNoCastle:
5961 nrCastlingRights = 0;
5962 /* !!?unconstrained back-rank shuffle */
5963 shuffleOpenings = 1;
5968 if(appData.NrFiles >= 0) {
5969 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
5970 gameInfo.boardWidth = appData.NrFiles;
5972 if(appData.NrRanks >= 0) {
5973 gameInfo.boardHeight = appData.NrRanks;
5975 if(appData.holdingsSize >= 0) {
5976 i = appData.holdingsSize;
5977 if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
5978 gameInfo.holdingsSize = i;
5980 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
5981 if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
5982 DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
5984 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
5985 if(pawnRow < 1) pawnRow = 1;
5986 if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand) pawnRow = 2;
5988 /* User pieceToChar list overrules defaults */
5989 if(appData.pieceToCharTable != NULL)
5990 SetCharTable(pieceToChar, appData.pieceToCharTable);
5992 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
5994 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
5995 s = (ChessSquare) 0; /* account holding counts in guard band */
5996 for( i=0; i<BOARD_HEIGHT; i++ )
5997 initialPosition[i][j] = s;
5999 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
6000 initialPosition[gameInfo.variant == VariantGrand][j] = pieces[0][j-gameInfo.holdingsWidth];
6001 initialPosition[pawnRow][j] = WhitePawn;
6002 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
6003 if(gameInfo.variant == VariantXiangqi) {
6005 initialPosition[pawnRow][j] =
6006 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
6007 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
6008 initialPosition[2][j] = WhiteCannon;
6009 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
6013 if(gameInfo.variant == VariantGrand) {
6014 if(j==BOARD_LEFT || j>=BOARD_RGHT-1) {
6015 initialPosition[0][j] = WhiteRook;
6016 initialPosition[BOARD_HEIGHT-1][j] = BlackRook;
6019 initialPosition[BOARD_HEIGHT-1-(gameInfo.variant == VariantGrand)][j] = pieces[1][j-gameInfo.holdingsWidth];
6021 if( (gameInfo.variant == VariantShogi) && !overrule ) {
6024 initialPosition[1][j] = WhiteBishop;
6025 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
6027 initialPosition[1][j] = WhiteRook;
6028 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
6031 if( nrCastlingRights == -1) {
6032 /* [HGM] Build normal castling rights (must be done after board sizing!) */
6033 /* This sets default castling rights from none to normal corners */
6034 /* Variants with other castling rights must set them themselves above */
6035 nrCastlingRights = 6;
6037 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
6038 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
6039 initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
6040 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
6041 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
6042 initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
6045 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
6046 if(gameInfo.variant == VariantGreat) { // promotion commoners
6047 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
6048 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
6049 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
6050 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
6052 if( gameInfo.variant == VariantSChess ) {
6053 initialPosition[1][0] = BlackMarshall;
6054 initialPosition[2][0] = BlackAngel;
6055 initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
6056 initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
6057 initialPosition[1][1] = initialPosition[2][1] =
6058 initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
6060 if (appData.debugMode) {
6061 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
6063 if(shuffleOpenings) {
6064 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
6065 startedFromSetupPosition = TRUE;
6067 if(startedFromPositionFile) {
6068 /* [HGM] loadPos: use PositionFile for every new game */
6069 CopyBoard(initialPosition, filePosition);
6070 for(i=0; i<nrCastlingRights; i++)
6071 initialRights[i] = filePosition[CASTLING][i];
6072 startedFromSetupPosition = TRUE;
6075 CopyBoard(boards[0], initialPosition);
6077 if(oldx != gameInfo.boardWidth ||
6078 oldy != gameInfo.boardHeight ||
6079 oldv != gameInfo.variant ||
6080 oldh != gameInfo.holdingsWidth
6082 InitDrawingSizes(-2 ,0);
6084 oldv = gameInfo.variant;
6086 DrawPosition(TRUE, boards[currentMove]);
6090 SendBoard (ChessProgramState *cps, int moveNum)
6092 char message[MSG_SIZ];
6094 if (cps->useSetboard) {
6095 char* fen = PositionToFEN(moveNum, cps->fenOverride);
6096 snprintf(message, MSG_SIZ,"setboard %s\n", fen);
6097 SendToProgram(message, cps);
6102 int i, j, left=0, right=BOARD_WIDTH;
6103 /* Kludge to set black to move, avoiding the troublesome and now
6104 * deprecated "black" command.
6106 if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
6107 SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn ? "a2a3\n" : "black\n", cps);
6109 if(!cps->extendedEdit) left = BOARD_LEFT, right = BOARD_RGHT; // only board proper
6111 SendToProgram("edit\n", cps);
6112 SendToProgram("#\n", cps);
6113 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6114 bp = &boards[moveNum][i][left];
6115 for (j = left; j < right; j++, bp++) {
6116 if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6117 if ((int) *bp < (int) BlackPawn) {
6118 if(j == BOARD_RGHT+1)
6119 snprintf(message, MSG_SIZ, "%c@%d\n", PieceToChar(*bp), bp[-1]);
6120 else snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp), AAA + j, ONE + i);
6121 if(message[0] == '+' || message[0] == '~') {
6122 snprintf(message, MSG_SIZ,"%c%c%c+\n",
6123 PieceToChar((ChessSquare)(DEMOTED *bp)),
6126 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6127 message[1] = BOARD_RGHT - 1 - j + '1';
6128 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6130 SendToProgram(message, cps);
6135 SendToProgram("c\n", cps);
6136 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6137 bp = &boards[moveNum][i][left];
6138 for (j = left; j < right; j++, bp++) {
6139 if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6140 if (((int) *bp != (int) EmptySquare)
6141 && ((int) *bp >= (int) BlackPawn)) {
6142 if(j == BOARD_LEFT-2)
6143 snprintf(message, MSG_SIZ, "%c@%d\n", ToUpper(PieceToChar(*bp)), bp[1]);
6144 else snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
6146 if(message[0] == '+' || message[0] == '~') {
6147 snprintf(message, MSG_SIZ,"%c%c%c+\n",
6148 PieceToChar((ChessSquare)(DEMOTED *bp)),
6151 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6152 message[1] = BOARD_RGHT - 1 - j + '1';
6153 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6155 SendToProgram(message, cps);
6160 SendToProgram(".\n", cps);
6162 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
6165 char exclusionHeader[MSG_SIZ];
6166 int exCnt, excludePtr;
6167 typedef struct { int ff, fr, tf, tr, pc, mark; } Exclusion;
6168 static Exclusion excluTab[200];
6169 static char excludeMap[(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8]; // [HGM] exclude: bitmap for excluced moves
6175 for(j=0; j<(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8; j++) excludeMap[j] = s;
6176 exclusionHeader[19] = s ? '-' : '+'; // update tail state
6182 safeStrCpy(exclusionHeader, "exclude: none best +tail \n", MSG_SIZ);
6183 excludePtr = 24; exCnt = 0;
6188 UpdateExcludeHeader (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6189 { // search given move in table of header moves, to know where it is listed (and add if not there), and update state
6190 char buf[2*MOVE_LEN], *p;
6191 Exclusion *e = excluTab;
6193 for(i=0; i<exCnt; i++)
6194 if(e[i].ff == fromX && e[i].fr == fromY &&
6195 e[i].tf == toX && e[i].tr == toY && e[i].pc == promoChar) break;
6196 if(i == exCnt) { // was not in exclude list; add it
6197 CoordsToAlgebraic(boards[currentMove], PosFlags(currentMove), fromY, fromX, toY, toX, promoChar, buf);
6198 if(strlen(exclusionHeader + excludePtr) < strlen(buf)) { // no space to write move
6199 if(state != exclusionHeader[19]) exclusionHeader[19] = '*'; // tail is now in mixed state
6202 e[i].ff = fromX; e[i].fr = fromY; e[i].tf = toX; e[i].tr = toY; e[i].pc = promoChar;
6203 excludePtr++; e[i].mark = excludePtr++;
6204 for(p=buf; *p; p++) exclusionHeader[excludePtr++] = *p; // copy move
6207 exclusionHeader[e[i].mark] = state;
6211 ExcludeOneMove (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6212 { // include or exclude the given move, as specified by state ('+' or '-'), or toggle
6216 if((signed char)promoChar == -1) { // kludge to indicate best move
6217 if(!ParseOneMove(lastPV[0], currentMove, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) // get current best move from last PV
6218 return 1; // if unparsable, abort
6220 // update exclusion map (resolving toggle by consulting existing state)
6221 k=(BOARD_FILES*fromY+fromX)*BOARD_RANKS*BOARD_FILES + (BOARD_FILES*toY+toX);
6223 if(state == '*') state = (excludeMap[k] & 1<<j ? '+' : '-'); // toggle
6224 if(state == '-' && !promoChar) // only non-promotions get marked as excluded, to allow exclusion of under-promotions
6225 excludeMap[k] |= 1<<j;
6226 else excludeMap[k] &= ~(1<<j);
6228 UpdateExcludeHeader(fromY, fromX, toY, toX, promoChar, state);
6230 snprintf(buf, MSG_SIZ, "%sclude ", state == '+' ? "in" : "ex");
6231 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, buf+8);
6233 return (state == '+');
6237 ExcludeClick (int index)
6240 Exclusion *e = excluTab;
6241 if(index < 25) { // none, best or tail clicked
6242 if(index < 13) { // none: include all
6243 WriteMap(0); // clear map
6244 for(i=0; i<exCnt; i++) exclusionHeader[excluTab[i].mark] = '+'; // and moves
6245 SendToBoth("include all\n"); // and inform engine
6246 } else if(index > 18) { // tail
6247 if(exclusionHeader[19] == '-') { // tail was excluded
6248 SendToBoth("include all\n");
6249 WriteMap(0); // clear map completely
6250 // now re-exclude selected moves
6251 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '-')
6252 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '-');
6253 } else { // tail was included or in mixed state
6254 SendToBoth("exclude all\n");
6255 WriteMap(0xFF); // fill map completely
6256 // now re-include selected moves
6257 j = 0; // count them
6258 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '+')
6259 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '+'), j++;
6260 if(!j) ExcludeOneMove(0, 0, 0, 0, -1, '+'); // if no moves were selected, keep best
6263 ExcludeOneMove(0, 0, 0, 0, -1, '-'); // exclude it
6266 for(i=0; i<exCnt; i++) if(i == exCnt-1 || excluTab[i+1].mark > index) {
6267 char *p=exclusionHeader + excluTab[i].mark; // do trust header more than map (promotions!)
6268 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, *p == '+' ? '-' : '+');
6275 DefaultPromoChoice (int white)
6278 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
6279 result = WhiteFerz; // no choice
6280 else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
6281 result= WhiteKing; // in Suicide Q is the last thing we want
6282 else if(gameInfo.variant == VariantSpartan)
6283 result = white ? WhiteQueen : WhiteAngel;
6284 else result = WhiteQueen;
6285 if(!white) result = WHITE_TO_BLACK result;
6289 static int autoQueen; // [HGM] oneclick
6292 HasPromotionChoice (int fromX, int fromY, int toX, int toY, char *promoChoice, int sweepSelect)
6294 /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
6295 /* [HGM] add Shogi promotions */
6296 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
6301 if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
6302 if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
6304 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
6305 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
6308 piece = boards[currentMove][fromY][fromX];
6309 if(gameInfo.variant == VariantShogi) {
6310 promotionZoneSize = BOARD_HEIGHT/3;
6311 highestPromotingPiece = (int)WhiteFerz;
6312 } else if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand) {
6313 promotionZoneSize = 3;
6316 // Treat Lance as Pawn when it is not representing Amazon
6317 if(gameInfo.variant != VariantSuper) {
6318 if(piece == WhiteLance) piece = WhitePawn; else
6319 if(piece == BlackLance) piece = BlackPawn;
6322 // next weed out all moves that do not touch the promotion zone at all
6323 if((int)piece >= BlackPawn) {
6324 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
6326 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
6328 if( toY < BOARD_HEIGHT - promotionZoneSize &&
6329 fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
6332 if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
6334 // weed out mandatory Shogi promotions
6335 if(gameInfo.variant == VariantShogi) {
6336 if(piece >= BlackPawn) {
6337 if(toY == 0 && piece == BlackPawn ||
6338 toY == 0 && piece == BlackQueen ||
6339 toY <= 1 && piece == BlackKnight) {
6344 if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
6345 toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
6346 toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
6353 // weed out obviously illegal Pawn moves
6354 if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
6355 if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
6356 if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
6357 if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
6358 if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
6359 // note we are not allowed to test for valid (non-)capture, due to premove
6362 // we either have a choice what to promote to, or (in Shogi) whether to promote
6363 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk) {
6364 *promoChoice = PieceToChar(BlackFerz); // no choice
6367 // no sense asking what we must promote to if it is going to explode...
6368 if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
6369 *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
6372 // give caller the default choice even if we will not make it
6373 *promoChoice = ToLower(PieceToChar(defaultPromoChoice));
6374 if(gameInfo.variant == VariantShogi) *promoChoice = (defaultPromoChoice == piece ? '=' : '+');
6375 if( sweepSelect && gameInfo.variant != VariantGreat
6376 && gameInfo.variant != VariantGrand
6377 && gameInfo.variant != VariantSuper) return FALSE;
6378 if(autoQueen) return FALSE; // predetermined
6380 // suppress promotion popup on illegal moves that are not premoves
6381 premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
6382 gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
6383 if(appData.testLegality && !premove) {
6384 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6385 fromY, fromX, toY, toX, gameInfo.variant == VariantShogi ? '+' : NULLCHAR);
6386 if(moveType != WhitePromotion && moveType != BlackPromotion)
6394 InPalace (int row, int column)
6395 { /* [HGM] for Xiangqi */
6396 if( (row < 3 || row > BOARD_HEIGHT-4) &&
6397 column < (BOARD_WIDTH + 4)/2 &&
6398 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
6403 PieceForSquare (int x, int y)
6405 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
6408 return boards[currentMove][y][x];
6412 OKToStartUserMove (int x, int y)
6414 ChessSquare from_piece;
6417 if (matchMode) return FALSE;
6418 if (gameMode == EditPosition) return TRUE;
6420 if (x >= 0 && y >= 0)
6421 from_piece = boards[currentMove][y][x];
6423 from_piece = EmptySquare;
6425 if (from_piece == EmptySquare) return FALSE;
6427 white_piece = (int)from_piece >= (int)WhitePawn &&
6428 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
6432 case TwoMachinesPlay:
6440 case MachinePlaysWhite:
6441 case IcsPlayingBlack:
6442 if (appData.zippyPlay) return FALSE;
6444 DisplayMoveError(_("You are playing Black"));
6449 case MachinePlaysBlack:
6450 case IcsPlayingWhite:
6451 if (appData.zippyPlay) return FALSE;
6453 DisplayMoveError(_("You are playing White"));
6458 case PlayFromGameFile:
6459 if(!shiftKey || !appData.variations) return FALSE; // [HGM] allow starting variation in this mode
6461 if (!white_piece && WhiteOnMove(currentMove)) {
6462 DisplayMoveError(_("It is White's turn"));
6465 if (white_piece && !WhiteOnMove(currentMove)) {
6466 DisplayMoveError(_("It is Black's turn"));
6469 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
6470 /* Editing correspondence game history */
6471 /* Could disallow this or prompt for confirmation */
6476 case BeginningOfGame:
6477 if (appData.icsActive) return FALSE;
6478 if (!appData.noChessProgram) {
6480 DisplayMoveError(_("You are playing White"));
6487 if (!white_piece && WhiteOnMove(currentMove)) {
6488 DisplayMoveError(_("It is White's turn"));
6491 if (white_piece && !WhiteOnMove(currentMove)) {
6492 DisplayMoveError(_("It is Black's turn"));
6501 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
6502 && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
6503 && gameMode != PlayFromGameFile // [HGM] as EditGame, with protected main line
6504 && gameMode != AnalyzeFile && gameMode != Training) {
6505 DisplayMoveError(_("Displayed position is not current"));
6512 OnlyMove (int *x, int *y, Boolean captures)
6514 DisambiguateClosure cl;
6515 if (appData.zippyPlay || !appData.testLegality) return FALSE;
6517 case MachinePlaysBlack:
6518 case IcsPlayingWhite:
6519 case BeginningOfGame:
6520 if(!WhiteOnMove(currentMove)) return FALSE;
6522 case MachinePlaysWhite:
6523 case IcsPlayingBlack:
6524 if(WhiteOnMove(currentMove)) return FALSE;
6531 cl.pieceIn = EmptySquare;
6536 cl.promoCharIn = NULLCHAR;
6537 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6538 if( cl.kind == NormalMove ||
6539 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6540 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6541 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6548 if(cl.kind != ImpossibleMove) return FALSE;
6549 cl.pieceIn = EmptySquare;
6554 cl.promoCharIn = NULLCHAR;
6555 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6556 if( cl.kind == NormalMove ||
6557 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6558 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6559 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6564 autoQueen = TRUE; // act as if autoQueen on when we click to-square
6570 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
6571 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
6572 int lastLoadGameUseList = FALSE;
6573 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
6574 ChessMove lastLoadGameStart = EndOfFile;
6578 UserMoveEvent(int fromX, int fromY, int toX, int toY, int promoChar)
6582 int ff=fromX, rf=fromY, ft=toX, rt=toY;
6584 /* Check if the user is playing in turn. This is complicated because we
6585 let the user "pick up" a piece before it is his turn. So the piece he
6586 tried to pick up may have been captured by the time he puts it down!
6587 Therefore we use the color the user is supposed to be playing in this
6588 test, not the color of the piece that is currently on the starting
6589 square---except in EditGame mode, where the user is playing both
6590 sides; fortunately there the capture race can't happen. (It can
6591 now happen in IcsExamining mode, but that's just too bad. The user
6592 will get a somewhat confusing message in that case.)
6597 case TwoMachinesPlay:
6601 /* We switched into a game mode where moves are not accepted,
6602 perhaps while the mouse button was down. */
6605 case MachinePlaysWhite:
6606 /* User is moving for Black */
6607 if (WhiteOnMove(currentMove)) {
6608 DisplayMoveError(_("It is White's turn"));
6613 case MachinePlaysBlack:
6614 /* User is moving for White */
6615 if (!WhiteOnMove(currentMove)) {
6616 DisplayMoveError(_("It is Black's turn"));
6621 case PlayFromGameFile:
6622 if(!shiftKey ||!appData.variations) return; // [HGM] only variations
6625 case BeginningOfGame:
6628 if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
6629 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
6630 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
6631 /* User is moving for Black */
6632 if (WhiteOnMove(currentMove)) {
6633 DisplayMoveError(_("It is White's turn"));
6637 /* User is moving for White */
6638 if (!WhiteOnMove(currentMove)) {
6639 DisplayMoveError(_("It is Black's turn"));
6645 case IcsPlayingBlack:
6646 /* User is moving for Black */
6647 if (WhiteOnMove(currentMove)) {
6648 if (!appData.premove) {
6649 DisplayMoveError(_("It is White's turn"));
6650 } else if (toX >= 0 && toY >= 0) {
6653 premoveFromX = fromX;
6654 premoveFromY = fromY;
6655 premovePromoChar = promoChar;
6657 if (appData.debugMode)
6658 fprintf(debugFP, "Got premove: fromX %d,"
6659 "fromY %d, toX %d, toY %d\n",
6660 fromX, fromY, toX, toY);
6666 case IcsPlayingWhite:
6667 /* User is moving for White */
6668 if (!WhiteOnMove(currentMove)) {
6669 if (!appData.premove) {
6670 DisplayMoveError(_("It is Black's turn"));
6671 } else if (toX >= 0 && toY >= 0) {
6674 premoveFromX = fromX;
6675 premoveFromY = fromY;
6676 premovePromoChar = promoChar;
6678 if (appData.debugMode)
6679 fprintf(debugFP, "Got premove: fromX %d,"
6680 "fromY %d, toX %d, toY %d\n",
6681 fromX, fromY, toX, toY);
6691 /* EditPosition, empty square, or different color piece;
6692 click-click move is possible */
6693 if (toX == -2 || toY == -2) {
6694 boards[0][fromY][fromX] = EmptySquare;
6695 DrawPosition(FALSE, boards[currentMove]);
6697 } else if (toX >= 0 && toY >= 0) {
6698 boards[0][toY][toX] = boards[0][fromY][fromX];
6699 if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
6700 if(boards[0][fromY][0] != EmptySquare) {
6701 if(boards[0][fromY][1]) boards[0][fromY][1]--;
6702 if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
6705 if(fromX == BOARD_RGHT+1) {
6706 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
6707 if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
6708 if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
6711 boards[0][fromY][fromX] = gatingPiece;
6712 DrawPosition(FALSE, boards[currentMove]);
6718 if(toX < 0 || toY < 0) return;
6719 pup = boards[currentMove][toY][toX];
6721 /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
6722 if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
6723 if( pup != EmptySquare ) return;
6724 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
6725 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
6726 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
6727 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
6728 if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
6729 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
6730 while(PieceToChar(fromX) == '.' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
6734 /* [HGM] always test for legality, to get promotion info */
6735 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6736 fromY, fromX, toY, toX, promoChar);
6738 if(fromY == DROP_RANK && fromX == EmptySquare && (gameMode == AnalyzeMode || gameMode == EditGame)) moveType = NormalMove;
6740 /* [HGM] but possibly ignore an IllegalMove result */
6741 if (appData.testLegality) {
6742 if (moveType == IllegalMove || moveType == ImpossibleMove) {
6743 DisplayMoveError(_("Illegal move"));
6748 if(doubleClick) { // [HGM] exclude: move entered with double-click on from square is for exclusion, not playing
6749 if(ExcludeOneMove(fromY, fromX, toY, toX, promoChar, '*')) // toggle
6750 ClearPremoveHighlights(); // was included
6751 else ClearHighlights(), SetPremoveHighlights(ff, rf, ft, rt); // exclusion indicated by premove highlights
6755 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
6758 /* Common tail of UserMoveEvent and DropMenuEvent */
6760 FinishMove (ChessMove moveType, int fromX, int fromY, int toX, int toY, int promoChar)
6764 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) && promoChar != NULLCHAR) {
6765 // [HGM] superchess: suppress promotions to non-available piece (but P always allowed)
6766 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
6767 if(WhiteOnMove(currentMove)) {
6768 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
6770 if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
6774 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
6775 move type in caller when we know the move is a legal promotion */
6776 if(moveType == NormalMove && promoChar)
6777 moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
6779 /* [HGM] <popupFix> The following if has been moved here from
6780 UserMoveEvent(). Because it seemed to belong here (why not allow
6781 piece drops in training games?), and because it can only be
6782 performed after it is known to what we promote. */
6783 if (gameMode == Training) {
6784 /* compare the move played on the board to the next move in the
6785 * game. If they match, display the move and the opponent's response.
6786 * If they don't match, display an error message.
6790 CopyBoard(testBoard, boards[currentMove]);
6791 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
6793 if (CompareBoards(testBoard, boards[currentMove+1])) {
6794 ForwardInner(currentMove+1);
6796 /* Autoplay the opponent's response.
6797 * if appData.animate was TRUE when Training mode was entered,
6798 * the response will be animated.
6800 saveAnimate = appData.animate;
6801 appData.animate = animateTraining;
6802 ForwardInner(currentMove+1);
6803 appData.animate = saveAnimate;
6805 /* check for the end of the game */
6806 if (currentMove >= forwardMostMove) {
6807 gameMode = PlayFromGameFile;
6809 SetTrainingModeOff();
6810 DisplayInformation(_("End of game"));
6813 DisplayError(_("Incorrect move"), 0);
6818 /* Ok, now we know that the move is good, so we can kill
6819 the previous line in Analysis Mode */
6820 if ((gameMode == AnalyzeMode || gameMode == EditGame || gameMode == PlayFromGameFile && appData.variations && shiftKey)
6821 && currentMove < forwardMostMove) {
6822 if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
6823 else forwardMostMove = currentMove;
6828 /* If we need the chess program but it's dead, restart it */
6829 ResurrectChessProgram();
6831 /* A user move restarts a paused game*/
6835 thinkOutput[0] = NULLCHAR;
6837 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
6839 if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
6840 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6844 if (gameMode == BeginningOfGame) {
6845 if (appData.noChessProgram) {
6846 gameMode = EditGame;
6850 gameMode = MachinePlaysBlack;
6853 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
6855 if (first.sendName) {
6856 snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
6857 SendToProgram(buf, &first);
6864 /* Relay move to ICS or chess engine */
6865 if (appData.icsActive) {
6866 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
6867 gameMode == IcsExamining) {
6868 if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
6869 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
6871 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6873 // also send plain move, in case ICS does not understand atomic claims
6874 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
6878 if (first.sendTime && (gameMode == BeginningOfGame ||
6879 gameMode == MachinePlaysWhite ||
6880 gameMode == MachinePlaysBlack)) {
6881 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
6883 if (gameMode != EditGame && gameMode != PlayFromGameFile && gameMode != AnalyzeMode) {
6884 // [HGM] book: if program might be playing, let it use book
6885 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
6886 first.maybeThinking = TRUE;
6887 } else if(fromY == DROP_RANK && fromX == EmptySquare) {
6888 if(!first.useSetboard) SendToProgram("undo\n", &first); // kludge to change stm in engines that do not support setboard
6889 SendBoard(&first, currentMove+1);
6890 if(second.analyzing) {
6891 if(!second.useSetboard) SendToProgram("undo\n", &second);
6892 SendBoard(&second, currentMove+1);
6895 SendMoveToProgram(forwardMostMove-1, &first);
6896 if(second.analyzing) SendMoveToProgram(forwardMostMove-1, &second);
6898 if (currentMove == cmailOldMove + 1) {
6899 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
6903 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
6907 if(appData.testLegality)
6908 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
6914 if (WhiteOnMove(currentMove)) {
6915 GameEnds(BlackWins, "Black mates", GE_PLAYER);
6917 GameEnds(WhiteWins, "White mates", GE_PLAYER);
6921 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
6926 case MachinePlaysBlack:
6927 case MachinePlaysWhite:
6928 /* disable certain menu options while machine is thinking */
6929 SetMachineThinkingEnables();
6936 userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
6937 promoDefaultAltered = FALSE; // [HGM] fall back on default choice
6939 if(bookHit) { // [HGM] book: simulate book reply
6940 static char bookMove[MSG_SIZ]; // a bit generous?
6942 programStats.nodes = programStats.depth = programStats.time =
6943 programStats.score = programStats.got_only_move = 0;
6944 sprintf(programStats.movelist, "%s (xbook)", bookHit);
6946 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
6947 strcat(bookMove, bookHit);
6948 HandleMachineMove(bookMove, &first);
6954 Mark (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
6956 typedef char Markers[BOARD_RANKS][BOARD_FILES];
6957 Markers *m = (Markers *) closure;
6958 if(rf == fromY && ff == fromX)
6959 (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
6960 || kind == WhiteCapturesEnPassant
6961 || kind == BlackCapturesEnPassant);
6962 else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3;
6966 MarkTargetSquares (int clear)
6969 if(clear) // no reason to ever suppress clearing
6970 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) marker[y][x] = 0;
6971 if(!appData.markers || !appData.highlightDragging || appData.icsActive && gameInfo.variant < VariantShogi ||
6972 !appData.testLegality || gameMode == EditPosition) return;
6975 GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker, EmptySquare);
6976 if(PosFlags(0) & F_MANDATORY_CAPTURE) {
6977 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
6979 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
6982 DrawPosition(FALSE, NULL);
6986 Explode (Board board, int fromX, int fromY, int toX, int toY)
6988 if(gameInfo.variant == VariantAtomic &&
6989 (board[toY][toX] != EmptySquare || // capture?
6990 toX != fromX && (board[fromY][fromX] == WhitePawn || // e.p. ?
6991 board[fromY][fromX] == BlackPawn )
6993 AnimateAtomicCapture(board, fromX, fromY, toX, toY);
6999 ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
7002 CanPromote (ChessSquare piece, int y)
7004 if(gameMode == EditPosition) return FALSE; // no promotions when editing position
7005 // some variants have fixed promotion piece, no promotion at all, or another selection mechanism
7006 if(gameInfo.variant == VariantShogi || gameInfo.variant == VariantXiangqi ||
7007 gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat ||
7008 gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
7009 gameInfo.variant == VariantMakruk) return FALSE;
7010 return (piece == BlackPawn && y == 1 ||
7011 piece == WhitePawn && y == BOARD_HEIGHT-2 ||
7012 piece == BlackLance && y == 1 ||
7013 piece == WhiteLance && y == BOARD_HEIGHT-2 );
7017 LeftClick (ClickType clickType, int xPix, int yPix)
7020 Boolean saveAnimate;
7021 static int second = 0, promotionChoice = 0, clearFlag = 0, sweepSelecting = 0;
7022 char promoChoice = NULLCHAR;
7024 static TimeMark lastClickTime, prevClickTime;
7026 if(SeekGraphClick(clickType, xPix, yPix, 0)) return;
7028 prevClickTime = lastClickTime; GetTimeMark(&lastClickTime);
7030 if (clickType == Press) ErrorPopDown();
7032 x = EventToSquare(xPix, BOARD_WIDTH);
7033 y = EventToSquare(yPix, BOARD_HEIGHT);
7034 if (!flipView && y >= 0) {
7035 y = BOARD_HEIGHT - 1 - y;
7037 if (flipView && x >= 0) {
7038 x = BOARD_WIDTH - 1 - x;
7041 if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
7042 defaultPromoChoice = promoSweep;
7043 promoSweep = EmptySquare; // terminate sweep
7044 promoDefaultAltered = TRUE;
7045 if(!selectFlag && !sweepSelecting && (x != toX || y != toY)) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
7048 if(promotionChoice) { // we are waiting for a click to indicate promotion piece
7049 if(clickType == Release) return; // ignore upclick of click-click destination
7050 promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
7051 if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
7052 if(gameInfo.holdingsWidth &&
7053 (WhiteOnMove(currentMove)
7054 ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y >= 0
7055 : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT) ) {
7056 // click in right holdings, for determining promotion piece
7057 ChessSquare p = boards[currentMove][y][x];
7058 if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
7059 if(p == WhitePawn || p == BlackPawn) p = EmptySquare; // [HGM] Pawns could be valid as deferral
7060 if(p != EmptySquare || gameInfo.variant == VariantGrand && toY != 0 && toY != BOARD_HEIGHT-1) { // [HGM] grand: empty square means defer
7061 FinishMove(NormalMove, fromX, fromY, toX, toY, p==EmptySquare ? NULLCHAR : ToLower(PieceToChar(p)));
7066 DrawPosition(FALSE, boards[currentMove]);
7070 /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
7071 if(clickType == Press
7072 && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
7073 || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
7074 || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
7077 if(gotPremove && x == premoveFromX && y == premoveFromY && clickType == Release) {
7078 // could be static click on premove from-square: abort premove
7080 ClearPremoveHighlights();
7083 if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered && SubtractTimeMarks(&lastClickTime, &prevClickTime) >= 200)
7084 fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
7086 if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
7087 int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
7088 gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
7089 defaultPromoChoice = DefaultPromoChoice(side);
7092 autoQueen = appData.alwaysPromoteToQueen;
7096 gatingPiece = EmptySquare;
7097 if (clickType != Press) {
7098 if(dragging) { // [HGM] from-square must have been reset due to game end since last press
7099 DragPieceEnd(xPix, yPix); dragging = 0;
7100 DrawPosition(FALSE, NULL);
7104 doubleClick = FALSE;
7105 fromX = x; fromY = y; toX = toY = -1;
7106 if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
7107 // even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
7108 appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
7110 if (OKToStartUserMove(fromX, fromY)) {
7112 MarkTargetSquares(0);
7113 if(gameMode == EditPosition && controlKey) gatingPiece = boards[currentMove][fromY][fromX];
7114 DragPieceBegin(xPix, yPix, FALSE); dragging = 1;
7115 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
7116 promoSweep = defaultPromoChoice;
7117 selectFlag = 0; lastX = xPix; lastY = yPix;
7118 Sweep(0); // Pawn that is going to promote: preview promotion piece
7119 DisplayMessage("", _("Pull pawn backwards to under-promote"));
7121 if (appData.highlightDragging) {
7122 SetHighlights(fromX, fromY, -1, -1);
7126 } else fromX = fromY = -1;
7132 if (clickType == Press && gameMode != EditPosition) {
7137 // ignore off-board to clicks
7138 if(y < 0 || x < 0) return;
7140 /* Check if clicking again on the same color piece */
7141 fromP = boards[currentMove][fromY][fromX];
7142 toP = boards[currentMove][y][x];
7143 frc = gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom || gameInfo.variant == VariantSChess;
7144 if ((WhitePawn <= fromP && fromP <= WhiteKing &&
7145 WhitePawn <= toP && toP <= WhiteKing &&
7146 !(fromP == WhiteKing && toP == WhiteRook && frc) &&
7147 !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
7148 (BlackPawn <= fromP && fromP <= BlackKing &&
7149 BlackPawn <= toP && toP <= BlackKing &&
7150 !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
7151 !(fromP == BlackKing && toP == BlackRook && frc))) {
7152 /* Clicked again on same color piece -- changed his mind */
7153 second = (x == fromX && y == fromY);
7154 if(second && gameMode == AnalyzeMode && SubtractTimeMarks(&lastClickTime, &prevClickTime) < 200) {
7155 second = FALSE; // first double-click rather than scond click
7156 doubleClick = first.excludeMoves; // used by UserMoveEvent to recognize exclude moves
7158 promoDefaultAltered = FALSE;
7159 MarkTargetSquares(1);
7160 if(!second || appData.oneClick && !OnlyMove(&x, &y, TRUE)) {
7161 if (appData.highlightDragging) {
7162 SetHighlights(x, y, -1, -1);
7166 if (OKToStartUserMove(x, y)) {
7167 if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
7168 (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
7169 y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
7170 gatingPiece = boards[currentMove][fromY][fromX];
7171 else gatingPiece = doubleClick ? fromP : EmptySquare;
7173 fromY = y; dragging = 1;
7174 MarkTargetSquares(0);
7175 DragPieceBegin(xPix, yPix, FALSE);
7176 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
7177 promoSweep = defaultPromoChoice;
7178 selectFlag = 0; lastX = xPix; lastY = yPix;
7179 Sweep(0); // Pawn that is going to promote: preview promotion piece
7183 if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
7186 // ignore clicks on holdings
7187 if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
7190 if (clickType == Release && x == fromX && y == fromY) {
7191 DragPieceEnd(xPix, yPix); dragging = 0;
7193 // a deferred attempt to click-click move an empty square on top of a piece
7194 boards[currentMove][y][x] = EmptySquare;
7196 DrawPosition(FALSE, boards[currentMove]);
7197 fromX = fromY = -1; clearFlag = 0;
7200 if (appData.animateDragging) {
7201 /* Undo animation damage if any */
7202 DrawPosition(FALSE, NULL);
7204 if (second || sweepSelecting) {
7205 /* Second up/down in same square; just abort move */
7206 if(sweepSelecting) DrawPosition(FALSE, boards[currentMove]);
7207 second = sweepSelecting = 0;
7209 gatingPiece = EmptySquare;
7212 ClearPremoveHighlights();
7214 /* First upclick in same square; start click-click mode */
7215 SetHighlights(x, y, -1, -1);
7222 /* we now have a different from- and (possibly off-board) to-square */
7223 /* Completed move */
7224 if(!sweepSelecting) {
7227 } else sweepSelecting = 0; // this must be the up-click corresponding to the down-click that started the sweep
7229 saveAnimate = appData.animate;
7230 if (clickType == Press) {
7231 if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
7232 // must be Edit Position mode with empty-square selected
7233 fromX = x; fromY = y; DragPieceBegin(xPix, yPix, FALSE); dragging = 1; // consider this a new attempt to drag
7234 if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
7237 if(HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, FALSE)) {
7238 if(appData.sweepSelect) {
7239 ChessSquare piece = boards[currentMove][fromY][fromX];
7240 promoSweep = defaultPromoChoice;
7241 if(PieceToChar(PROMOTED piece) == '+') promoSweep = PROMOTED piece;
7242 selectFlag = 0; lastX = xPix; lastY = yPix;
7243 Sweep(0); // Pawn that is going to promote: preview promotion piece
7245 DisplayMessage("", _("Pull pawn backwards to under-promote"));
7246 MarkTargetSquares(1);
7248 return; // promo popup appears on up-click
7250 /* Finish clickclick move */
7251 if (appData.animate || appData.highlightLastMove) {
7252 SetHighlights(fromX, fromY, toX, toY);
7257 /* Finish drag move */
7258 if (appData.highlightLastMove) {
7259 SetHighlights(fromX, fromY, toX, toY);
7263 DragPieceEnd(xPix, yPix); dragging = 0;
7264 /* Don't animate move and drag both */
7265 appData.animate = FALSE;
7267 MarkTargetSquares(1);
7269 // moves into holding are invalid for now (except in EditPosition, adapting to-square)
7270 if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
7271 ChessSquare piece = boards[currentMove][fromY][fromX];
7272 if(gameMode == EditPosition && piece != EmptySquare &&
7273 fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
7276 if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
7277 n = PieceToNumber(piece - (int)BlackPawn);
7278 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
7279 boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
7280 boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
7282 if(x == BOARD_RGHT+1 && piece < BlackPawn) {
7283 n = PieceToNumber(piece);
7284 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
7285 boards[currentMove][n][BOARD_WIDTH-1] = piece;
7286 boards[currentMove][n][BOARD_WIDTH-2]++;
7288 boards[currentMove][fromY][fromX] = EmptySquare;
7292 DrawPosition(TRUE, boards[currentMove]);
7296 // off-board moves should not be highlighted
7297 if(x < 0 || y < 0) ClearHighlights();
7299 if(gatingPiece != EmptySquare && gameInfo.variant == VariantSChess) promoChoice = ToLower(PieceToChar(gatingPiece));
7301 if (HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, appData.sweepSelect)) {
7302 SetHighlights(fromX, fromY, toX, toY);
7303 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
7304 // [HGM] super: promotion to captured piece selected from holdings
7305 ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
7306 promotionChoice = TRUE;
7307 // kludge follows to temporarily execute move on display, without promoting yet
7308 boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
7309 boards[currentMove][toY][toX] = p;
7310 DrawPosition(FALSE, boards[currentMove]);
7311 boards[currentMove][fromY][fromX] = p; // take back, but display stays
7312 boards[currentMove][toY][toX] = q;
7313 DisplayMessage("Click in holdings to choose piece", "");
7318 int oldMove = currentMove;
7319 UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
7320 if (!appData.highlightLastMove || gotPremove) ClearHighlights();
7321 if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
7322 if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
7323 Explode(boards[currentMove-1], fromX, fromY, toX, toY))
7324 DrawPosition(TRUE, boards[currentMove]);
7327 appData.animate = saveAnimate;
7328 if (appData.animate || appData.animateDragging) {
7329 /* Undo animation damage if needed */
7330 DrawPosition(FALSE, NULL);
7335 RightClick (ClickType action, int x, int y, int *fromX, int *fromY)
7336 { // front-end-free part taken out of PieceMenuPopup
7337 int whichMenu; int xSqr, ySqr;
7339 if(seekGraphUp) { // [HGM] seekgraph
7340 if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
7341 if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
7345 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
7346 && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
7347 if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
7348 if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
7349 if(action == Press) {
7350 originalFlip = flipView;
7351 flipView = !flipView; // temporarily flip board to see game from partners perspective
7352 DrawPosition(TRUE, partnerBoard);
7353 DisplayMessage(partnerStatus, "");
7355 } else if(action == Release) {
7356 flipView = originalFlip;
7357 DrawPosition(TRUE, boards[currentMove]);
7363 xSqr = EventToSquare(x, BOARD_WIDTH);
7364 ySqr = EventToSquare(y, BOARD_HEIGHT);
7365 if (action == Release) {
7366 if(pieceSweep != EmptySquare) {
7367 EditPositionMenuEvent(pieceSweep, toX, toY);
7368 pieceSweep = EmptySquare;
7369 } else UnLoadPV(); // [HGM] pv
7371 if (action != Press) return -2; // return code to be ignored
7374 if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
7376 if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
7377 if (xSqr < 0 || ySqr < 0) return -1;
7378 if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
7379 pieceSweep = shiftKey ? BlackPawn : WhitePawn; // [HGM] sweep: prepare selecting piece by mouse sweep
7380 toX = xSqr; toY = ySqr; lastX = x, lastY = y;
7381 if(flipView) toX = BOARD_WIDTH - 1 - toX; else toY = BOARD_HEIGHT - 1 - toY;
7385 if(!appData.icsEngineAnalyze) return -1;
7386 case IcsPlayingWhite:
7387 case IcsPlayingBlack:
7388 if(!appData.zippyPlay) goto noZip;
7391 case MachinePlaysWhite:
7392 case MachinePlaysBlack:
7393 case TwoMachinesPlay: // [HGM] pv: use for showing PV
7394 if (!appData.dropMenu) {
7396 return 2; // flag front-end to grab mouse events
7398 if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
7399 gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
7402 if (xSqr < 0 || ySqr < 0) return -1;
7403 if (!appData.dropMenu || appData.testLegality &&
7404 gameInfo.variant != VariantBughouse &&
7405 gameInfo.variant != VariantCrazyhouse) return -1;
7406 whichMenu = 1; // drop menu
7412 if (((*fromX = xSqr) < 0) ||
7413 ((*fromY = ySqr) < 0)) {
7414 *fromX = *fromY = -1;
7418 *fromX = BOARD_WIDTH - 1 - *fromX;
7420 *fromY = BOARD_HEIGHT - 1 - *fromY;
7426 SendProgramStatsToFrontend (ChessProgramState * cps, ChessProgramStats * cpstats)
7428 // char * hint = lastHint;
7429 FrontEndProgramStats stats;
7431 stats.which = cps == &first ? 0 : 1;
7432 stats.depth = cpstats->depth;
7433 stats.nodes = cpstats->nodes;
7434 stats.score = cpstats->score;
7435 stats.time = cpstats->time;
7436 stats.pv = cpstats->movelist;
7437 stats.hint = lastHint;
7438 stats.an_move_index = 0;
7439 stats.an_move_count = 0;
7441 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
7442 stats.hint = cpstats->move_name;
7443 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
7444 stats.an_move_count = cpstats->nr_moves;
7447 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
7449 SetProgramStats( &stats );
7453 ClearEngineOutputPane (int which)
7455 static FrontEndProgramStats dummyStats;
7456 dummyStats.which = which;
7457 dummyStats.pv = "#";
7458 SetProgramStats( &dummyStats );
7461 #define MAXPLAYERS 500
7464 TourneyStandings (int display)
7466 int i, w, b, color, wScore, bScore, dummy, nr=0, nPlayers=0;
7467 int score[MAXPLAYERS], ranking[MAXPLAYERS], points[MAXPLAYERS], games[MAXPLAYERS];
7468 char result, *p, *names[MAXPLAYERS];
7470 if(appData.tourneyType < 0 && !strchr(appData.results, '*'))
7471 return strdup(_("Swiss tourney finished")); // standings of Swiss yet TODO
7472 names[0] = p = strdup(appData.participants);
7473 while(p = strchr(p, '\n')) *p++ = NULLCHAR, names[++nPlayers] = p; // count participants
7475 for(i=0; i<nPlayers; i++) score[i] = games[i] = 0;
7477 while(result = appData.results[nr]) {
7478 color = Pairing(nr, nPlayers, &w, &b, &dummy);
7479 if(!(color ^ matchGame & 1)) { dummy = w; w = b; b = dummy; }
7480 wScore = bScore = 0;
7482 case '+': wScore = 2; break;
7483 case '-': bScore = 2; break;
7484 case '=': wScore = bScore = 1; break;
7486 case '*': return strdup("busy"); // tourney not finished
7494 if(appData.tourneyType > 0) nPlayers = appData.tourneyType; // in gauntlet, list only gauntlet engine(s)
7495 for(w=0; w<nPlayers; w++) {
7497 for(i=0; i<nPlayers; i++) if(score[i] > bScore) bScore = score[i], b = i;
7498 ranking[w] = b; points[w] = bScore; score[b] = -2;
7500 p = malloc(nPlayers*34+1);
7501 for(w=0; w<nPlayers && w<display; w++)
7502 sprintf(p+34*w, "%2d. %5.1f/%-3d %-19.19s\n", w+1, points[w]/2., games[ranking[w]], names[ranking[w]]);
7508 Count (Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
7509 { // count all piece types
7511 *nB = *nW = *wStale = *bStale = *bishopColor = 0;
7512 for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
7513 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
7516 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
7517 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
7518 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
7519 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
7520 p == BlackBishop || p == BlackFerz || p == BlackAlfil )
7521 *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
7526 SufficientDefence (int pCnt[], int side, int nMine, int nHis)
7528 int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
7529 int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
7531 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
7532 if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
7533 if(myPawns == 2 && nMine == 3) // KPP
7534 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
7535 if(myPawns == 1 && nMine == 2) // KP
7536 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
7537 if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
7538 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
7539 if(myPawns) return FALSE;
7540 if(pCnt[WhiteRook+side])
7541 return pCnt[BlackRook-side] ||
7542 pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
7543 pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
7544 pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
7545 if(pCnt[WhiteCannon+side]) {
7546 if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
7547 return majorDefense || pCnt[BlackAlfil-side] >= 2;
7549 if(pCnt[WhiteKnight+side])
7550 return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
7555 MatingPotential (int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
7557 VariantClass v = gameInfo.variant;
7559 if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
7560 if(v == VariantShatranj) return TRUE; // always winnable through baring
7561 if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
7562 if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
7564 if(v == VariantXiangqi) {
7565 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
7567 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
7568 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
7569 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
7570 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
7571 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
7572 if(stale) // we have at least one last-rank P plus perhaps C
7573 return majors // KPKX
7574 || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
7576 return pCnt[WhiteFerz+side] // KCAK
7577 || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
7578 || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
7579 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
7581 } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
7582 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
7584 if(nMine == 1) return FALSE; // bare King
7585 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
7586 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
7587 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
7588 // by now we have King + 1 piece (or multiple Bishops on the same color)
7589 if(pCnt[WhiteKnight+side])
7590 return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
7591 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
7592 || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
7594 return (pCnt[BlackKnight-side]); // KBKN, KFKN
7595 if(pCnt[WhiteAlfil+side])
7596 return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
7597 if(pCnt[WhiteWazir+side])
7598 return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
7605 CompareWithRights (Board b1, Board b2)
7608 if(!CompareBoards(b1, b2)) return FALSE;
7609 if(b1[EP_STATUS] != b2[EP_STATUS]) return FALSE;
7610 /* compare castling rights */
7611 if( b1[CASTLING][2] != b2[CASTLING][2] && (b2[CASTLING][0] != NoRights || b2[CASTLING][1] != NoRights) )
7612 rights++; /* King lost rights, while rook still had them */
7613 if( b1[CASTLING][2] != NoRights ) { /* king has rights */
7614 if( b1[CASTLING][0] != b2[CASTLING][0] || b1[CASTLING][1] != b2[CASTLING][1] )
7615 rights++; /* but at least one rook lost them */
7617 if( b1[CASTLING][5] != b1[CASTLING][5] && (b2[CASTLING][3] != NoRights || b2[CASTLING][4] != NoRights) )
7619 if( b1[CASTLING][5] != NoRights ) {
7620 if( b1[CASTLING][3] != b2[CASTLING][3] || b1[CASTLING][4] != b2[CASTLING][4] )
7627 Adjudicate (ChessProgramState *cps)
7628 { // [HGM] some adjudications useful with buggy engines
7629 // [HGM] adjudicate: made into separate routine, which now can be called after every move
7630 // In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
7631 // Actually ending the game is now based on the additional internal condition canAdjudicate.
7632 // Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
7633 int k, count = 0; static int bare = 1;
7634 ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
7635 Boolean canAdjudicate = !appData.icsActive;
7637 // most tests only when we understand the game, i.e. legality-checking on
7638 if( appData.testLegality )
7639 { /* [HGM] Some more adjudications for obstinate engines */
7640 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+1], i;
7641 static int moveCount = 6;
7643 char *reason = NULL;
7645 /* Count what is on board. */
7646 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
7648 /* Some material-based adjudications that have to be made before stalemate test */
7649 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
7650 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
7651 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
7652 if(canAdjudicate && appData.checkMates) {
7654 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7655 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
7656 "Xboard adjudication: King destroyed", GE_XBOARD );
7661 /* Bare King in Shatranj (loses) or Losers (wins) */
7662 if( nrW == 1 || nrB == 1) {
7663 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
7664 boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
7665 if(canAdjudicate && appData.checkMates) {
7667 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
7668 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
7669 "Xboard adjudication: Bare king", GE_XBOARD );
7673 if( gameInfo.variant == VariantShatranj && --bare < 0)
7675 boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
7676 if(canAdjudicate && appData.checkMates) {
7677 /* but only adjudicate if adjudication enabled */
7679 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
7680 GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
7681 "Xboard adjudication: Bare king", GE_XBOARD );
7688 // don't wait for engine to announce game end if we can judge ourselves
7689 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
7691 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
7692 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
7693 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
7694 if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
7697 reason = "Xboard adjudication: 3rd check";
7698 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
7708 reason = "Xboard adjudication: Stalemate";
7709 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
7710 boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
7711 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
7712 boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
7713 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
7714 boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
7715 ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
7716 EP_CHECKMATE : EP_WINS);
7717 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi)
7718 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
7722 reason = "Xboard adjudication: Checkmate";
7723 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
7727 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
7729 result = GameIsDrawn; break;
7731 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
7733 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
7737 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
7739 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7740 GameEnds( result, reason, GE_XBOARD );
7744 /* Next absolutely insufficient mating material. */
7745 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
7746 !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
7747 { /* includes KBK, KNK, KK of KBKB with like Bishops */
7749 /* always flag draws, for judging claims */
7750 boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
7752 if(canAdjudicate && appData.materialDraws) {
7753 /* but only adjudicate them if adjudication enabled */
7754 if(engineOpponent) {
7755 SendToProgram("force\n", engineOpponent); // suppress reply
7756 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
7758 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
7763 /* Then some trivial draws (only adjudicate, cannot be claimed) */
7764 if(gameInfo.variant == VariantXiangqi ?
7765 SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
7767 ( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
7768 || nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
7769 || nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
7770 || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
7772 if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
7773 { /* if the first 3 moves do not show a tactical win, declare draw */
7774 if(engineOpponent) {
7775 SendToProgram("force\n", engineOpponent); // suppress reply
7776 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7778 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
7781 } else moveCount = 6;
7784 // Repetition draws and 50-move rule can be applied independently of legality testing
7786 /* Check for rep-draws */
7788 for(k = forwardMostMove-2;
7789 k>=backwardMostMove && k>=forwardMostMove-100 &&
7790 (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
7791 (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE;
7794 if(CompareBoards(boards[k], boards[forwardMostMove])) {
7795 /* compare castling rights */
7796 if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
7797 (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
7798 rights++; /* King lost rights, while rook still had them */
7799 if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
7800 if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
7801 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
7802 rights++; /* but at least one rook lost them */
7804 if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
7805 (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
7807 if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
7808 if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
7809 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
7812 if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
7813 && appData.drawRepeats > 1) {
7814 /* adjudicate after user-specified nr of repeats */
7815 int result = GameIsDrawn;
7816 char *details = "XBoard adjudication: repetition draw";
7817 if(gameInfo.variant == VariantXiangqi && appData.testLegality) {
7818 // [HGM] xiangqi: check for forbidden perpetuals
7819 int m, ourPerpetual = 1, hisPerpetual = 1;
7820 for(m=forwardMostMove; m>k; m-=2) {
7821 if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
7822 ourPerpetual = 0; // the current mover did not always check
7823 if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
7824 hisPerpetual = 0; // the opponent did not always check
7826 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
7827 ourPerpetual, hisPerpetual);
7828 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
7829 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7830 details = "Xboard adjudication: perpetual checking";
7832 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
7833 break; // (or we would have caught him before). Abort repetition-checking loop.
7835 // Now check for perpetual chases
7836 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
7837 hisPerpetual = PerpetualChase(k, forwardMostMove);
7838 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
7839 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
7840 static char resdet[MSG_SIZ];
7841 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
7843 snprintf(resdet, MSG_SIZ, "Xboard adjudication: perpetual chasing of %c%c", ourPerpetual>>8, ourPerpetual&255);
7845 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
7846 break; // Abort repetition-checking loop.
7848 // if neither of us is checking or chasing all the time, or both are, it is draw
7850 if(engineOpponent) {
7851 SendToProgram("force\n", engineOpponent); // suppress reply
7852 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7854 GameEnds( result, details, GE_XBOARD );
7857 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
7858 boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
7862 /* Now we test for 50-move draws. Determine ply count */
7863 count = forwardMostMove;
7864 /* look for last irreversble move */
7865 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
7867 /* if we hit starting position, add initial plies */
7868 if( count == backwardMostMove )
7869 count -= initialRulePlies;
7870 count = forwardMostMove - count;
7871 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
7872 // adjust reversible move counter for checks in Xiangqi
7873 int i = forwardMostMove - count, inCheck = 0, lastCheck;
7874 if(i < backwardMostMove) i = backwardMostMove;
7875 while(i <= forwardMostMove) {
7876 lastCheck = inCheck; // check evasion does not count
7877 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
7878 if(inCheck || lastCheck) count--; // check does not count
7883 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
7884 /* this is used to judge if draw claims are legal */
7885 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
7886 if(engineOpponent) {
7887 SendToProgram("force\n", engineOpponent); // suppress reply
7888 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7890 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
7894 /* if draw offer is pending, treat it as a draw claim
7895 * when draw condition present, to allow engines a way to
7896 * claim draws before making their move to avoid a race
7897 * condition occurring after their move
7899 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
7901 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
7902 p = "Draw claim: 50-move rule";
7903 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
7904 p = "Draw claim: 3-fold repetition";
7905 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
7906 p = "Draw claim: insufficient mating material";
7907 if( p != NULL && canAdjudicate) {
7908 if(engineOpponent) {
7909 SendToProgram("force\n", engineOpponent); // suppress reply
7910 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7912 GameEnds( GameIsDrawn, p, GE_XBOARD );
7917 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
7918 if(engineOpponent) {
7919 SendToProgram("force\n", engineOpponent); // suppress reply
7920 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
7922 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
7929 SendMoveToBookUser (int moveNr, ChessProgramState *cps, int initial)
7930 { // [HGM] book: this routine intercepts moves to simulate book replies
7931 char *bookHit = NULL;
7933 //first determine if the incoming move brings opponent into his book
7934 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
7935 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
7936 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
7937 if(bookHit != NULL && !cps->bookSuspend) {
7938 // make sure opponent is not going to reply after receiving move to book position
7939 SendToProgram("force\n", cps);
7940 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
7942 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
7943 // now arrange restart after book miss
7945 // after a book hit we never send 'go', and the code after the call to this routine
7946 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
7947 char buf[MSG_SIZ], *move = bookHit;
7949 int fromX, fromY, toX, toY;
7953 if (ParseOneMove(bookHit, forwardMostMove, &moveType,
7954 &fromX, &fromY, &toX, &toY, &promoChar)) {
7955 (void) CoordsToAlgebraic(boards[forwardMostMove],
7956 PosFlags(forwardMostMove),
7957 fromY, fromX, toY, toX, promoChar, move);
7959 if(appData.debugMode) fprintf(debugFP, "Book move could not be parsed\n");
7963 snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), move); // force book move into program supposed to play it
7964 SendToProgram(buf, cps);
7965 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
7966 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
7967 SendToProgram("go\n", cps);
7968 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
7969 } else { // 'go' might be sent based on 'firstMove' after this routine returns
7970 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
7971 SendToProgram("go\n", cps);
7972 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
7974 return bookHit; // notify caller of hit, so it can take action to send move to opponent
7978 LoadError (char *errmess, ChessProgramState *cps)
7979 { // unloads engine and switches back to -ncp mode if it was first
7980 if(cps->initDone) return FALSE;
7981 cps->isr = NULL; // this should suppress further error popups from breaking pipes
7982 DestroyChildProcess(cps->pr, 9 ); // just to be sure
7985 appData.noChessProgram = TRUE;
7986 gameMode = MachinePlaysBlack; ModeHighlight(); // kludge to unmark Machine Black menu
7987 gameMode = BeginningOfGame; ModeHighlight();
7990 if(GetDelayedEvent()) CancelDelayedEvent(), ThawUI(); // [HGM] cancel remaining loading effort scheduled after feature timeout
7991 DisplayMessage("", ""); // erase waiting message
7992 if(errmess) DisplayError(errmess, 0); // announce reason, if given
7997 ChessProgramState *savedState;
7999 DeferredBookMove (void)
8001 if(savedState->lastPing != savedState->lastPong)
8002 ScheduleDelayedEvent(DeferredBookMove, 10);
8004 HandleMachineMove(savedMessage, savedState);
8007 static int savedWhitePlayer, savedBlackPlayer, pairingReceived;
8010 HandleMachineMove (char *message, ChessProgramState *cps)
8012 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
8013 char realname[MSG_SIZ];
8014 int fromX, fromY, toX, toY;
8018 int machineWhite, oldError;
8021 if(cps == &pairing && sscanf(message, "%d-%d", &savedWhitePlayer, &savedBlackPlayer) == 2) {
8022 // [HGM] pairing: Mega-hack! Pairing engine also uses this routine (so it could give other WB commands).
8023 if(savedWhitePlayer == 0 || savedBlackPlayer == 0) {
8024 DisplayError(_("Invalid pairing from pairing engine"), 0);
8027 pairingReceived = 1;
8029 return; // Skim the pairing messages here.
8032 oldError = cps->userError; cps->userError = 0;
8034 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
8036 * Kludge to ignore BEL characters
8038 while (*message == '\007') message++;
8041 * [HGM] engine debug message: ignore lines starting with '#' character
8043 if(cps->debug && *message == '#') return;
8046 * Look for book output
8048 if (cps == &first && bookRequested) {
8049 if (message[0] == '\t' || message[0] == ' ') {
8050 /* Part of the book output is here; append it */
8051 strcat(bookOutput, message);
8052 strcat(bookOutput, " \n");
8054 } else if (bookOutput[0] != NULLCHAR) {
8055 /* All of book output has arrived; display it */
8056 char *p = bookOutput;
8057 while (*p != NULLCHAR) {
8058 if (*p == '\t') *p = ' ';
8061 DisplayInformation(bookOutput);
8062 bookRequested = FALSE;
8063 /* Fall through to parse the current output */
8068 * Look for machine move.
8070 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
8071 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
8073 /* This method is only useful on engines that support ping */
8074 if (cps->lastPing != cps->lastPong) {
8075 if (gameMode == BeginningOfGame) {
8076 /* Extra move from before last new; ignore */
8077 if (appData.debugMode) {
8078 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8081 if (appData.debugMode) {
8082 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
8083 cps->which, gameMode);
8086 SendToProgram("undo\n", cps);
8092 case BeginningOfGame:
8093 /* Extra move from before last reset; ignore */
8094 if (appData.debugMode) {
8095 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8102 /* Extra move after we tried to stop. The mode test is
8103 not a reliable way of detecting this problem, but it's
8104 the best we can do on engines that don't support ping.
8106 if (appData.debugMode) {
8107 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
8108 cps->which, gameMode);
8110 SendToProgram("undo\n", cps);
8113 case MachinePlaysWhite:
8114 case IcsPlayingWhite:
8115 machineWhite = TRUE;
8118 case MachinePlaysBlack:
8119 case IcsPlayingBlack:
8120 machineWhite = FALSE;
8123 case TwoMachinesPlay:
8124 machineWhite = (cps->twoMachinesColor[0] == 'w');
8127 if (WhiteOnMove(forwardMostMove) != machineWhite) {
8128 if (appData.debugMode) {
8130 "Ignoring move out of turn by %s, gameMode %d"
8131 ", forwardMost %d\n",
8132 cps->which, gameMode, forwardMostMove);
8137 if(cps->alphaRank) AlphaRank(machineMove, 4);
8138 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
8139 &fromX, &fromY, &toX, &toY, &promoChar)) {
8140 /* Machine move could not be parsed; ignore it. */
8141 snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
8142 machineMove, _(cps->which));
8143 DisplayError(buf1, 0);
8144 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d",
8145 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType);
8146 if (gameMode == TwoMachinesPlay) {
8147 GameEnds(machineWhite ? BlackWins : WhiteWins,
8153 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
8154 /* So we have to redo legality test with true e.p. status here, */
8155 /* to make sure an illegal e.p. capture does not slip through, */
8156 /* to cause a forfeit on a justified illegal-move complaint */
8157 /* of the opponent. */
8158 if( gameMode==TwoMachinesPlay && appData.testLegality ) {
8160 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
8161 fromY, fromX, toY, toX, promoChar);
8162 if(moveType == IllegalMove) {
8163 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
8164 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
8165 GameEnds(machineWhite ? BlackWins : WhiteWins,
8168 } else if(gameInfo.variant != VariantFischeRandom && gameInfo.variant != VariantCapaRandom)
8169 /* [HGM] Kludge to handle engines that send FRC-style castling
8170 when they shouldn't (like TSCP-Gothic) */
8172 case WhiteASideCastleFR:
8173 case BlackASideCastleFR:
8175 currentMoveString[2]++;
8177 case WhiteHSideCastleFR:
8178 case BlackHSideCastleFR:
8180 currentMoveString[2]--;
8182 default: ; // nothing to do, but suppresses warning of pedantic compilers
8185 hintRequested = FALSE;
8186 lastHint[0] = NULLCHAR;
8187 bookRequested = FALSE;
8188 /* Program may be pondering now */
8189 cps->maybeThinking = TRUE;
8190 if (cps->sendTime == 2) cps->sendTime = 1;
8191 if (cps->offeredDraw) cps->offeredDraw--;
8193 /* [AS] Save move info*/
8194 pvInfoList[ forwardMostMove ].score = programStats.score;
8195 pvInfoList[ forwardMostMove ].depth = programStats.depth;
8196 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
8198 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
8200 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
8201 if( gameMode == TwoMachinesPlay && adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
8204 while( count < adjudicateLossPlies ) {
8205 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
8208 score = -score; /* Flip score for winning side */
8211 if( score > adjudicateLossThreshold ) {
8218 if( count >= adjudicateLossPlies ) {
8219 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8221 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
8222 "Xboard adjudication",
8229 if(Adjudicate(cps)) {
8230 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8231 return; // [HGM] adjudicate: for all automatic game ends
8235 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
8237 if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
8238 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
8240 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8242 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8244 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
8245 char buf[3*MSG_SIZ];
8247 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
8248 programStats.score / 100.,
8250 programStats.time / 100.,
8251 (unsigned int)programStats.nodes,
8252 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
8253 programStats.movelist);
8255 if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats.nodes, programStats.nodes);
8260 /* [AS] Clear stats for next move */
8261 ClearProgramStats();
8262 thinkOutput[0] = NULLCHAR;
8263 hiddenThinkOutputState = 0;
8266 if (gameMode == TwoMachinesPlay) {
8267 /* [HGM] relaying draw offers moved to after reception of move */
8268 /* and interpreting offer as claim if it brings draw condition */
8269 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
8270 SendToProgram("draw\n", cps->other);
8272 if (cps->other->sendTime) {
8273 SendTimeRemaining(cps->other,
8274 cps->other->twoMachinesColor[0] == 'w');
8276 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
8277 if (firstMove && !bookHit) {
8279 if (cps->other->useColors) {
8280 SendToProgram(cps->other->twoMachinesColor, cps->other);
8282 SendToProgram("go\n", cps->other);
8284 cps->other->maybeThinking = TRUE;
8287 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8289 if (!pausing && appData.ringBellAfterMoves) {
8294 * Reenable menu items that were disabled while
8295 * machine was thinking
8297 if (gameMode != TwoMachinesPlay)
8298 SetUserThinkingEnables();
8300 // [HGM] book: after book hit opponent has received move and is now in force mode
8301 // force the book reply into it, and then fake that it outputted this move by jumping
8302 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
8304 static char bookMove[MSG_SIZ]; // a bit generous?
8306 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
8307 strcat(bookMove, bookHit);
8310 programStats.nodes = programStats.depth = programStats.time =
8311 programStats.score = programStats.got_only_move = 0;
8312 sprintf(programStats.movelist, "%s (xbook)", bookHit);
8314 if(cps->lastPing != cps->lastPong) {
8315 savedMessage = message; // args for deferred call
8317 ScheduleDelayedEvent(DeferredBookMove, 10);
8326 /* Set special modes for chess engines. Later something general
8327 * could be added here; for now there is just one kludge feature,
8328 * needed because Crafty 15.10 and earlier don't ignore SIGINT
8329 * when "xboard" is given as an interactive command.
8331 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
8332 cps->useSigint = FALSE;
8333 cps->useSigterm = FALSE;
8335 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
8336 ParseFeatures(message+8, cps);
8337 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
8340 if ((!appData.testLegality || gameInfo.variant == VariantFairy) &&
8341 !strncmp(message, "setup ", 6)) { // [HGM] allow first engine to define opening position
8342 int dummy, s=6; char buf[MSG_SIZ];
8343 if(appData.icsActive || forwardMostMove != 0 || cps != &first) return;
8344 if(sscanf(message, "setup (%s", buf) == 1) s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTable(pieceToChar, buf);
8345 if(startedFromSetupPosition) return;
8346 ParseFEN(boards[0], &dummy, message+s);
8347 DrawPosition(TRUE, boards[0]);
8348 startedFromSetupPosition = TRUE;
8351 /* [HGM] Allow engine to set up a position. Don't ask me why one would
8352 * want this, I was asked to put it in, and obliged.
8354 if (!strncmp(message, "setboard ", 9)) {
8355 Board initial_position;
8357 GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
8359 if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9)) {
8360 DisplayError(_("Bad FEN received from engine"), 0);
8364 CopyBoard(boards[0], initial_position);
8365 initialRulePlies = FENrulePlies;
8366 if(blackPlaysFirst) gameMode = MachinePlaysWhite;
8367 else gameMode = MachinePlaysBlack;
8368 DrawPosition(FALSE, boards[currentMove]);
8374 * Look for communication commands
8376 if (!strncmp(message, "telluser ", 9)) {
8377 if(message[9] == '\\' && message[10] == '\\')
8378 EscapeExpand(message+9, message+11); // [HGM] esc: allow escape sequences in popup box
8380 DisplayNote(message + 9);
8383 if (!strncmp(message, "tellusererror ", 14)) {
8385 if(message[14] == '\\' && message[15] == '\\')
8386 EscapeExpand(message+14, message+16); // [HGM] esc: allow escape sequences in popup box
8388 DisplayError(message + 14, 0);
8391 if (!strncmp(message, "tellopponent ", 13)) {
8392 if (appData.icsActive) {
8394 snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
8398 DisplayNote(message + 13);
8402 if (!strncmp(message, "tellothers ", 11)) {
8403 if (appData.icsActive) {
8405 snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
8411 if (!strncmp(message, "tellall ", 8)) {
8412 if (appData.icsActive) {
8414 snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
8418 DisplayNote(message + 8);
8422 if (strncmp(message, "warning", 7) == 0) {
8423 /* Undocumented feature, use tellusererror in new code */
8424 DisplayError(message, 0);
8427 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
8428 safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
8429 strcat(realname, " query");
8430 AskQuestion(realname, buf2, buf1, cps->pr);
8433 /* Commands from the engine directly to ICS. We don't allow these to be
8434 * sent until we are logged on. Crafty kibitzes have been known to
8435 * interfere with the login process.
8438 if (!strncmp(message, "tellics ", 8)) {
8439 SendToICS(message + 8);
8443 if (!strncmp(message, "tellicsnoalias ", 15)) {
8444 SendToICS(ics_prefix);
8445 SendToICS(message + 15);
8449 /* The following are for backward compatibility only */
8450 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
8451 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
8452 SendToICS(ics_prefix);
8458 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
8462 * If the move is illegal, cancel it and redraw the board.
8463 * Also deal with other error cases. Matching is rather loose
8464 * here to accommodate engines written before the spec.
8466 if (strncmp(message + 1, "llegal move", 11) == 0 ||
8467 strncmp(message, "Error", 5) == 0) {
8468 if (StrStr(message, "name") ||
8469 StrStr(message, "rating") || StrStr(message, "?") ||
8470 StrStr(message, "result") || StrStr(message, "board") ||
8471 StrStr(message, "bk") || StrStr(message, "computer") ||
8472 StrStr(message, "variant") || StrStr(message, "hint") ||
8473 StrStr(message, "random") || StrStr(message, "depth") ||
8474 StrStr(message, "accepted")) {
8477 if (StrStr(message, "protover")) {
8478 /* Program is responding to input, so it's apparently done
8479 initializing, and this error message indicates it is
8480 protocol version 1. So we don't need to wait any longer
8481 for it to initialize and send feature commands. */
8482 FeatureDone(cps, 1);
8483 cps->protocolVersion = 1;
8486 cps->maybeThinking = FALSE;
8488 if (StrStr(message, "draw")) {
8489 /* Program doesn't have "draw" command */
8490 cps->sendDrawOffers = 0;
8493 if (cps->sendTime != 1 &&
8494 (StrStr(message, "time") || StrStr(message, "otim"))) {
8495 /* Program apparently doesn't have "time" or "otim" command */
8499 if (StrStr(message, "analyze")) {
8500 cps->analysisSupport = FALSE;
8501 cps->analyzing = FALSE;
8502 // Reset(FALSE, TRUE); // [HGM] this caused discrepancy between display and internal state!
8503 EditGameEvent(); // [HGM] try to preserve loaded game
8504 snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
8505 DisplayError(buf2, 0);
8508 if (StrStr(message, "(no matching move)st")) {
8509 /* Special kludge for GNU Chess 4 only */
8510 cps->stKludge = TRUE;
8511 SendTimeControl(cps, movesPerSession, timeControl,
8512 timeIncrement, appData.searchDepth,
8516 if (StrStr(message, "(no matching move)sd")) {
8517 /* Special kludge for GNU Chess 4 only */
8518 cps->sdKludge = TRUE;
8519 SendTimeControl(cps, movesPerSession, timeControl,
8520 timeIncrement, appData.searchDepth,
8524 if (!StrStr(message, "llegal")) {
8527 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
8528 gameMode == IcsIdle) return;
8529 if (forwardMostMove <= backwardMostMove) return;
8530 if (pausing) PauseEvent();
8531 if(appData.forceIllegal) {
8532 // [HGM] illegal: machine refused move; force position after move into it
8533 SendToProgram("force\n", cps);
8534 if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
8535 // we have a real problem now, as SendBoard will use the a2a3 kludge
8536 // when black is to move, while there might be nothing on a2 or black
8537 // might already have the move. So send the board as if white has the move.
8538 // But first we must change the stm of the engine, as it refused the last move
8539 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
8540 if(WhiteOnMove(forwardMostMove)) {
8541 SendToProgram("a7a6\n", cps); // for the engine black still had the move
8542 SendBoard(cps, forwardMostMove); // kludgeless board
8544 SendToProgram("a2a3\n", cps); // for the engine white still had the move
8545 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
8546 SendBoard(cps, forwardMostMove+1); // kludgeless board
8548 } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
8549 if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
8550 gameMode == TwoMachinesPlay)
8551 SendToProgram("go\n", cps);
8554 if (gameMode == PlayFromGameFile) {
8555 /* Stop reading this game file */
8556 gameMode = EditGame;
8559 /* [HGM] illegal-move claim should forfeit game when Xboard */
8560 /* only passes fully legal moves */
8561 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
8562 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
8563 "False illegal-move claim", GE_XBOARD );
8564 return; // do not take back move we tested as valid
8566 currentMove = forwardMostMove-1;
8567 DisplayMove(currentMove-1); /* before DisplayMoveError */
8568 SwitchClocks(forwardMostMove-1); // [HGM] race
8569 DisplayBothClocks();
8570 snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
8571 parseList[currentMove], _(cps->which));
8572 DisplayMoveError(buf1);
8573 DrawPosition(FALSE, boards[currentMove]);
8575 SetUserThinkingEnables();
8578 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
8579 /* Program has a broken "time" command that
8580 outputs a string not ending in newline.
8586 * If chess program startup fails, exit with an error message.
8587 * Attempts to recover here are futile. [HGM] Well, we try anyway
8589 if ((StrStr(message, "unknown host") != NULL)
8590 || (StrStr(message, "No remote directory") != NULL)
8591 || (StrStr(message, "not found") != NULL)
8592 || (StrStr(message, "No such file") != NULL)
8593 || (StrStr(message, "can't alloc") != NULL)
8594 || (StrStr(message, "Permission denied") != NULL)) {
8596 cps->maybeThinking = FALSE;
8597 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
8598 _(cps->which), cps->program, cps->host, message);
8599 RemoveInputSource(cps->isr);
8600 if(appData.icsActive) DisplayFatalError(buf1, 0, 1); else {
8601 if(LoadError(oldError ? NULL : buf1, cps)) return; // error has then been handled by LoadError
8602 if(!oldError) DisplayError(buf1, 0); // if reason neatly announced, suppress general error popup
8608 * Look for hint output
8610 if (sscanf(message, "Hint: %s", buf1) == 1) {
8611 if (cps == &first && hintRequested) {
8612 hintRequested = FALSE;
8613 if (ParseOneMove(buf1, forwardMostMove, &moveType,
8614 &fromX, &fromY, &toX, &toY, &promoChar)) {
8615 (void) CoordsToAlgebraic(boards[forwardMostMove],
8616 PosFlags(forwardMostMove),
8617 fromY, fromX, toY, toX, promoChar, buf1);
8618 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
8619 DisplayInformation(buf2);
8621 /* Hint move could not be parsed!? */
8622 snprintf(buf2, sizeof(buf2),
8623 _("Illegal hint move \"%s\"\nfrom %s chess program"),
8624 buf1, _(cps->which));
8625 DisplayError(buf2, 0);
8628 safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
8634 * Ignore other messages if game is not in progress
8636 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
8637 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
8640 * look for win, lose, draw, or draw offer
8642 if (strncmp(message, "1-0", 3) == 0) {
8643 char *p, *q, *r = "";
8644 p = strchr(message, '{');
8652 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
8654 } else if (strncmp(message, "0-1", 3) == 0) {
8655 char *p, *q, *r = "";
8656 p = strchr(message, '{');
8664 /* Kludge for Arasan 4.1 bug */
8665 if (strcmp(r, "Black resigns") == 0) {
8666 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
8669 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
8671 } else if (strncmp(message, "1/2", 3) == 0) {
8672 char *p, *q, *r = "";
8673 p = strchr(message, '{');
8682 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
8685 } else if (strncmp(message, "White resign", 12) == 0) {
8686 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8688 } else if (strncmp(message, "Black resign", 12) == 0) {
8689 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8691 } else if (strncmp(message, "White matches", 13) == 0 ||
8692 strncmp(message, "Black matches", 13) == 0 ) {
8693 /* [HGM] ignore GNUShogi noises */
8695 } else if (strncmp(message, "White", 5) == 0 &&
8696 message[5] != '(' &&
8697 StrStr(message, "Black") == NULL) {
8698 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8700 } else if (strncmp(message, "Black", 5) == 0 &&
8701 message[5] != '(') {
8702 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8704 } else if (strcmp(message, "resign") == 0 ||
8705 strcmp(message, "computer resigns") == 0) {
8707 case MachinePlaysBlack:
8708 case IcsPlayingBlack:
8709 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
8711 case MachinePlaysWhite:
8712 case IcsPlayingWhite:
8713 GameEnds(BlackWins, "White resigns", GE_ENGINE);
8715 case TwoMachinesPlay:
8716 if (cps->twoMachinesColor[0] == 'w')
8717 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
8719 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
8726 } else if (strncmp(message, "opponent mates", 14) == 0) {
8728 case MachinePlaysBlack:
8729 case IcsPlayingBlack:
8730 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8732 case MachinePlaysWhite:
8733 case IcsPlayingWhite:
8734 GameEnds(BlackWins, "Black mates", GE_ENGINE);
8736 case TwoMachinesPlay:
8737 if (cps->twoMachinesColor[0] == 'w')
8738 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8740 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8747 } else if (strncmp(message, "computer mates", 14) == 0) {
8749 case MachinePlaysBlack:
8750 case IcsPlayingBlack:
8751 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
8753 case MachinePlaysWhite:
8754 case IcsPlayingWhite:
8755 GameEnds(WhiteWins, "White mates", GE_ENGINE);
8757 case TwoMachinesPlay:
8758 if (cps->twoMachinesColor[0] == 'w')
8759 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8761 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8768 } else if (strncmp(message, "checkmate", 9) == 0) {
8769 if (WhiteOnMove(forwardMostMove)) {
8770 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
8772 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
8775 } else if (strstr(message, "Draw") != NULL ||
8776 strstr(message, "game is a draw") != NULL) {
8777 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
8779 } else if (strstr(message, "offer") != NULL &&
8780 strstr(message, "draw") != NULL) {
8782 if (appData.zippyPlay && first.initDone) {
8783 /* Relay offer to ICS */
8784 SendToICS(ics_prefix);
8785 SendToICS("draw\n");
8788 cps->offeredDraw = 2; /* valid until this engine moves twice */
8789 if (gameMode == TwoMachinesPlay) {
8790 if (cps->other->offeredDraw) {
8791 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8792 /* [HGM] in two-machine mode we delay relaying draw offer */
8793 /* until after we also have move, to see if it is really claim */
8795 } else if (gameMode == MachinePlaysWhite ||
8796 gameMode == MachinePlaysBlack) {
8797 if (userOfferedDraw) {
8798 DisplayInformation(_("Machine accepts your draw offer"));
8799 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
8801 DisplayInformation(_("Machine offers a draw\nSelect Action / Draw to agree"));
8808 * Look for thinking output
8810 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
8811 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
8813 int plylev, mvleft, mvtot, curscore, time;
8814 char mvname[MOVE_LEN];
8818 int prefixHint = FALSE;
8819 mvname[0] = NULLCHAR;
8822 case MachinePlaysBlack:
8823 case IcsPlayingBlack:
8824 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8826 case MachinePlaysWhite:
8827 case IcsPlayingWhite:
8828 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
8833 case IcsObserving: /* [DM] icsEngineAnalyze */
8834 if (!appData.icsEngineAnalyze) ignore = TRUE;
8836 case TwoMachinesPlay:
8837 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
8847 ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
8849 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
8850 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
8852 if (plyext != ' ' && plyext != '\t') {
8856 /* [AS] Negate score if machine is playing black and reporting absolute scores */
8857 if( cps->scoreIsAbsolute &&
8858 ( gameMode == MachinePlaysBlack ||
8859 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
8860 gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
8861 (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
8862 !WhiteOnMove(currentMove)
8865 curscore = -curscore;
8868 if(appData.pvSAN[cps==&second]) pv = PvToSAN(buf1);
8870 if(serverMoves && (time > 100 || time == 0 && plylev > 7)) {
8873 snprintf(buf, MSG_SIZ, "%s", appData.serverMovesName);
8874 buf[strlen(buf)-1] = gameMode == MachinePlaysWhite ? 'w' :
8875 gameMode == MachinePlaysBlack ? 'b' : cps->twoMachinesColor[0];
8876 if(appData.debugMode) fprintf(debugFP, "write PV on file '%s'\n", buf);
8877 if(f = fopen(buf, "w")) { // export PV to applicable PV file
8878 fprintf(f, "%5.2f/%-2d %s", curscore/100., plylev, pv);
8880 } else DisplayError(_("failed writing PV"), 0);
8883 tempStats.depth = plylev;
8884 tempStats.nodes = nodes;
8885 tempStats.time = time;
8886 tempStats.score = curscore;
8887 tempStats.got_only_move = 0;
8889 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
8892 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
8893 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
8894 if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
8895 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
8896 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
8897 if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
8898 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
8899 blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
8902 /* Buffer overflow protection */
8903 if (pv[0] != NULLCHAR) {
8904 if (strlen(pv) >= sizeof(tempStats.movelist)
8905 && appData.debugMode) {
8907 "PV is too long; using the first %u bytes.\n",
8908 (unsigned) sizeof(tempStats.movelist) - 1);
8911 safeStrCpy( tempStats.movelist, pv, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
8913 sprintf(tempStats.movelist, " no PV\n");
8916 if (tempStats.seen_stat) {
8917 tempStats.ok_to_send = 1;
8920 if (strchr(tempStats.movelist, '(') != NULL) {
8921 tempStats.line_is_book = 1;
8922 tempStats.nr_moves = 0;
8923 tempStats.moves_left = 0;
8925 tempStats.line_is_book = 0;
8928 if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
8929 programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
8931 SendProgramStatsToFrontend( cps, &tempStats );
8934 [AS] Protect the thinkOutput buffer from overflow... this
8935 is only useful if buf1 hasn't overflowed first!
8937 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s",
8939 (gameMode == TwoMachinesPlay ?
8940 ToUpper(cps->twoMachinesColor[0]) : ' '),
8941 ((double) curscore) / 100.0,
8942 prefixHint ? lastHint : "",
8943 prefixHint ? " " : "" );
8945 if( buf1[0] != NULLCHAR ) {
8946 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
8948 if( strlen(pv) > max_len ) {
8949 if( appData.debugMode) {
8950 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
8952 pv[max_len+1] = '\0';
8955 strcat( thinkOutput, pv);
8958 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
8959 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8960 DisplayMove(currentMove - 1);
8964 } else if ((p=StrStr(message, "(only move)")) != NULL) {
8965 /* crafty (9.25+) says "(only move) <move>"
8966 * if there is only 1 legal move
8968 sscanf(p, "(only move) %s", buf1);
8969 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
8970 sprintf(programStats.movelist, "%s (only move)", buf1);
8971 programStats.depth = 1;
8972 programStats.nr_moves = 1;
8973 programStats.moves_left = 1;
8974 programStats.nodes = 1;
8975 programStats.time = 1;
8976 programStats.got_only_move = 1;
8978 /* Not really, but we also use this member to
8979 mean "line isn't going to change" (Crafty
8980 isn't searching, so stats won't change) */
8981 programStats.line_is_book = 1;
8983 SendProgramStatsToFrontend( cps, &programStats );
8985 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
8986 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
8987 DisplayMove(currentMove - 1);
8990 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
8991 &time, &nodes, &plylev, &mvleft,
8992 &mvtot, mvname) >= 5) {
8993 /* The stat01: line is from Crafty (9.29+) in response
8994 to the "." command */
8995 programStats.seen_stat = 1;
8996 cps->maybeThinking = TRUE;
8998 if (programStats.got_only_move || !appData.periodicUpdates)
9001 programStats.depth = plylev;
9002 programStats.time = time;
9003 programStats.nodes = nodes;
9004 programStats.moves_left = mvleft;
9005 programStats.nr_moves = mvtot;
9006 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
9007 programStats.ok_to_send = 1;
9008 programStats.movelist[0] = '\0';
9010 SendProgramStatsToFrontend( cps, &programStats );
9014 } else if (strncmp(message,"++",2) == 0) {
9015 /* Crafty 9.29+ outputs this */
9016 programStats.got_fail = 2;
9019 } else if (strncmp(message,"--",2) == 0) {
9020 /* Crafty 9.29+ outputs this */
9021 programStats.got_fail = 1;
9024 } else if (thinkOutput[0] != NULLCHAR &&
9025 strncmp(message, " ", 4) == 0) {
9026 unsigned message_len;
9029 while (*p && *p == ' ') p++;
9031 message_len = strlen( p );
9033 /* [AS] Avoid buffer overflow */
9034 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
9035 strcat(thinkOutput, " ");
9036 strcat(thinkOutput, p);
9039 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
9040 strcat(programStats.movelist, " ");
9041 strcat(programStats.movelist, p);
9044 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
9045 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
9046 DisplayMove(currentMove - 1);
9054 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
9055 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
9057 ChessProgramStats cpstats;
9059 if (plyext != ' ' && plyext != '\t') {
9063 /* [AS] Negate score if machine is playing black and reporting absolute scores */
9064 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
9065 curscore = -curscore;
9068 cpstats.depth = plylev;
9069 cpstats.nodes = nodes;
9070 cpstats.time = time;
9071 cpstats.score = curscore;
9072 cpstats.got_only_move = 0;
9073 cpstats.movelist[0] = '\0';
9075 if (buf1[0] != NULLCHAR) {
9076 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
9079 cpstats.ok_to_send = 0;
9080 cpstats.line_is_book = 0;
9081 cpstats.nr_moves = 0;
9082 cpstats.moves_left = 0;
9084 SendProgramStatsToFrontend( cps, &cpstats );
9091 /* Parse a game score from the character string "game", and
9092 record it as the history of the current game. The game
9093 score is NOT assumed to start from the standard position.
9094 The display is not updated in any way.
9097 ParseGameHistory (char *game)
9100 int fromX, fromY, toX, toY, boardIndex;
9105 if (appData.debugMode)
9106 fprintf(debugFP, "Parsing game history: %s\n", game);
9108 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
9109 gameInfo.site = StrSave(appData.icsHost);
9110 gameInfo.date = PGNDate();
9111 gameInfo.round = StrSave("-");
9113 /* Parse out names of players */
9114 while (*game == ' ') game++;
9116 while (*game != ' ') *p++ = *game++;
9118 gameInfo.white = StrSave(buf);
9119 while (*game == ' ') game++;
9121 while (*game != ' ' && *game != '\n') *p++ = *game++;
9123 gameInfo.black = StrSave(buf);
9126 boardIndex = blackPlaysFirst ? 1 : 0;
9129 yyboardindex = boardIndex;
9130 moveType = (ChessMove) Myylex();
9132 case IllegalMove: /* maybe suicide chess, etc. */
9133 if (appData.debugMode) {
9134 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
9135 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9136 setbuf(debugFP, NULL);
9138 case WhitePromotion:
9139 case BlackPromotion:
9140 case WhiteNonPromotion:
9141 case BlackNonPromotion:
9143 case WhiteCapturesEnPassant:
9144 case BlackCapturesEnPassant:
9145 case WhiteKingSideCastle:
9146 case WhiteQueenSideCastle:
9147 case BlackKingSideCastle:
9148 case BlackQueenSideCastle:
9149 case WhiteKingSideCastleWild:
9150 case WhiteQueenSideCastleWild:
9151 case BlackKingSideCastleWild:
9152 case BlackQueenSideCastleWild:
9154 case WhiteHSideCastleFR:
9155 case WhiteASideCastleFR:
9156 case BlackHSideCastleFR:
9157 case BlackASideCastleFR:
9159 fromX = currentMoveString[0] - AAA;
9160 fromY = currentMoveString[1] - ONE;
9161 toX = currentMoveString[2] - AAA;
9162 toY = currentMoveString[3] - ONE;
9163 promoChar = currentMoveString[4];
9167 if(currentMoveString[0] == '@') continue; // no null moves in ICS mode!
9168 fromX = moveType == WhiteDrop ?
9169 (int) CharToPiece(ToUpper(currentMoveString[0])) :
9170 (int) CharToPiece(ToLower(currentMoveString[0]));
9172 toX = currentMoveString[2] - AAA;
9173 toY = currentMoveString[3] - ONE;
9174 promoChar = NULLCHAR;
9178 snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
9179 if (appData.debugMode) {
9180 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
9181 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9182 setbuf(debugFP, NULL);
9184 DisplayError(buf, 0);
9186 case ImpossibleMove:
9188 snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
9189 if (appData.debugMode) {
9190 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
9191 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9192 setbuf(debugFP, NULL);
9194 DisplayError(buf, 0);
9197 if (boardIndex < backwardMostMove) {
9198 /* Oops, gap. How did that happen? */
9199 DisplayError(_("Gap in move list"), 0);
9202 backwardMostMove = blackPlaysFirst ? 1 : 0;
9203 if (boardIndex > forwardMostMove) {
9204 forwardMostMove = boardIndex;
9208 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
9209 strcat(parseList[boardIndex-1], " ");
9210 strcat(parseList[boardIndex-1], yy_text);
9222 case GameUnfinished:
9223 if (gameMode == IcsExamining) {
9224 if (boardIndex < backwardMostMove) {
9225 /* Oops, gap. How did that happen? */
9228 backwardMostMove = blackPlaysFirst ? 1 : 0;
9231 gameInfo.result = moveType;
9232 p = strchr(yy_text, '{');
9233 if (p == NULL) p = strchr(yy_text, '(');
9236 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
9238 q = strchr(p, *p == '{' ? '}' : ')');
9239 if (q != NULL) *q = NULLCHAR;
9242 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
9243 gameInfo.resultDetails = StrSave(p);
9246 if (boardIndex >= forwardMostMove &&
9247 !(gameMode == IcsObserving && ics_gamenum == -1)) {
9248 backwardMostMove = blackPlaysFirst ? 1 : 0;
9251 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
9252 fromY, fromX, toY, toX, promoChar,
9253 parseList[boardIndex]);
9254 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
9255 /* currentMoveString is set as a side-effect of yylex */
9256 safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
9257 strcat(moveList[boardIndex], "\n");
9259 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
9260 switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
9266 if(gameInfo.variant != VariantShogi)
9267 strcat(parseList[boardIndex - 1], "+");
9271 strcat(parseList[boardIndex - 1], "#");
9278 /* Apply a move to the given board */
9280 ApplyMove (int fromX, int fromY, int toX, int toY, int promoChar, Board board)
9282 ChessSquare captured = board[toY][toX], piece, king; int p, oldEP = EP_NONE, berolina = 0;
9283 int promoRank = gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand ? 3 : 1;
9285 /* [HGM] compute & store e.p. status and castling rights for new position */
9286 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
9288 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
9289 oldEP = (signed char)board[EP_STATUS];
9290 board[EP_STATUS] = EP_NONE;
9292 if (fromY == DROP_RANK) {
9294 if(fromX == EmptySquare) { // [HGM] pass: empty drop encodes null move; nothing to change.
9295 board[EP_STATUS] = EP_CAPTURE; // null move considered irreversible
9298 piece = board[toY][toX] = (ChessSquare) fromX;
9302 if( board[toY][toX] != EmptySquare )
9303 board[EP_STATUS] = EP_CAPTURE;
9305 if( board[fromY][fromX] == WhiteLance || board[fromY][fromX] == BlackLance ) {
9306 if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi )
9307 board[EP_STATUS] = EP_PAWN_MOVE; // Lance is Pawn-like in most variants
9309 if( board[fromY][fromX] == WhitePawn ) {
9310 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9311 board[EP_STATUS] = EP_PAWN_MOVE;
9313 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
9314 gameInfo.variant != VariantBerolina || toX < fromX)
9315 board[EP_STATUS] = toX | berolina;
9316 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
9317 gameInfo.variant != VariantBerolina || toX > fromX)
9318 board[EP_STATUS] = toX;
9321 if( board[fromY][fromX] == BlackPawn ) {
9322 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9323 board[EP_STATUS] = EP_PAWN_MOVE;
9324 if( toY-fromY== -2) {
9325 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
9326 gameInfo.variant != VariantBerolina || toX < fromX)
9327 board[EP_STATUS] = toX | berolina;
9328 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
9329 gameInfo.variant != VariantBerolina || toX > fromX)
9330 board[EP_STATUS] = toX;
9334 for(i=0; i<nrCastlingRights; i++) {
9335 if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
9336 board[CASTLING][i] == toX && castlingRank[i] == toY
9337 ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
9340 if(gameInfo.variant == VariantSChess) { // update virginity
9341 if(fromY == 0) board[VIRGIN][fromX] &= ~VIRGIN_W; // loss by moving
9342 if(fromY == BOARD_HEIGHT-1) board[VIRGIN][fromX] &= ~VIRGIN_B;
9343 if(toY == 0) board[VIRGIN][toX] &= ~VIRGIN_W; // loss by capture
9344 if(toY == BOARD_HEIGHT-1) board[VIRGIN][toX] &= ~VIRGIN_B;
9347 if (fromX == toX && fromY == toY) return;
9349 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
9350 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
9351 if(gameInfo.variant == VariantKnightmate)
9352 king += (int) WhiteUnicorn - (int) WhiteKing;
9354 /* Code added by Tord: */
9355 /* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
9356 if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
9357 board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
9358 board[fromY][fromX] = EmptySquare;
9359 board[toY][toX] = EmptySquare;
9360 if((toX > fromX) != (piece == WhiteRook)) {
9361 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
9363 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
9365 } else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
9366 board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
9367 board[fromY][fromX] = EmptySquare;
9368 board[toY][toX] = EmptySquare;
9369 if((toX > fromX) != (piece == BlackRook)) {
9370 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
9372 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
9374 /* End of code added by Tord */
9376 } else if (board[fromY][fromX] == king
9377 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9378 && toY == fromY && toX > fromX+1) {
9379 board[fromY][fromX] = EmptySquare;
9380 board[toY][toX] = king;
9381 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
9382 board[fromY][BOARD_RGHT-1] = EmptySquare;
9383 } else if (board[fromY][fromX] == king
9384 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9385 && toY == fromY && toX < fromX-1) {
9386 board[fromY][fromX] = EmptySquare;
9387 board[toY][toX] = king;
9388 board[toY][toX+1] = board[fromY][BOARD_LEFT];
9389 board[fromY][BOARD_LEFT] = EmptySquare;
9390 } else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
9391 board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
9392 && toY >= BOARD_HEIGHT-promoRank && promoChar // defaulting to Q is done elsewhere
9394 /* white pawn promotion */
9395 board[toY][toX] = CharToPiece(ToUpper(promoChar));
9396 if(gameInfo.variant==VariantBughouse ||
9397 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
9398 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
9399 board[fromY][fromX] = EmptySquare;
9400 } else if ((fromY >= BOARD_HEIGHT>>1)
9402 && gameInfo.variant != VariantXiangqi
9403 && gameInfo.variant != VariantBerolina
9404 && (board[fromY][fromX] == WhitePawn)
9405 && (board[toY][toX] == EmptySquare)) {
9406 board[fromY][fromX] = EmptySquare;
9407 board[toY][toX] = WhitePawn;
9408 captured = board[toY - 1][toX];
9409 board[toY - 1][toX] = EmptySquare;
9410 } else if ((fromY == BOARD_HEIGHT-4)
9412 && gameInfo.variant == VariantBerolina
9413 && (board[fromY][fromX] == WhitePawn)
9414 && (board[toY][toX] == EmptySquare)) {
9415 board[fromY][fromX] = EmptySquare;
9416 board[toY][toX] = WhitePawn;
9417 if(oldEP & EP_BEROLIN_A) {
9418 captured = board[fromY][fromX-1];
9419 board[fromY][fromX-1] = EmptySquare;
9420 }else{ captured = board[fromY][fromX+1];
9421 board[fromY][fromX+1] = EmptySquare;
9423 } else if (board[fromY][fromX] == king
9424 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9425 && toY == fromY && toX > fromX+1) {
9426 board[fromY][fromX] = EmptySquare;
9427 board[toY][toX] = king;
9428 board[toY][toX-1] = board[fromY][BOARD_RGHT-1];
9429 board[fromY][BOARD_RGHT-1] = EmptySquare;
9430 } else if (board[fromY][fromX] == king
9431 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
9432 && toY == fromY && toX < fromX-1) {
9433 board[fromY][fromX] = EmptySquare;
9434 board[toY][toX] = king;
9435 board[toY][toX+1] = board[fromY][BOARD_LEFT];
9436 board[fromY][BOARD_LEFT] = EmptySquare;
9437 } else if (fromY == 7 && fromX == 3
9438 && board[fromY][fromX] == BlackKing
9439 && toY == 7 && toX == 5) {
9440 board[fromY][fromX] = EmptySquare;
9441 board[toY][toX] = BlackKing;
9442 board[fromY][7] = EmptySquare;
9443 board[toY][4] = BlackRook;
9444 } else if (fromY == 7 && fromX == 3
9445 && board[fromY][fromX] == BlackKing
9446 && toY == 7 && toX == 1) {
9447 board[fromY][fromX] = EmptySquare;
9448 board[toY][toX] = BlackKing;
9449 board[fromY][0] = EmptySquare;
9450 board[toY][2] = BlackRook;
9451 } else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
9452 board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantShogi)
9453 && toY < promoRank && promoChar
9455 /* black pawn promotion */
9456 board[toY][toX] = CharToPiece(ToLower(promoChar));
9457 if(gameInfo.variant==VariantBughouse ||
9458 gameInfo.variant==VariantCrazyhouse) /* [HGM] use shadow piece */
9459 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
9460 board[fromY][fromX] = EmptySquare;
9461 } else if ((fromY < BOARD_HEIGHT>>1)
9463 && gameInfo.variant != VariantXiangqi
9464 && gameInfo.variant != VariantBerolina
9465 && (board[fromY][fromX] == BlackPawn)
9466 && (board[toY][toX] == EmptySquare)) {
9467 board[fromY][fromX] = EmptySquare;
9468 board[toY][toX] = BlackPawn;
9469 captured = board[toY + 1][toX];
9470 board[toY + 1][toX] = EmptySquare;
9471 } else if ((fromY == 3)
9473 && gameInfo.variant == VariantBerolina
9474 && (board[fromY][fromX] == BlackPawn)
9475 && (board[toY][toX] == EmptySquare)) {
9476 board[fromY][fromX] = EmptySquare;
9477 board[toY][toX] = BlackPawn;
9478 if(oldEP & EP_BEROLIN_A) {
9479 captured = board[fromY][fromX-1];
9480 board[fromY][fromX-1] = EmptySquare;
9481 }else{ captured = board[fromY][fromX+1];
9482 board[fromY][fromX+1] = EmptySquare;
9485 board[toY][toX] = board[fromY][fromX];
9486 board[fromY][fromX] = EmptySquare;
9490 if (gameInfo.holdingsWidth != 0) {
9492 /* !!A lot more code needs to be written to support holdings */
9493 /* [HGM] OK, so I have written it. Holdings are stored in the */
9494 /* penultimate board files, so they are automaticlly stored */
9495 /* in the game history. */
9496 if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
9497 && promoChar && piece != WhitePawn && piece != BlackPawn) {
9498 /* Delete from holdings, by decreasing count */
9499 /* and erasing image if necessary */
9500 p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
9501 if(p < (int) BlackPawn) { /* white drop */
9502 p -= (int)WhitePawn;
9503 p = PieceToNumber((ChessSquare)p);
9504 if(p >= gameInfo.holdingsSize) p = 0;
9505 if(--board[p][BOARD_WIDTH-2] <= 0)
9506 board[p][BOARD_WIDTH-1] = EmptySquare;
9507 if((int)board[p][BOARD_WIDTH-2] < 0)
9508 board[p][BOARD_WIDTH-2] = 0;
9509 } else { /* black drop */
9510 p -= (int)BlackPawn;
9511 p = PieceToNumber((ChessSquare)p);
9512 if(p >= gameInfo.holdingsSize) p = 0;
9513 if(--board[BOARD_HEIGHT-1-p][1] <= 0)
9514 board[BOARD_HEIGHT-1-p][0] = EmptySquare;
9515 if((int)board[BOARD_HEIGHT-1-p][1] < 0)
9516 board[BOARD_HEIGHT-1-p][1] = 0;
9519 if (captured != EmptySquare && gameInfo.holdingsSize > 0
9520 && gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess ) {
9521 /* [HGM] holdings: Add to holdings, if holdings exist */
9522 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
9523 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
9524 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
9527 if (p >= (int) BlackPawn) {
9528 p -= (int)BlackPawn;
9529 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
9530 /* in Shogi restore piece to its original first */
9531 captured = (ChessSquare) (DEMOTED captured);
9534 p = PieceToNumber((ChessSquare)p);
9535 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
9536 board[p][BOARD_WIDTH-2]++;
9537 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
9539 p -= (int)WhitePawn;
9540 if(gameInfo.variant == VariantShogi && DEMOTED p >= 0) {
9541 captured = (ChessSquare) (DEMOTED captured);
9544 p = PieceToNumber((ChessSquare)p);
9545 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
9546 board[BOARD_HEIGHT-1-p][1]++;
9547 board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
9550 } else if (gameInfo.variant == VariantAtomic) {
9551 if (captured != EmptySquare) {
9553 for (y = toY-1; y <= toY+1; y++) {
9554 for (x = toX-1; x <= toX+1; x++) {
9555 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
9556 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
9557 board[y][x] = EmptySquare;
9561 board[toY][toX] = EmptySquare;
9564 if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
9565 board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
9567 if(promoChar == '+') {
9568 /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite ordinary Pawn promotion) */
9569 board[toY][toX] = (ChessSquare) (PROMOTED piece);
9570 } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
9571 ChessSquare newPiece = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
9572 if((newPiece <= WhiteMan || newPiece >= BlackPawn && newPiece <= BlackMan) // unpromoted piece specified
9573 && pieceToChar[PROMOTED newPiece] == '~') newPiece = PROMOTED newPiece; // but promoted version available
9574 board[toY][toX] = newPiece;
9576 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
9577 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
9578 // [HGM] superchess: take promotion piece out of holdings
9579 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
9580 if((int)piece < (int)BlackPawn) { // determine stm from piece color
9581 if(!--board[k][BOARD_WIDTH-2])
9582 board[k][BOARD_WIDTH-1] = EmptySquare;
9584 if(!--board[BOARD_HEIGHT-1-k][1])
9585 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
9591 /* Updates forwardMostMove */
9593 MakeMove (int fromX, int fromY, int toX, int toY, int promoChar)
9595 // forwardMostMove++; // [HGM] bare: moved downstream
9597 (void) CoordsToAlgebraic(boards[forwardMostMove],
9598 PosFlags(forwardMostMove),
9599 fromY, fromX, toY, toX, promoChar,
9600 parseList[forwardMostMove]);
9602 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
9603 int timeLeft; static int lastLoadFlag=0; int king, piece;
9604 piece = boards[forwardMostMove][fromY][fromX];
9605 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
9606 if(gameInfo.variant == VariantKnightmate)
9607 king += (int) WhiteUnicorn - (int) WhiteKing;
9608 if(forwardMostMove == 0) {
9609 if(gameMode == MachinePlaysBlack || gameMode == BeginningOfGame)
9610 fprintf(serverMoves, "%s;", UserName());
9611 else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b')
9612 fprintf(serverMoves, "%s;", second.tidy);
9613 fprintf(serverMoves, "%s;", first.tidy);
9614 if(gameMode == MachinePlaysWhite)
9615 fprintf(serverMoves, "%s;", UserName());
9616 else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
9617 fprintf(serverMoves, "%s;", second.tidy);
9618 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
9619 lastLoadFlag = loadFlag;
9621 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
9622 // print castling suffix
9623 if( toY == fromY && piece == king ) {
9625 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
9627 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
9630 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
9631 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
9632 boards[forwardMostMove][toY][toX] == EmptySquare
9633 && fromX != toX && fromY != toY)
9634 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
9636 if(promoChar != NULLCHAR) {
9637 if(fromY == 0 || fromY == BOARD_HEIGHT-1)
9638 fprintf(serverMoves, ":%c%c:%c%c", WhiteOnMove(forwardMostMove) ? 'w' : 'b',
9639 ToLower(promoChar), AAA+fromX, ONE+fromY); // Seirawan gating
9640 else fprintf(serverMoves, ":%c:%c%c", ToLower(promoChar), AAA+toX, ONE+toY);
9643 char buf[MOVE_LEN*2], *p; int len;
9644 fprintf(serverMoves, "/%d/%d",
9645 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
9646 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
9647 else timeLeft = blackTimeRemaining/1000;
9648 fprintf(serverMoves, "/%d", timeLeft);
9649 strncpy(buf, parseList[forwardMostMove], MOVE_LEN*2);
9650 if(p = strchr(buf, '/')) *p = NULLCHAR; else
9651 if(p = strchr(buf, '=')) *p = NULLCHAR;
9652 len = strlen(buf); if(len > 1 && buf[len-2] != '-') buf[len-2] = NULLCHAR; // strip to-square
9653 fprintf(serverMoves, "/%s", buf);
9655 fflush(serverMoves);
9658 if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations..
9659 GameEnds(GameUnfinished, _("Game too long; increase MAX_MOVES and recompile"), GE_XBOARD);
9662 UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
9663 if (commentList[forwardMostMove+1] != NULL) {
9664 free(commentList[forwardMostMove+1]);
9665 commentList[forwardMostMove+1] = NULL;
9667 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
9668 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
9669 // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
9670 SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
9671 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
9672 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
9673 adjustedClock = FALSE;
9674 gameInfo.result = GameUnfinished;
9675 if (gameInfo.resultDetails != NULL) {
9676 free(gameInfo.resultDetails);
9677 gameInfo.resultDetails = NULL;
9679 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
9680 moveList[forwardMostMove - 1]);
9681 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
9687 if(gameInfo.variant != VariantShogi)
9688 strcat(parseList[forwardMostMove - 1], "+");
9692 strcat(parseList[forwardMostMove - 1], "#");
9698 /* Updates currentMove if not pausing */
9700 ShowMove (int fromX, int fromY, int toX, int toY)
9702 int instant = (gameMode == PlayFromGameFile) ?
9703 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
9704 if(appData.noGUI) return;
9705 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
9707 if (forwardMostMove == currentMove + 1) {
9708 AnimateMove(boards[forwardMostMove - 1],
9709 fromX, fromY, toX, toY);
9711 if (appData.highlightLastMove) {
9712 SetHighlights(fromX, fromY, toX, toY);
9715 currentMove = forwardMostMove;
9718 if (instant) return;
9720 DisplayMove(currentMove - 1);
9721 DrawPosition(FALSE, boards[currentMove]);
9722 DisplayBothClocks();
9723 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
9727 SendEgtPath (ChessProgramState *cps)
9728 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
9729 char buf[MSG_SIZ], name[MSG_SIZ], *p;
9731 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
9734 char c, *q = name+1, *r, *s;
9736 name[0] = ','; // extract next format name from feature and copy with prefixed ','
9737 while(*p && *p != ',') *q++ = *p++;
9739 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
9740 strcmp(name, ",nalimov:") == 0 ) {
9741 // take nalimov path from the menu-changeable option first, if it is defined
9742 snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
9743 SendToProgram(buf,cps); // send egtbpath command for nalimov
9745 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
9746 (s = StrStr(appData.egtFormats, name)) != NULL) {
9747 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
9748 s = r = StrStr(s, ":") + 1; // beginning of path info
9749 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
9750 c = *r; *r = 0; // temporarily null-terminate path info
9751 *--q = 0; // strip of trailig ':' from name
9752 snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
9754 SendToProgram(buf,cps); // send egtbpath command for this format
9756 if(*p == ',') p++; // read away comma to position for next format name
9761 InitChessProgram (ChessProgramState *cps, int setup)
9762 /* setup needed to setup FRC opening position */
9764 char buf[MSG_SIZ], b[MSG_SIZ]; int overruled;
9765 if (appData.noChessProgram) return;
9766 hintRequested = FALSE;
9767 bookRequested = FALSE;
9769 ParseFeatures(appData.features[cps == &second], cps); // [HGM] allow user to overrule features
9770 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
9771 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
9772 if(cps->memSize) { /* [HGM] memory */
9773 snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
9774 SendToProgram(buf, cps);
9776 SendEgtPath(cps); /* [HGM] EGT */
9777 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
9778 snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
9779 SendToProgram(buf, cps);
9782 SendToProgram(cps->initString, cps);
9783 if (gameInfo.variant != VariantNormal &&
9784 gameInfo.variant != VariantLoadable
9785 /* [HGM] also send variant if board size non-standard */
9786 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0
9788 char *v = VariantName(gameInfo.variant);
9789 if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) {
9790 /* [HGM] in protocol 1 we have to assume all variants valid */
9791 snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), v, cps->tidy);
9792 DisplayFatalError(buf, 0, 1);
9796 /* [HGM] make prefix for non-standard board size. Awkward testing... */
9797 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9798 if( gameInfo.variant == VariantXiangqi )
9799 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 0;
9800 if( gameInfo.variant == VariantShogi )
9801 overruled = gameInfo.boardWidth != 9 || gameInfo.boardHeight != 9 || gameInfo.holdingsSize != 7;
9802 if( gameInfo.variant == VariantBughouse || gameInfo.variant == VariantCrazyhouse )
9803 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 5;
9804 if( gameInfo.variant == VariantCapablanca || gameInfo.variant == VariantCapaRandom ||
9805 gameInfo.variant == VariantGothic || gameInfo.variant == VariantFalcon || gameInfo.variant == VariantJanus )
9806 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9807 if( gameInfo.variant == VariantCourier )
9808 overruled = gameInfo.boardWidth != 12 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0;
9809 if( gameInfo.variant == VariantSuper )
9810 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9811 if( gameInfo.variant == VariantGreat )
9812 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8;
9813 if( gameInfo.variant == VariantSChess )
9814 overruled = gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 7;
9815 if( gameInfo.variant == VariantGrand )
9816 overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 10 || gameInfo.holdingsSize != 7;
9819 snprintf(b, MSG_SIZ, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight,
9820 gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name
9821 /* [HGM] varsize: try first if this defiant size variant is specifically known */
9822 if(StrStr(cps->variants, b) == NULL) {
9823 // specific sized variant not known, check if general sizing allowed
9824 if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best
9825 if(StrStr(cps->variants, "boardsize") == NULL) {
9826 snprintf(buf, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
9827 gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy);
9828 DisplayFatalError(buf, 0, 1);
9831 /* [HGM] here we really should compare with the maximum supported board size */
9834 } else snprintf(b, MSG_SIZ,"%s", VariantName(gameInfo.variant));
9835 snprintf(buf, MSG_SIZ, "variant %s\n", b);
9836 SendToProgram(buf, cps);
9838 currentlyInitializedVariant = gameInfo.variant;
9840 /* [HGM] send opening position in FRC to first engine */
9842 SendToProgram("force\n", cps);
9844 /* engine is now in force mode! Set flag to wake it up after first move. */
9845 setboardSpoiledMachineBlack = 1;
9849 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
9850 SendToProgram(buf, cps);
9852 cps->maybeThinking = FALSE;
9853 cps->offeredDraw = 0;
9854 if (!appData.icsActive) {
9855 SendTimeControl(cps, movesPerSession, timeControl,
9856 timeIncrement, appData.searchDepth,
9859 if (appData.showThinking
9860 // [HGM] thinking: four options require thinking output to be sent
9861 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
9863 SendToProgram("post\n", cps);
9865 SendToProgram("hard\n", cps);
9866 if (!appData.ponderNextMove) {
9867 /* Warning: "easy" is a toggle in GNU Chess, so don't send
9868 it without being sure what state we are in first. "hard"
9869 is not a toggle, so that one is OK.
9871 SendToProgram("easy\n", cps);
9874 snprintf(buf, MSG_SIZ, "ping %d\n", ++cps->lastPing);
9875 SendToProgram(buf, cps);
9877 cps->initDone = TRUE;
9878 ClearEngineOutputPane(cps == &second);
9883 StartChessProgram (ChessProgramState *cps)
9888 if (appData.noChessProgram) return;
9889 cps->initDone = FALSE;
9891 if (strcmp(cps->host, "localhost") == 0) {
9892 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
9893 } else if (*appData.remoteShell == NULLCHAR) {
9894 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
9896 if (*appData.remoteUser == NULLCHAR) {
9897 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
9900 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
9901 cps->host, appData.remoteUser, cps->program);
9903 err = StartChildProcess(buf, "", &cps->pr);
9907 snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
9908 DisplayError(buf, err); // [HGM] bit of a rough kludge: ignore failure, (which XBoard would do anyway), and let I/O discover it
9909 if(cps != &first) return;
9910 appData.noChessProgram = TRUE;
9913 // DisplayFatalError(buf, err, 1);
9914 // cps->pr = NoProc;
9919 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
9920 if (cps->protocolVersion > 1) {
9921 snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
9922 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
9923 cps->comboCnt = 0; // and values of combo boxes
9924 SendToProgram(buf, cps);
9926 SendToProgram("xboard\n", cps);
9931 TwoMachinesEventIfReady P((void))
9933 static int curMess = 0;
9934 if (first.lastPing != first.lastPong) {
9935 if(curMess != 1) DisplayMessage("", _("Waiting for first chess program")); curMess = 1;
9936 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9939 if (second.lastPing != second.lastPong) {
9940 if(curMess != 2) DisplayMessage("", _("Waiting for second chess program")); curMess = 2;
9941 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
9944 DisplayMessage("", ""); curMess = 0;
9950 MakeName (char *template)
9954 static char buf[MSG_SIZ];
9958 clock = time((time_t *)NULL);
9959 tm = localtime(&clock);
9961 while(*p++ = *template++) if(p[-1] == '%') {
9962 switch(*template++) {
9963 case 0: *p = 0; return buf;
9964 case 'Y': i = tm->tm_year+1900; break;
9965 case 'y': i = tm->tm_year-100; break;
9966 case 'M': i = tm->tm_mon+1; break;
9967 case 'd': i = tm->tm_mday; break;
9968 case 'h': i = tm->tm_hour; break;
9969 case 'm': i = tm->tm_min; break;
9970 case 's': i = tm->tm_sec; break;
9973 snprintf(p-1, MSG_SIZ-10 - (p - buf), "%02d", i); p += strlen(p);
9979 CountPlayers (char *p)
9982 while(p = strchr(p, '\n')) p++, n++; // count participants
9987 WriteTourneyFile (char *results, FILE *f)
9988 { // write tournament parameters on tourneyFile; on success return the stream pointer for closing
9989 if(f == NULL) f = fopen(appData.tourneyFile, "w");
9990 if(f == NULL) DisplayError(_("Could not write on tourney file"), 0); else {
9991 // create a file with tournament description
9992 fprintf(f, "-participants {%s}\n", appData.participants);
9993 fprintf(f, "-seedBase %d\n", appData.seedBase);
9994 fprintf(f, "-tourneyType %d\n", appData.tourneyType);
9995 fprintf(f, "-tourneyCycles %d\n", appData.tourneyCycles);
9996 fprintf(f, "-defaultMatchGames %d\n", appData.defaultMatchGames);
9997 fprintf(f, "-syncAfterRound %s\n", appData.roundSync ? "true" : "false");
9998 fprintf(f, "-syncAfterCycle %s\n", appData.cycleSync ? "true" : "false");
9999 fprintf(f, "-saveGameFile \"%s\"\n", appData.saveGameFile);
10000 fprintf(f, "-loadGameFile \"%s\"\n", appData.loadGameFile);
10001 fprintf(f, "-loadGameIndex %d\n", appData.loadGameIndex);
10002 fprintf(f, "-loadPositionFile \"%s\"\n", appData.loadPositionFile);
10003 fprintf(f, "-loadPositionIndex %d\n", appData.loadPositionIndex);
10004 fprintf(f, "-rewindIndex %d\n", appData.rewindIndex);
10005 fprintf(f, "-discourageOwnBooks %s\n", appData.defNoBook ? "true" : "false");
10007 fprintf(f, "-searchTime \"%d:%02d\"\n", searchTime/60, searchTime%60);
10009 fprintf(f, "-mps %d\n", appData.movesPerSession);
10010 fprintf(f, "-tc %s\n", appData.timeControl);
10011 fprintf(f, "-inc %.2f\n", appData.timeIncrement);
10013 fprintf(f, "-results \"%s\"\n", results);
10018 char *command[MAXENGINES], *mnemonic[MAXENGINES];
10021 Substitute (char *participants, int expunge)
10023 int i, changed, changes=0, nPlayers=0;
10024 char *p, *q, *r, buf[MSG_SIZ];
10025 if(participants == NULL) return;
10026 if(appData.tourneyFile[0] == NULLCHAR) { free(participants); return; }
10027 r = p = participants; q = appData.participants;
10028 while(*p && *p == *q) {
10029 if(*p == '\n') r = p+1, nPlayers++;
10032 if(*p) { // difference
10033 while(*p && *p++ != '\n');
10034 while(*q && *q++ != '\n');
10035 changed = nPlayers;
10036 changes = 1 + (strcmp(p, q) != 0);
10038 if(changes == 1) { // a single engine mnemonic was changed
10039 q = r; while(*q) nPlayers += (*q++ == '\n');
10040 p = buf; while(*r && (*p = *r++) != '\n') p++;
10042 NamesToList(firstChessProgramNames, command, mnemonic, "all");
10043 for(i=1; mnemonic[i]; i++) if(!strcmp(buf, mnemonic[i])) break;
10044 if(mnemonic[i]) { // The substitute is valid
10046 if(appData.tourneyFile[0] && (f = fopen(appData.tourneyFile, "r+")) ) {
10047 flock(fileno(f), LOCK_EX);
10048 ParseArgsFromFile(f);
10049 fseek(f, 0, SEEK_SET);
10050 FREE(appData.participants); appData.participants = participants;
10051 if(expunge) { // erase results of replaced engine
10052 int len = strlen(appData.results), w, b, dummy;
10053 for(i=0; i<len; i++) {
10054 Pairing(i, nPlayers, &w, &b, &dummy);
10055 if((w == changed || b == changed) && appData.results[i] == '*') {
10056 DisplayError(_("You cannot replace an engine while it is engaged!\nTerminate its game first."), 0);
10061 for(i=0; i<len; i++) {
10062 Pairing(i, nPlayers, &w, &b, &dummy);
10063 if(w == changed || b == changed) appData.results[i] = ' '; // mark as not played
10066 WriteTourneyFile(appData.results, f);
10067 fclose(f); // release lock
10070 } else DisplayError(_("No engine with the name you gave is installed"), 0);
10072 if(changes == 0) DisplayError(_("First change an engine by editing the participants list\nof the Tournament Options dialog"), 0);
10073 if(changes > 1) DisplayError(_("You can only change one engine at the time"), 0);
10074 free(participants);
10079 CheckPlayers (char *participants)
10082 char buf[MSG_SIZ], *p;
10083 NamesToList(firstChessProgramNames, command, mnemonic, "all");
10084 while(p = strchr(participants, '\n')) {
10086 for(i=1; mnemonic[i]; i++) if(!strcmp(participants, mnemonic[i])) break;
10088 snprintf(buf, MSG_SIZ, _("No engine %s is installed"), participants);
10090 DisplayError(buf, 0);
10094 participants = p + 1;
10100 CreateTourney (char *name)
10103 if(matchMode && strcmp(name, appData.tourneyFile)) {
10104 ASSIGN(name, appData.tourneyFile); //do not allow change of tourneyfile while playing
10106 if(name[0] == NULLCHAR) {
10107 if(appData.participants[0])
10108 DisplayError(_("You must supply a tournament file,\nfor storing the tourney progress"), 0);
10111 f = fopen(name, "r");
10112 if(f) { // file exists
10113 ASSIGN(appData.tourneyFile, name);
10114 ParseArgsFromFile(f); // parse it
10116 if(!appData.participants[0]) return 0; // ignore tourney file if non-existing & no participants
10117 if(CountPlayers(appData.participants) < (appData.tourneyType>0 ? appData.tourneyType+1 : 2)) {
10118 DisplayError(_("Not enough participants"), 0);
10121 if(CheckPlayers(appData.participants)) return 0;
10122 ASSIGN(appData.tourneyFile, name);
10123 if(appData.tourneyType < 0) appData.defaultMatchGames = 1; // Swiss forces games/pairing = 1
10124 if((f = WriteTourneyFile("", NULL)) == NULL) return 0;
10127 appData.noChessProgram = FALSE;
10128 appData.clockMode = TRUE;
10134 NamesToList (char *names, char **engineList, char **engineMnemonic, char *group)
10136 char buf[MSG_SIZ], *p, *q;
10137 int i=1, header, skip, all = !strcmp(group, "all"), depth = 0;
10138 insert = names; // afterwards, this global will point just after last retrieved engine line or group end in the 'names'
10139 skip = !all && group[0]; // if group requested, we start in skip mode
10140 for(;*names && depth >= 0 && i < MAXENGINES-1; names = p) {
10141 p = names; q = buf; header = 0;
10142 while(*p && *p != '\n') *q++ = *p++;
10144 if(*p == '\n') p++;
10145 if(buf[0] == '#') {
10146 if(strstr(buf, "# end") == buf) { if(!--depth) insert = p; continue; } // leave group, and suppress printing label
10147 depth++; // we must be entering a new group
10148 if(all) continue; // suppress printing group headers when complete list requested
10150 if(skip && !strcmp(group, buf)) { depth = 0; skip = FALSE; } // start when we reach requested group
10152 if(depth != header && !all || skip) continue; // skip contents of group (but print first-level header)
10153 if(engineList[i]) free(engineList[i]);
10154 engineList[i] = strdup(buf);
10155 if(buf[0] != '#') insert = p, TidyProgramName(engineList[i], "localhost", buf); // group headers not tidied
10156 if(engineMnemonic[i]) free(engineMnemonic[i]);
10157 if((q = strstr(engineList[i]+2, "variant")) && q[-2]== ' ' && (q[-1]=='/' || q[-1]=='-') && (q[7]==' ' || q[7]=='=')) {
10159 sscanf(q + 8, "%s", buf + strlen(buf));
10162 engineMnemonic[i] = strdup(buf);
10165 engineList[i] = engineMnemonic[i] = NULL;
10169 // following implemented as macro to avoid type limitations
10170 #define SWAP(item, temp) temp = appData.item[0]; appData.item[0] = appData.item[n]; appData.item[n] = temp;
10173 SwapEngines (int n)
10174 { // swap settings for first engine and other engine (so far only some selected options)
10179 SWAP(chessProgram, p)
10181 SWAP(hasOwnBookUCI, h)
10182 SWAP(protocolVersion, h)
10184 SWAP(scoreIsAbsolute, h)
10189 SWAP(engOptions, p)
10190 SWAP(engInitString, p)
10191 SWAP(computerString, p)
10193 SWAP(fenOverride, p)
10195 SWAP(accumulateTC, h)
10200 GetEngineLine (char *s, int n)
10204 extern char *icsNames;
10205 if(!s || !*s) return 0;
10206 NamesToList(n == 10 ? icsNames : firstChessProgramNames, command, mnemonic, "all");
10207 for(i=1; mnemonic[i]; i++) if(!strcmp(s, mnemonic[i])) break;
10208 if(!mnemonic[i]) return 0;
10209 snprintf(buf, MSG_SIZ, "-%s %s", n == 10 ? "icshost" : "fcp", command[i]);
10210 if(n == 1) SwapEngines(n);
10211 ParseArgsFromString(buf);
10212 if(n == 1) SwapEngines(n);
10213 if(n == 0 && *appData.secondChessProgram == NULLCHAR) {
10214 SwapEngines(1); // set second same as first if not yet set (to suppress WB startup dialog)
10215 ParseArgsFromString(buf);
10221 SetPlayer (int player, char *p)
10222 { // [HGM] find the engine line of the partcipant given by number, and parse its options.
10224 char buf[MSG_SIZ], *engineName;
10225 for(i=0; i<player; i++) p = strchr(p, '\n') + 1;
10226 engineName = strdup(p); if(p = strchr(engineName, '\n')) *p = NULLCHAR;
10227 for(i=1; command[i]; i++) if(!strcmp(mnemonic[i], engineName)) break;
10229 snprintf(buf, MSG_SIZ, "-fcp %s", command[i]);
10230 ParseArgsFromString(resetOptions); appData.fenOverride[0] = NULL; appData.pvSAN[0] = FALSE;
10231 appData.firstHasOwnBookUCI = !appData.defNoBook; appData.protocolVersion[0] = PROTOVER;
10232 ParseArgsFromString(buf);
10238 char *recentEngines;
10241 RecentEngineEvent (int nr)
10244 // SwapEngines(1); // bump first to second
10245 // ReplaceEngine(&second, 1); // and load it there
10246 NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
10247 n = SetPlayer(nr, recentEngines); // select new (using original menu order!)
10248 if(mnemonic[n]) { // if somehow the engine with the selected nickname is no longer found in the list, we skip
10249 ReplaceEngine(&first, 0);
10250 FloatToFront(&appData.recentEngineList, command[n]);
10255 Pairing (int nr, int nPlayers, int *whitePlayer, int *blackPlayer, int *syncInterval)
10256 { // determine players from game number
10257 int curCycle, curRound, curPairing, gamesPerCycle, gamesPerRound, roundsPerCycle=1, pairingsPerRound=1;
10259 if(appData.tourneyType == 0) {
10260 roundsPerCycle = (nPlayers - 1) | 1;
10261 pairingsPerRound = nPlayers / 2;
10262 } else if(appData.tourneyType > 0) {
10263 roundsPerCycle = nPlayers - appData.tourneyType;
10264 pairingsPerRound = appData.tourneyType;
10266 gamesPerRound = pairingsPerRound * appData.defaultMatchGames;
10267 gamesPerCycle = gamesPerRound * roundsPerCycle;
10268 appData.matchGames = gamesPerCycle * appData.tourneyCycles - 1; // fake like all games are one big match
10269 curCycle = nr / gamesPerCycle; nr %= gamesPerCycle;
10270 curRound = nr / gamesPerRound; nr %= gamesPerRound;
10271 curPairing = nr / appData.defaultMatchGames; nr %= appData.defaultMatchGames;
10272 matchGame = nr + curCycle * appData.defaultMatchGames + 1; // fake game nr that loads correct game or position from file
10273 roundNr = (curCycle * roundsPerCycle + curRound) * appData.defaultMatchGames + nr + 1;
10275 if(appData.cycleSync) *syncInterval = gamesPerCycle;
10276 if(appData.roundSync) *syncInterval = gamesPerRound;
10278 if(appData.debugMode) fprintf(debugFP, "cycle=%d, round=%d, pairing=%d curGame=%d\n", curCycle, curRound, curPairing, matchGame);
10280 if(appData.tourneyType == 0) {
10281 if(curPairing == (nPlayers-1)/2 ) {
10282 *whitePlayer = curRound;
10283 *blackPlayer = nPlayers - 1; // this is the 'bye' when nPlayer is odd
10285 *whitePlayer = curRound - (nPlayers-1)/2 + curPairing;
10286 if(*whitePlayer < 0) *whitePlayer += nPlayers-1+(nPlayers&1);
10287 *blackPlayer = curRound + (nPlayers-1)/2 - curPairing;
10288 if(*blackPlayer >= nPlayers-1+(nPlayers&1)) *blackPlayer -= nPlayers-1+(nPlayers&1);
10290 } else if(appData.tourneyType > 1) {
10291 *blackPlayer = curPairing; // in multi-gauntlet, assign gauntlet engines to second, so first an be kept loaded during round
10292 *whitePlayer = curRound + appData.tourneyType;
10293 } else if(appData.tourneyType > 0) {
10294 *whitePlayer = curPairing;
10295 *blackPlayer = curRound + appData.tourneyType;
10298 // take care of white/black alternation per round.
10299 // For cycles and games this is already taken care of by default, derived from matchGame!
10300 return curRound & 1;
10304 NextTourneyGame (int nr, int *swapColors)
10305 { // !!!major kludge!!! fiddle appData settings to get everything in order for next tourney game
10307 int whitePlayer, blackPlayer, firstBusy=1000000000, syncInterval = 0, nPlayers;
10309 if(appData.tourneyFile[0] == NULLCHAR) return 1; // no tourney, always allow next game
10310 tf = fopen(appData.tourneyFile, "r");
10311 if(tf == NULL) { DisplayFatalError(_("Bad tournament file"), 0, 1); return 0; }
10312 ParseArgsFromFile(tf); fclose(tf);
10313 InitTimeControls(); // TC might be altered from tourney file
10315 nPlayers = CountPlayers(appData.participants); // count participants
10316 if(appData.tourneyType < 0) syncInterval = nPlayers/2; else
10317 *swapColors = Pairing(nr<0 ? 0 : nr, nPlayers, &whitePlayer, &blackPlayer, &syncInterval);
10320 p = q = appData.results;
10321 while(*q) if(*q++ == '*' || q[-1] == ' ') { firstBusy = q - p - 1; break; }
10322 if(firstBusy/syncInterval < (nextGame/syncInterval)) {
10323 DisplayMessage(_("Waiting for other game(s)"),"");
10324 waitingForGame = TRUE;
10325 ScheduleDelayedEvent(NextMatchGame, 1000); // wait for all games of previous round to finish
10328 waitingForGame = FALSE;
10331 if(appData.tourneyType < 0) {
10332 if(nr>=0 && !pairingReceived) {
10334 if(pairing.pr == NoProc) {
10335 if(!appData.pairingEngine[0]) {
10336 DisplayFatalError(_("No pairing engine specified"), 0, 1);
10339 StartChessProgram(&pairing); // starts the pairing engine
10341 snprintf(buf, 1<<16, "results %d %s\n", nPlayers, appData.results);
10342 SendToProgram(buf, &pairing);
10343 snprintf(buf, 1<<16, "pairing %d\n", nr+1);
10344 SendToProgram(buf, &pairing);
10345 return 0; // wait for pairing engine to answer (which causes NextTourneyGame to be called again...
10347 pairingReceived = 0; // ... so we continue here
10349 appData.matchGames = appData.tourneyCycles * syncInterval - 1;
10350 whitePlayer = savedWhitePlayer-1; blackPlayer = savedBlackPlayer-1;
10351 matchGame = 1; roundNr = nr / syncInterval + 1;
10354 if(first.pr != NoProc && second.pr != NoProc || nr<0) return 1; // engines already loaded
10356 // redefine engines, engine dir, etc.
10357 NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
10358 if(first.pr == NoProc) {
10359 SetPlayer(whitePlayer, appData.participants); // find white player amongst it, and parse its engine line
10360 InitEngine(&first, 0); // initialize ChessProgramStates based on new settings.
10362 if(second.pr == NoProc) {
10364 SetPlayer(blackPlayer, appData.participants); // find black player amongst it, and parse its engine line
10365 SwapEngines(1); // and make that valid for second engine by swapping
10366 InitEngine(&second, 1);
10368 CommonEngineInit(); // after this TwoMachinesEvent will create correct engine processes
10369 UpdateLogos(FALSE); // leave display to ModeHiglight()
10375 { // performs game initialization that does not invoke engines, and then tries to start the game
10376 int res, firstWhite, swapColors = 0;
10377 if(!NextTourneyGame(nextGame, &swapColors)) return; // this sets matchGame, -fcp / -scp and other options for next game, if needed
10378 if(matchMode && appData.debugMode) { // [HGM] debug split: game is part of a match; we might have to create a debug file just for this game
10380 snprintf(buf, MSG_SIZ, appData.nameOfDebugFile, nextGame+1); // expand name of debug file with %d in it
10381 if(strcmp(buf, currentDebugFile)) { // name has changed
10382 FILE *f = fopen(buf, "w");
10383 if(f) { // if opening the new file failed, just keep using the old one
10384 ASSIGN(currentDebugFile, buf);
10388 if(appData.serverFileName) {
10389 if(serverFP) fclose(serverFP);
10390 serverFP = fopen(appData.serverFileName, "w");
10391 if(serverFP && first.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", first.tidy);
10392 if(serverFP && second.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", second.tidy);
10396 firstWhite = appData.firstPlaysBlack ^ (matchGame & 1 | appData.sameColorGames > 1); // non-incremental default
10397 firstWhite ^= swapColors; // reverses if NextTourneyGame says we are in an odd round
10398 first.twoMachinesColor = firstWhite ? "white\n" : "black\n"; // perform actual color assignement
10399 second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
10400 appData.noChessProgram = (first.pr == NoProc); // kludge to prevent Reset from starting up chess program
10401 if(appData.loadGameIndex == -2) srandom(appData.seedBase + 68163*(nextGame & ~1)); // deterministic seed to force same opening
10402 Reset(FALSE, first.pr != NoProc);
10403 res = LoadGameOrPosition(matchGame); // setup game
10404 appData.noChessProgram = FALSE; // LoadGameOrPosition might call Reset too!
10405 if(!res) return; // abort when bad game/pos file
10406 TwoMachinesEvent();
10410 UserAdjudicationEvent (int result)
10412 ChessMove gameResult = GameIsDrawn;
10415 gameResult = WhiteWins;
10417 else if( result < 0 ) {
10418 gameResult = BlackWins;
10421 if( gameMode == TwoMachinesPlay ) {
10422 GameEnds( gameResult, "User adjudication", GE_XBOARD );
10427 // [HGM] save: calculate checksum of game to make games easily identifiable
10429 StringCheckSum (char *s)
10432 if(s==NULL) return 0;
10433 while(*s) i = i*259 + *s++;
10441 for(i=backwardMostMove; i<forwardMostMove; i++) {
10442 sum += pvInfoList[i].depth;
10443 sum += StringCheckSum(parseList[i]);
10444 sum += StringCheckSum(commentList[i]);
10447 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
10448 return sum + StringCheckSum(commentList[i]);
10449 } // end of save patch
10452 GameEnds (ChessMove result, char *resultDetails, int whosays)
10454 GameMode nextGameMode;
10456 char buf[MSG_SIZ], popupRequested = 0, *ranking = NULL;
10458 if(endingGame) return; /* [HGM] crash: forbid recursion */
10460 if(twoBoards) { // [HGM] dual: switch back to one board
10461 twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
10462 DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
10464 if (appData.debugMode) {
10465 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
10466 result, resultDetails ? resultDetails : "(null)", whosays);
10469 fromX = fromY = -1; // [HGM] abort any move the user is entering.
10471 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
10472 /* If we are playing on ICS, the server decides when the
10473 game is over, but the engine can offer to draw, claim
10477 if (appData.zippyPlay && first.initDone) {
10478 if (result == GameIsDrawn) {
10479 /* In case draw still needs to be claimed */
10480 SendToICS(ics_prefix);
10481 SendToICS("draw\n");
10482 } else if (StrCaseStr(resultDetails, "resign")) {
10483 SendToICS(ics_prefix);
10484 SendToICS("resign\n");
10488 endingGame = 0; /* [HGM] crash */
10492 /* If we're loading the game from a file, stop */
10493 if (whosays == GE_FILE) {
10494 (void) StopLoadGameTimer();
10498 /* Cancel draw offers */
10499 first.offeredDraw = second.offeredDraw = 0;
10501 /* If this is an ICS game, only ICS can really say it's done;
10502 if not, anyone can. */
10503 isIcsGame = (gameMode == IcsPlayingWhite ||
10504 gameMode == IcsPlayingBlack ||
10505 gameMode == IcsObserving ||
10506 gameMode == IcsExamining);
10508 if (!isIcsGame || whosays == GE_ICS) {
10509 /* OK -- not an ICS game, or ICS said it was done */
10511 if (!isIcsGame && !appData.noChessProgram)
10512 SetUserThinkingEnables();
10514 /* [HGM] if a machine claims the game end we verify this claim */
10515 if(gameMode == TwoMachinesPlay && appData.testClaims) {
10516 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
10518 ChessMove trueResult = (ChessMove) -1;
10520 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
10521 first.twoMachinesColor[0] :
10522 second.twoMachinesColor[0] ;
10524 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
10525 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
10526 /* [HGM] verify: engine mate claims accepted if they were flagged */
10527 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
10529 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
10530 /* [HGM] verify: engine mate claims accepted if they were flagged */
10531 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
10533 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
10534 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
10537 // now verify win claims, but not in drop games, as we don't understand those yet
10538 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
10539 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) &&
10540 (result == WhiteWins && claimer == 'w' ||
10541 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
10542 if (appData.debugMode) {
10543 fprintf(debugFP, "result=%d sp=%d move=%d\n",
10544 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
10546 if(result != trueResult) {
10547 snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
10548 result = claimer == 'w' ? BlackWins : WhiteWins;
10549 resultDetails = buf;
10552 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
10553 && (forwardMostMove <= backwardMostMove ||
10554 (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
10555 (claimer=='b')==(forwardMostMove&1))
10557 /* [HGM] verify: draws that were not flagged are false claims */
10558 snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
10559 result = claimer == 'w' ? BlackWins : WhiteWins;
10560 resultDetails = buf;
10562 /* (Claiming a loss is accepted no questions asked!) */
10564 /* [HGM] bare: don't allow bare King to win */
10565 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
10566 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
10567 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
10568 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
10569 && result != GameIsDrawn)
10570 { int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
10571 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
10572 int p = (signed char)boards[forwardMostMove][i][j] - color;
10573 if(p >= 0 && p <= (int)WhiteKing) k++;
10575 if (appData.debugMode) {
10576 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
10577 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
10580 result = GameIsDrawn;
10581 snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
10582 resultDetails = buf;
10588 if(serverMoves != NULL && !loadFlag) { char c = '=';
10589 if(result==WhiteWins) c = '+';
10590 if(result==BlackWins) c = '-';
10591 if(resultDetails != NULL)
10592 fprintf(serverMoves, ";%c;%s\n", c, resultDetails), fflush(serverMoves);
10594 if (resultDetails != NULL) {
10595 gameInfo.result = result;
10596 gameInfo.resultDetails = StrSave(resultDetails);
10598 /* display last move only if game was not loaded from file */
10599 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
10600 DisplayMove(currentMove - 1);
10602 if (forwardMostMove != 0) {
10603 if (gameMode != PlayFromGameFile && gameMode != EditGame
10604 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
10606 if (*appData.saveGameFile != NULLCHAR) {
10607 SaveGameToFile(appData.saveGameFile, TRUE);
10608 } else if (appData.autoSaveGames) {
10611 if (*appData.savePositionFile != NULLCHAR) {
10612 SavePositionToFile(appData.savePositionFile);
10617 /* Tell program how game ended in case it is learning */
10618 /* [HGM] Moved this to after saving the PGN, just in case */
10619 /* engine died and we got here through time loss. In that */
10620 /* case we will get a fatal error writing the pipe, which */
10621 /* would otherwise lose us the PGN. */
10622 /* [HGM] crash: not needed anymore, but doesn't hurt; */
10623 /* output during GameEnds should never be fatal anymore */
10624 if (gameMode == MachinePlaysWhite ||
10625 gameMode == MachinePlaysBlack ||
10626 gameMode == TwoMachinesPlay ||
10627 gameMode == IcsPlayingWhite ||
10628 gameMode == IcsPlayingBlack ||
10629 gameMode == BeginningOfGame) {
10631 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
10633 if (first.pr != NoProc) {
10634 SendToProgram(buf, &first);
10636 if (second.pr != NoProc &&
10637 gameMode == TwoMachinesPlay) {
10638 SendToProgram(buf, &second);
10643 if (appData.icsActive) {
10644 if (appData.quietPlay &&
10645 (gameMode == IcsPlayingWhite ||
10646 gameMode == IcsPlayingBlack)) {
10647 SendToICS(ics_prefix);
10648 SendToICS("set shout 1\n");
10650 nextGameMode = IcsIdle;
10651 ics_user_moved = FALSE;
10652 /* clean up premove. It's ugly when the game has ended and the
10653 * premove highlights are still on the board.
10656 gotPremove = FALSE;
10657 ClearPremoveHighlights();
10658 DrawPosition(FALSE, boards[currentMove]);
10660 if (whosays == GE_ICS) {
10663 if (gameMode == IcsPlayingWhite)
10665 else if(gameMode == IcsPlayingBlack)
10666 PlayIcsLossSound();
10669 if (gameMode == IcsPlayingBlack)
10671 else if(gameMode == IcsPlayingWhite)
10672 PlayIcsLossSound();
10675 PlayIcsDrawSound();
10678 PlayIcsUnfinishedSound();
10681 } else if (gameMode == EditGame ||
10682 gameMode == PlayFromGameFile ||
10683 gameMode == AnalyzeMode ||
10684 gameMode == AnalyzeFile) {
10685 nextGameMode = gameMode;
10687 nextGameMode = EndOfGame;
10692 nextGameMode = gameMode;
10695 if (appData.noChessProgram) {
10696 gameMode = nextGameMode;
10698 endingGame = 0; /* [HGM] crash */
10703 /* Put first chess program into idle state */
10704 if (first.pr != NoProc &&
10705 (gameMode == MachinePlaysWhite ||
10706 gameMode == MachinePlaysBlack ||
10707 gameMode == TwoMachinesPlay ||
10708 gameMode == IcsPlayingWhite ||
10709 gameMode == IcsPlayingBlack ||
10710 gameMode == BeginningOfGame)) {
10711 SendToProgram("force\n", &first);
10712 if (first.usePing) {
10714 snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
10715 SendToProgram(buf, &first);
10718 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
10719 /* Kill off first chess program */
10720 if (first.isr != NULL)
10721 RemoveInputSource(first.isr);
10724 if (first.pr != NoProc) {
10726 DoSleep( appData.delayBeforeQuit );
10727 SendToProgram("quit\n", &first);
10728 DoSleep( appData.delayAfterQuit );
10729 DestroyChildProcess(first.pr, first.useSigterm);
10733 if (second.reuse) {
10734 /* Put second chess program into idle state */
10735 if (second.pr != NoProc &&
10736 gameMode == TwoMachinesPlay) {
10737 SendToProgram("force\n", &second);
10738 if (second.usePing) {
10740 snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
10741 SendToProgram(buf, &second);
10744 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
10745 /* Kill off second chess program */
10746 if (second.isr != NULL)
10747 RemoveInputSource(second.isr);
10750 if (second.pr != NoProc) {
10751 DoSleep( appData.delayBeforeQuit );
10752 SendToProgram("quit\n", &second);
10753 DoSleep( appData.delayAfterQuit );
10754 DestroyChildProcess(second.pr, second.useSigterm);
10756 second.pr = NoProc;
10759 if (matchMode && (gameMode == TwoMachinesPlay || waitingForGame && exiting)) {
10760 char resChar = '=';
10764 if (first.twoMachinesColor[0] == 'w') {
10767 second.matchWins++;
10772 if (first.twoMachinesColor[0] == 'b') {
10775 second.matchWins++;
10778 case GameUnfinished:
10784 if(waitingForGame) resChar = ' '; // quit while waiting for round sync: unreserve already reserved game
10785 if(appData.tourneyFile[0]){ // [HGM] we are in a tourney; update tourney file with game result
10786 if(appData.afterGame && appData.afterGame[0]) RunCommand(appData.afterGame);
10787 ReserveGame(nextGame, resChar); // sets nextGame
10788 if(nextGame > appData.matchGames) appData.tourneyFile[0] = 0, ranking = TourneyStandings(3); // tourney is done
10789 else ranking = strdup("busy"); //suppress popup when aborted but not finished
10790 } else roundNr = nextGame = matchGame + 1; // normal match, just increment; round equals matchGame
10792 if (nextGame <= appData.matchGames && !abortMatch) {
10793 gameMode = nextGameMode;
10794 matchGame = nextGame; // this will be overruled in tourney mode!
10795 GetTimeMark(&pauseStart); // [HGM] matchpause: stipulate a pause
10796 ScheduleDelayedEvent(NextMatchGame, 10); // but start game immediately (as it will wait out the pause itself)
10797 endingGame = 0; /* [HGM] crash */
10800 gameMode = nextGameMode;
10801 snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
10802 first.tidy, second.tidy,
10803 first.matchWins, second.matchWins,
10804 appData.matchGames - (first.matchWins + second.matchWins));
10805 if(!appData.tourneyFile[0]) matchGame++, DisplayTwoMachinesTitle(); // [HGM] update result in window title
10806 if(ranking && strcmp(ranking, "busy") && appData.afterTourney && appData.afterTourney[0]) RunCommand(appData.afterTourney);
10807 popupRequested++; // [HGM] crash: postpone to after resetting endingGame
10808 if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
10809 first.twoMachinesColor = "black\n";
10810 second.twoMachinesColor = "white\n";
10812 first.twoMachinesColor = "white\n";
10813 second.twoMachinesColor = "black\n";
10817 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
10818 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
10820 gameMode = nextGameMode;
10822 endingGame = 0; /* [HGM] crash */
10823 if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
10824 if(matchMode == TRUE) { // match through command line: exit with or without popup
10826 ToNrEvent(forwardMostMove);
10827 if(strcmp(ranking, "busy")) DisplayFatalError(ranking, 0, 0);
10829 } else DisplayFatalError(buf, 0, 0);
10830 } else { // match through menu; just stop, with or without popup
10831 matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
10834 if(strcmp(ranking, "busy")) DisplayNote(ranking);
10835 } else DisplayNote(buf);
10837 if(ranking) free(ranking);
10841 /* Assumes program was just initialized (initString sent).
10842 Leaves program in force mode. */
10844 FeedMovesToProgram (ChessProgramState *cps, int upto)
10848 if (appData.debugMode)
10849 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
10850 startedFromSetupPosition ? "position and " : "",
10851 backwardMostMove, upto, cps->which);
10852 if(currentlyInitializedVariant != gameInfo.variant) {
10854 // [HGM] variantswitch: make engine aware of new variant
10855 if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL)
10856 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
10857 snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
10858 SendToProgram(buf, cps);
10859 currentlyInitializedVariant = gameInfo.variant;
10861 SendToProgram("force\n", cps);
10862 if (startedFromSetupPosition) {
10863 SendBoard(cps, backwardMostMove);
10864 if (appData.debugMode) {
10865 fprintf(debugFP, "feedMoves\n");
10868 for (i = backwardMostMove; i < upto; i++) {
10869 SendMoveToProgram(i, cps);
10875 ResurrectChessProgram ()
10877 /* The chess program may have exited.
10878 If so, restart it and feed it all the moves made so far. */
10879 static int doInit = 0;
10881 if (appData.noChessProgram) return 1;
10883 if(matchMode && appData.tourneyFile[0]) { // [HGM] tourney: make sure we get features after engine replacement. (Should we always do this?)
10884 if(WaitForEngine(&first, TwoMachinesEventIfReady)) { doInit = 1; return 0; } // request to do init on next visit
10885 if(!doInit) return 1; // this replaces testing first.pr != NoProc, which is true when we get here, but first time no reason to abort
10886 doInit = 0; // we fell through (first time after starting the engine); make sure it doesn't happen again
10888 if (first.pr != NoProc) return 1;
10889 StartChessProgram(&first);
10891 InitChessProgram(&first, FALSE);
10892 FeedMovesToProgram(&first, currentMove);
10894 if (!first.sendTime) {
10895 /* can't tell gnuchess what its clock should read,
10896 so we bow to its notion. */
10898 timeRemaining[0][currentMove] = whiteTimeRemaining;
10899 timeRemaining[1][currentMove] = blackTimeRemaining;
10902 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
10903 appData.icsEngineAnalyze) && first.analysisSupport) {
10904 SendToProgram("analyze\n", &first);
10905 first.analyzing = TRUE;
10911 * Button procedures
10914 Reset (int redraw, int init)
10918 if (appData.debugMode) {
10919 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
10920 redraw, init, gameMode);
10922 CleanupTail(); // [HGM] vari: delete any stored variations
10923 CommentPopDown(); // [HGM] make sure no comments to the previous game keep hanging on
10924 pausing = pauseExamInvalid = FALSE;
10925 startedFromSetupPosition = blackPlaysFirst = FALSE;
10927 whiteFlag = blackFlag = FALSE;
10928 userOfferedDraw = FALSE;
10929 hintRequested = bookRequested = FALSE;
10930 first.maybeThinking = FALSE;
10931 second.maybeThinking = FALSE;
10932 first.bookSuspend = FALSE; // [HGM] book
10933 second.bookSuspend = FALSE;
10934 thinkOutput[0] = NULLCHAR;
10935 lastHint[0] = NULLCHAR;
10936 ClearGameInfo(&gameInfo);
10937 gameInfo.variant = StringToVariant(appData.variant);
10938 ics_user_moved = ics_clock_paused = FALSE;
10939 ics_getting_history = H_FALSE;
10941 white_holding[0] = black_holding[0] = NULLCHAR;
10942 ClearProgramStats();
10943 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
10947 flipView = appData.flipView;
10948 ClearPremoveHighlights();
10949 gotPremove = FALSE;
10950 alarmSounded = FALSE;
10952 GameEnds(EndOfFile, NULL, GE_PLAYER);
10953 if(appData.serverMovesName != NULL) {
10954 /* [HGM] prepare to make moves file for broadcasting */
10955 clock_t t = clock();
10956 if(serverMoves != NULL) fclose(serverMoves);
10957 serverMoves = fopen(appData.serverMovesName, "r");
10958 if(serverMoves != NULL) {
10959 fclose(serverMoves);
10960 /* delay 15 sec before overwriting, so all clients can see end */
10961 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
10963 serverMoves = fopen(appData.serverMovesName, "w");
10967 gameMode = BeginningOfGame;
10969 if(appData.icsActive) gameInfo.variant = VariantNormal;
10970 currentMove = forwardMostMove = backwardMostMove = 0;
10971 MarkTargetSquares(1);
10972 InitPosition(redraw);
10973 for (i = 0; i < MAX_MOVES; i++) {
10974 if (commentList[i] != NULL) {
10975 free(commentList[i]);
10976 commentList[i] = NULL;
10980 timeRemaining[0][0] = whiteTimeRemaining;
10981 timeRemaining[1][0] = blackTimeRemaining;
10983 if (first.pr == NoProc) {
10984 StartChessProgram(&first);
10987 InitChessProgram(&first, startedFromSetupPosition);
10990 DisplayMessage("", "");
10991 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
10992 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
10993 ClearMap(); // [HGM] exclude: invalidate map
10997 AutoPlayGameLoop ()
11000 if (!AutoPlayOneMove())
11002 if (matchMode || appData.timeDelay == 0)
11004 if (appData.timeDelay < 0)
11006 StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
11014 ReloadGame(1); // next game
11020 int fromX, fromY, toX, toY;
11022 if (appData.debugMode) {
11023 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
11026 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
11029 if (gameMode == AnalyzeFile && currentMove > backwardMostMove) {
11030 pvInfoList[currentMove].depth = programStats.depth;
11031 pvInfoList[currentMove].score = programStats.score;
11032 pvInfoList[currentMove].time = 0;
11033 if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
11036 if (currentMove >= forwardMostMove) {
11037 if(gameMode == AnalyzeFile) {
11038 if(appData.loadGameIndex == -1) {
11039 GameEnds(EndOfFile, NULL, GE_FILE);
11040 ScheduleDelayedEvent(AnalyzeNextGame, 10);
11042 ExitAnalyzeMode(); SendToProgram("force\n", &first);
11045 // gameMode = EndOfGame;
11046 // ModeHighlight();
11048 /* [AS] Clear current move marker at the end of a game */
11049 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
11054 toX = moveList[currentMove][2] - AAA;
11055 toY = moveList[currentMove][3] - ONE;
11057 if (moveList[currentMove][1] == '@') {
11058 if (appData.highlightLastMove) {
11059 SetHighlights(-1, -1, toX, toY);
11062 fromX = moveList[currentMove][0] - AAA;
11063 fromY = moveList[currentMove][1] - ONE;
11065 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
11067 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
11069 if (appData.highlightLastMove) {
11070 SetHighlights(fromX, fromY, toX, toY);
11073 DisplayMove(currentMove);
11074 SendMoveToProgram(currentMove++, &first);
11075 DisplayBothClocks();
11076 DrawPosition(FALSE, boards[currentMove]);
11077 // [HGM] PV info: always display, routine tests if empty
11078 DisplayComment(currentMove - 1, commentList[currentMove]);
11084 LoadGameOneMove (ChessMove readAhead)
11086 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
11087 char promoChar = NULLCHAR;
11088 ChessMove moveType;
11089 char move[MSG_SIZ];
11092 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
11093 gameMode != AnalyzeMode && gameMode != Training) {
11098 yyboardindex = forwardMostMove;
11099 if (readAhead != EndOfFile) {
11100 moveType = readAhead;
11102 if (gameFileFP == NULL)
11104 moveType = (ChessMove) Myylex();
11108 switch (moveType) {
11110 if (appData.debugMode)
11111 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
11114 /* append the comment but don't display it */
11115 AppendComment(currentMove, p, FALSE);
11118 case WhiteCapturesEnPassant:
11119 case BlackCapturesEnPassant:
11120 case WhitePromotion:
11121 case BlackPromotion:
11122 case WhiteNonPromotion:
11123 case BlackNonPromotion:
11125 case WhiteKingSideCastle:
11126 case WhiteQueenSideCastle:
11127 case BlackKingSideCastle:
11128 case BlackQueenSideCastle:
11129 case WhiteKingSideCastleWild:
11130 case WhiteQueenSideCastleWild:
11131 case BlackKingSideCastleWild:
11132 case BlackQueenSideCastleWild:
11134 case WhiteHSideCastleFR:
11135 case WhiteASideCastleFR:
11136 case BlackHSideCastleFR:
11137 case BlackASideCastleFR:
11139 if (appData.debugMode)
11140 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
11141 fromX = currentMoveString[0] - AAA;
11142 fromY = currentMoveString[1] - ONE;
11143 toX = currentMoveString[2] - AAA;
11144 toY = currentMoveString[3] - ONE;
11145 promoChar = currentMoveString[4];
11150 if (appData.debugMode)
11151 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
11152 fromX = moveType == WhiteDrop ?
11153 (int) CharToPiece(ToUpper(currentMoveString[0])) :
11154 (int) CharToPiece(ToLower(currentMoveString[0]));
11156 toX = currentMoveString[2] - AAA;
11157 toY = currentMoveString[3] - ONE;
11163 case GameUnfinished:
11164 if (appData.debugMode)
11165 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
11166 p = strchr(yy_text, '{');
11167 if (p == NULL) p = strchr(yy_text, '(');
11170 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
11172 q = strchr(p, *p == '{' ? '}' : ')');
11173 if (q != NULL) *q = NULLCHAR;
11176 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
11177 GameEnds(moveType, p, GE_FILE);
11179 if (cmailMsgLoaded) {
11181 flipView = WhiteOnMove(currentMove);
11182 if (moveType == GameUnfinished) flipView = !flipView;
11183 if (appData.debugMode)
11184 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
11189 if (appData.debugMode)
11190 fprintf(debugFP, "Parser hit end of file\n");
11191 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11197 if (WhiteOnMove(currentMove)) {
11198 GameEnds(BlackWins, "Black mates", GE_FILE);
11200 GameEnds(WhiteWins, "White mates", GE_FILE);
11204 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
11210 case MoveNumberOne:
11211 if (lastLoadGameStart == GNUChessGame) {
11212 /* GNUChessGames have numbers, but they aren't move numbers */
11213 if (appData.debugMode)
11214 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
11215 yy_text, (int) moveType);
11216 return LoadGameOneMove(EndOfFile); /* tail recursion */
11218 /* else fall thru */
11223 /* Reached start of next game in file */
11224 if (appData.debugMode)
11225 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
11226 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11232 if (WhiteOnMove(currentMove)) {
11233 GameEnds(BlackWins, "Black mates", GE_FILE);
11235 GameEnds(WhiteWins, "White mates", GE_FILE);
11239 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
11245 case PositionDiagram: /* should not happen; ignore */
11246 case ElapsedTime: /* ignore */
11247 case NAG: /* ignore */
11248 if (appData.debugMode)
11249 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
11250 yy_text, (int) moveType);
11251 return LoadGameOneMove(EndOfFile); /* tail recursion */
11254 if (appData.testLegality) {
11255 if (appData.debugMode)
11256 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
11257 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
11258 (forwardMostMove / 2) + 1,
11259 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
11260 DisplayError(move, 0);
11263 if (appData.debugMode)
11264 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
11265 yy_text, currentMoveString);
11266 fromX = currentMoveString[0] - AAA;
11267 fromY = currentMoveString[1] - ONE;
11268 toX = currentMoveString[2] - AAA;
11269 toY = currentMoveString[3] - ONE;
11270 promoChar = currentMoveString[4];
11274 case AmbiguousMove:
11275 if (appData.debugMode)
11276 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
11277 snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
11278 (forwardMostMove / 2) + 1,
11279 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
11280 DisplayError(move, 0);
11285 case ImpossibleMove:
11286 if (appData.debugMode)
11287 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
11288 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
11289 (forwardMostMove / 2) + 1,
11290 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
11291 DisplayError(move, 0);
11297 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
11298 DrawPosition(FALSE, boards[currentMove]);
11299 DisplayBothClocks();
11300 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
11301 DisplayComment(currentMove - 1, commentList[currentMove]);
11303 (void) StopLoadGameTimer();
11305 cmailOldMove = forwardMostMove;
11308 /* currentMoveString is set as a side-effect of yylex */
11310 thinkOutput[0] = NULLCHAR;
11311 MakeMove(fromX, fromY, toX, toY, promoChar);
11312 currentMove = forwardMostMove;
11317 /* Load the nth game from the given file */
11319 LoadGameFromFile (char *filename, int n, char *title, int useList)
11324 if (strcmp(filename, "-") == 0) {
11328 f = fopen(filename, "rb");
11330 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
11331 DisplayError(buf, errno);
11335 if (fseek(f, 0, 0) == -1) {
11336 /* f is not seekable; probably a pipe */
11339 if (useList && n == 0) {
11340 int error = GameListBuild(f);
11342 DisplayError(_("Cannot build game list"), error);
11343 } else if (!ListEmpty(&gameList) &&
11344 ((ListGame *) gameList.tailPred)->number > 1) {
11345 GameListPopUp(f, title);
11352 return LoadGame(f, n, title, FALSE);
11357 MakeRegisteredMove ()
11359 int fromX, fromY, toX, toY;
11361 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11362 switch (cmailMoveType[lastLoadGameNumber - 1]) {
11365 if (appData.debugMode)
11366 fprintf(debugFP, "Restoring %s for game %d\n",
11367 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
11369 thinkOutput[0] = NULLCHAR;
11370 safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
11371 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
11372 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
11373 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
11374 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
11375 promoChar = cmailMove[lastLoadGameNumber - 1][4];
11376 MakeMove(fromX, fromY, toX, toY, promoChar);
11377 ShowMove(fromX, fromY, toX, toY);
11379 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11386 if (WhiteOnMove(currentMove)) {
11387 GameEnds(BlackWins, "Black mates", GE_PLAYER);
11389 GameEnds(WhiteWins, "White mates", GE_PLAYER);
11394 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
11401 if (WhiteOnMove(currentMove)) {
11402 GameEnds(BlackWins, "White resigns", GE_PLAYER);
11404 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
11409 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
11420 /* Wrapper around LoadGame for use when a Cmail message is loaded */
11422 CmailLoadGame (FILE *f, int gameNumber, char *title, int useList)
11426 if (gameNumber > nCmailGames) {
11427 DisplayError(_("No more games in this message"), 0);
11430 if (f == lastLoadGameFP) {
11431 int offset = gameNumber - lastLoadGameNumber;
11433 cmailMsg[0] = NULLCHAR;
11434 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
11435 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
11436 nCmailMovesRegistered--;
11438 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
11439 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
11440 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
11443 if (! RegisterMove()) return FALSE;
11447 retVal = LoadGame(f, gameNumber, title, useList);
11449 /* Make move registered during previous look at this game, if any */
11450 MakeRegisteredMove();
11452 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
11453 commentList[currentMove]
11454 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
11455 DisplayComment(currentMove - 1, commentList[currentMove]);
11461 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
11463 ReloadGame (int offset)
11465 int gameNumber = lastLoadGameNumber + offset;
11466 if (lastLoadGameFP == NULL) {
11467 DisplayError(_("No game has been loaded yet"), 0);
11470 if (gameNumber <= 0) {
11471 DisplayError(_("Can't back up any further"), 0);
11474 if (cmailMsgLoaded) {
11475 return CmailLoadGame(lastLoadGameFP, gameNumber,
11476 lastLoadGameTitle, lastLoadGameUseList);
11478 return LoadGame(lastLoadGameFP, gameNumber,
11479 lastLoadGameTitle, lastLoadGameUseList);
11483 int keys[EmptySquare+1];
11486 PositionMatches (Board b1, Board b2)
11489 switch(appData.searchMode) {
11490 case 1: return CompareWithRights(b1, b2);
11492 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11493 if(b2[r][f] != EmptySquare && b1[r][f] != b2[r][f]) return FALSE;
11497 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11498 if((b2[r][f] == WhitePawn || b2[r][f] == BlackPawn) && b1[r][f] != b2[r][f]) return FALSE;
11499 sum += keys[b1[r][f]] - keys[b2[r][f]];
11503 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11504 sum += keys[b1[r][f]] - keys[b2[r][f]];
11516 int pieceList[256], quickBoard[256];
11517 ChessSquare pieceType[256] = { EmptySquare };
11518 Board soughtBoard, reverseBoard, flipBoard, rotateBoard;
11519 int counts[EmptySquare], minSought[EmptySquare], minReverse[EmptySquare], maxSought[EmptySquare], maxReverse[EmptySquare];
11520 int soughtTotal, turn;
11521 Boolean epOK, flipSearch;
11524 unsigned char piece, to;
11527 #define DSIZE (250000)
11529 Move initialSpace[DSIZE+1000]; // gamble on that game will not be more than 500 moves
11530 Move *moveDatabase = initialSpace;
11531 unsigned int movePtr, dataSize = DSIZE;
11534 MakePieceList (Board board, int *counts)
11536 int r, f, n=Q_PROMO, total=0;
11537 for(r=0;r<EmptySquare;r++) counts[r] = 0; // piece-type counts
11538 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11539 int sq = f + (r<<4);
11540 if(board[r][f] == EmptySquare) quickBoard[sq] = 0; else {
11541 quickBoard[sq] = ++n;
11543 pieceType[n] = board[r][f];
11544 counts[board[r][f]]++;
11545 if(board[r][f] == WhiteKing) pieceList[1] = n; else
11546 if(board[r][f] == BlackKing) pieceList[2] = n; // remember which are Kings, for castling
11550 epOK = gameInfo.variant != VariantXiangqi && gameInfo.variant != VariantBerolina;
11555 PackMove (int fromX, int fromY, int toX, int toY, ChessSquare promoPiece)
11557 int sq = fromX + (fromY<<4);
11558 int piece = quickBoard[sq];
11559 quickBoard[sq] = 0;
11560 moveDatabase[movePtr].to = pieceList[piece] = sq = toX + (toY<<4);
11561 if(piece == pieceList[1] && fromY == toY && (toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
11562 int from = toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT;
11563 moveDatabase[movePtr++].piece = Q_WCASTL;
11564 quickBoard[sq] = piece;
11565 piece = quickBoard[from]; quickBoard[from] = 0;
11566 moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
11568 if(piece == pieceList[2] && fromY == toY && (toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
11569 int from = (toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT) + (BOARD_HEIGHT-1 <<4);
11570 moveDatabase[movePtr++].piece = Q_BCASTL;
11571 quickBoard[sq] = piece;
11572 piece = quickBoard[from]; quickBoard[from] = 0;
11573 moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
11575 if(epOK && (pieceType[piece] == WhitePawn || pieceType[piece] == BlackPawn) && fromX != toX && quickBoard[sq] == 0) {
11576 quickBoard[(fromY<<4)+toX] = 0;
11577 moveDatabase[movePtr].piece = Q_EP;
11578 moveDatabase[movePtr++].to = (fromY<<4)+toX;
11579 moveDatabase[movePtr].to = sq;
11581 if(promoPiece != pieceType[piece]) {
11582 moveDatabase[movePtr++].piece = Q_PROMO;
11583 moveDatabase[movePtr].to = pieceType[piece] = (int) promoPiece;
11585 moveDatabase[movePtr].piece = piece;
11586 quickBoard[sq] = piece;
11591 PackGame (Board board)
11593 Move *newSpace = NULL;
11594 moveDatabase[movePtr].piece = 0; // terminate previous game
11595 if(movePtr > dataSize) {
11596 if(appData.debugMode) fprintf(debugFP, "move-cache overflow, enlarge to %d MB\n", dataSize/128);
11597 dataSize *= 8; // increase size by factor 8 (512KB -> 4MB -> 32MB -> 256MB -> 2GB)
11598 if(dataSize) newSpace = (Move*) calloc(dataSize + 1000, sizeof(Move));
11601 Move *p = moveDatabase, *q = newSpace;
11602 for(i=0; i<movePtr; i++) *q++ = *p++; // copy to newly allocated space
11603 if(dataSize > 8*DSIZE) free(moveDatabase); // and free old space (if it was allocated)
11604 moveDatabase = newSpace;
11605 } else { // calloc failed, we must be out of memory. Too bad...
11606 dataSize = 0; // prevent calloc events for all subsequent games
11607 return 0; // and signal this one isn't cached
11611 MakePieceList(board, counts);
11616 QuickCompare (Board board, int *minCounts, int *maxCounts)
11617 { // compare according to search mode
11619 switch(appData.searchMode)
11621 case 1: // exact position match
11622 if(!(turn & board[EP_STATUS-1])) return FALSE; // wrong side to move
11623 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11624 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
11627 case 2: // can have extra material on empty squares
11628 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11629 if(board[r][f] == EmptySquare) continue;
11630 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
11633 case 3: // material with exact Pawn structure
11634 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11635 if(board[r][f] != WhitePawn && board[r][f] != BlackPawn) continue;
11636 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
11637 } // fall through to material comparison
11638 case 4: // exact material
11639 for(r=0; r<EmptySquare; r++) if(counts[r] != maxCounts[r]) return FALSE;
11641 case 6: // material range with given imbalance
11642 for(r=0; r<BlackPawn; r++) if(counts[r] - minCounts[r] != counts[r+BlackPawn] - minCounts[r+BlackPawn]) return FALSE;
11643 // fall through to range comparison
11644 case 5: // material range
11645 for(r=0; r<EmptySquare; r++) if(counts[r] < minCounts[r] || counts[r] > maxCounts[r]) return FALSE;
11651 QuickScan (Board board, Move *move)
11652 { // reconstruct game,and compare all positions in it
11653 int cnt=0, stretch=0, total = MakePieceList(board, counts);
11655 int piece = move->piece;
11656 int to = move->to, from = pieceList[piece];
11657 if(piece <= Q_PROMO) { // special moves encoded by otherwise invalid piece numbers 1-4
11658 if(!piece) return -1;
11659 if(piece == Q_PROMO) { // promotion, encoded as (Q_PROMO, to) + (piece, promoType)
11660 piece = (++move)->piece;
11661 from = pieceList[piece];
11662 counts[pieceType[piece]]--;
11663 pieceType[piece] = (ChessSquare) move->to;
11664 counts[move->to]++;
11665 } else if(piece == Q_EP) { // e.p. capture, encoded as (Q_EP, ep-sqr) + (piece, to)
11666 counts[pieceType[quickBoard[to]]]--;
11667 quickBoard[to] = 0; total--;
11670 } else if(piece <= Q_BCASTL) { // castling, encoded as (Q_XCASTL, king-to) + (rook, rook-to)
11671 piece = pieceList[piece]; // first two elements of pieceList contain King numbers
11672 from = pieceList[piece]; // so this must be King
11673 quickBoard[from] = 0;
11674 pieceList[piece] = to;
11675 from = pieceList[(++move)->piece]; // for FRC this has to be done here
11676 quickBoard[from] = 0; // rook
11677 quickBoard[to] = piece;
11678 to = move->to; piece = move->piece;
11682 if(appData.searchMode > 2) counts[pieceType[quickBoard[to]]]--; // account capture
11683 if((total -= (quickBoard[to] != 0)) < soughtTotal) return -1; // piece count dropped below what we search for
11684 quickBoard[from] = 0;
11686 quickBoard[to] = piece;
11687 pieceList[piece] = to;
11689 if(QuickCompare(soughtBoard, minSought, maxSought) ||
11690 appData.ignoreColors && QuickCompare(reverseBoard, minReverse, maxReverse) ||
11691 flipSearch && (QuickCompare(flipBoard, minSought, maxSought) ||
11692 appData.ignoreColors && QuickCompare(rotateBoard, minReverse, maxReverse))
11694 static int lastCounts[EmptySquare+1];
11696 if(stretch) for(i=0; i<EmptySquare; i++) if(lastCounts[i] != counts[i]) { stretch = 0; break; } // reset if material changes
11697 if(stretch++ == 0) for(i=0; i<EmptySquare; i++) lastCounts[i] = counts[i]; // remember actual material
11698 } else stretch = 0;
11699 if(stretch && (appData.searchMode == 1 || stretch >= appData.stretch)) return cnt + 1 - stretch;
11708 flipSearch = FALSE;
11709 CopyBoard(soughtBoard, boards[currentMove]);
11710 soughtTotal = MakePieceList(soughtBoard, maxSought);
11711 soughtBoard[EP_STATUS-1] = (currentMove & 1) + 1;
11712 if(currentMove == 0 && gameMode == EditPosition) soughtBoard[EP_STATUS-1] = blackPlaysFirst + 1; // (!)
11713 CopyBoard(reverseBoard, boards[currentMove]);
11714 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11715 int piece = boards[currentMove][BOARD_HEIGHT-1-r][f];
11716 if(piece < BlackPawn) piece += BlackPawn; else if(piece < EmptySquare) piece -= BlackPawn; // color-flip
11717 reverseBoard[r][f] = piece;
11719 reverseBoard[EP_STATUS-1] = soughtBoard[EP_STATUS-1] ^ 3;
11720 for(r=0; r<6; r++) reverseBoard[CASTLING][r] = boards[currentMove][CASTLING][(r+3)%6];
11721 if(appData.findMirror && appData.searchMode <= 3 && (!nrCastlingRights
11722 || (boards[currentMove][CASTLING][2] == NoRights ||
11723 boards[currentMove][CASTLING][0] == NoRights && boards[currentMove][CASTLING][1] == NoRights )
11724 && (boards[currentMove][CASTLING][5] == NoRights ||
11725 boards[currentMove][CASTLING][3] == NoRights && boards[currentMove][CASTLING][4] == NoRights ) )
11728 CopyBoard(flipBoard, soughtBoard);
11729 CopyBoard(rotateBoard, reverseBoard);
11730 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
11731 flipBoard[r][f] = soughtBoard[r][BOARD_WIDTH-1-f];
11732 rotateBoard[r][f] = reverseBoard[r][BOARD_WIDTH-1-f];
11735 for(r=0; r<BlackPawn; r++) maxReverse[r] = maxSought[r+BlackPawn], maxReverse[r+BlackPawn] = maxSought[r];
11736 if(appData.searchMode >= 5) {
11737 for(r=BOARD_HEIGHT/2; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) soughtBoard[r][f] = EmptySquare;
11738 MakePieceList(soughtBoard, minSought);
11739 for(r=0; r<BlackPawn; r++) minReverse[r] = minSought[r+BlackPawn], minReverse[r+BlackPawn] = minSought[r];
11741 if(gameInfo.variant == VariantCrazyhouse || gameInfo.variant == VariantShogi || gameInfo.variant == VariantBughouse)
11742 soughtTotal = 0; // in drop games nr of pieces does not fall monotonously
11745 GameInfo dummyInfo;
11748 GameContainsPosition (FILE *f, ListGame *lg)
11750 int next, btm=0, plyNr=0, scratch=forwardMostMove+2&~1;
11751 int fromX, fromY, toX, toY;
11753 static int initDone=FALSE;
11755 // weed out games based on numerical tag comparison
11756 if(lg->gameInfo.variant != gameInfo.variant) return -1; // wrong variant
11757 if(appData.eloThreshold1 && (lg->gameInfo.whiteRating < appData.eloThreshold1 && lg->gameInfo.blackRating < appData.eloThreshold1)) return -1;
11758 if(appData.eloThreshold2 && (lg->gameInfo.whiteRating < appData.eloThreshold2 || lg->gameInfo.blackRating < appData.eloThreshold2)) return -1;
11759 if(appData.dateThreshold && (!lg->gameInfo.date || atoi(lg->gameInfo.date) < appData.dateThreshold)) return -1;
11761 for(next = WhitePawn; next<EmptySquare; next++) keys[next] = random()>>8 ^ random()<<6 ^random()<<20;
11764 if(lg->gameInfo.fen) ParseFEN(boards[scratch], &btm, lg->gameInfo.fen);
11765 else CopyBoard(boards[scratch], initialPosition); // default start position
11768 if((next = QuickScan( boards[scratch], &moveDatabase[lg->moves] )) < 0) return -1; // quick scan rules out it is there
11769 if(appData.searchMode >= 4) return next; // for material searches, trust QuickScan.
11772 if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
11773 fseek(f, lg->offset, 0);
11776 yyboardindex = scratch;
11777 quickFlag = plyNr+1;
11782 if(plyNr) return -1; // after we have seen moves, any tags will be start of next game
11788 if(plyNr) return -1; // after we have seen moves, this is for new game
11791 case AmbiguousMove: // we cannot reconstruct the game beyond these two
11792 case ImpossibleMove:
11793 case WhiteWins: // game ends here with these four
11796 case GameUnfinished:
11800 if(appData.testLegality) return -1;
11801 case WhiteCapturesEnPassant:
11802 case BlackCapturesEnPassant:
11803 case WhitePromotion:
11804 case BlackPromotion:
11805 case WhiteNonPromotion:
11806 case BlackNonPromotion:
11808 case WhiteKingSideCastle:
11809 case WhiteQueenSideCastle:
11810 case BlackKingSideCastle:
11811 case BlackQueenSideCastle:
11812 case WhiteKingSideCastleWild:
11813 case WhiteQueenSideCastleWild:
11814 case BlackKingSideCastleWild:
11815 case BlackQueenSideCastleWild:
11816 case WhiteHSideCastleFR:
11817 case WhiteASideCastleFR:
11818 case BlackHSideCastleFR:
11819 case BlackASideCastleFR:
11820 fromX = currentMoveString[0] - AAA;
11821 fromY = currentMoveString[1] - ONE;
11822 toX = currentMoveString[2] - AAA;
11823 toY = currentMoveString[3] - ONE;
11824 promoChar = currentMoveString[4];
11828 fromX = next == WhiteDrop ?
11829 (int) CharToPiece(ToUpper(currentMoveString[0])) :
11830 (int) CharToPiece(ToLower(currentMoveString[0]));
11832 toX = currentMoveString[2] - AAA;
11833 toY = currentMoveString[3] - ONE;
11837 // Move encountered; peform it. We need to shuttle between two boards, as even/odd index determines side to move
11839 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[scratch]);
11840 if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
11841 if(appData.ignoreColors && PositionMatches(boards[scratch], reverseBoard)) return plyNr;
11842 if(appData.findMirror) {
11843 if(PositionMatches(boards[scratch], flipBoard)) return plyNr;
11844 if(appData.ignoreColors && PositionMatches(boards[scratch], rotateBoard)) return plyNr;
11849 /* Load the nth game from open file f */
11851 LoadGame (FILE *f, int gameNumber, char *title, int useList)
11855 int gn = gameNumber;
11856 ListGame *lg = NULL;
11857 int numPGNTags = 0;
11859 GameMode oldGameMode;
11860 VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
11862 if (appData.debugMode)
11863 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
11865 if (gameMode == Training )
11866 SetTrainingModeOff();
11868 oldGameMode = gameMode;
11869 if (gameMode != BeginningOfGame) {
11870 Reset(FALSE, TRUE);
11874 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
11875 fclose(lastLoadGameFP);
11879 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
11882 fseek(f, lg->offset, 0);
11883 GameListHighlight(gameNumber);
11884 pos = lg->position;
11888 if(gameMode == AnalyzeFile && appData.loadGameIndex == -1)
11889 appData.loadGameIndex = 0; // [HGM] suppress error message if we reach file end after auto-stepping analysis
11891 DisplayError(_("Game number out of range"), 0);
11896 if (fseek(f, 0, 0) == -1) {
11897 if (f == lastLoadGameFP ?
11898 gameNumber == lastLoadGameNumber + 1 :
11902 DisplayError(_("Can't seek on game file"), 0);
11907 lastLoadGameFP = f;
11908 lastLoadGameNumber = gameNumber;
11909 safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
11910 lastLoadGameUseList = useList;
11914 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
11915 snprintf(buf, sizeof(buf), "%s %s %s", lg->gameInfo.white, _("vs."),
11916 lg->gameInfo.black);
11918 } else if (*title != NULLCHAR) {
11919 if (gameNumber > 1) {
11920 snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
11923 DisplayTitle(title);
11927 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
11928 gameMode = PlayFromGameFile;
11932 currentMove = forwardMostMove = backwardMostMove = 0;
11933 CopyBoard(boards[0], initialPosition);
11937 * Skip the first gn-1 games in the file.
11938 * Also skip over anything that precedes an identifiable
11939 * start of game marker, to avoid being confused by
11940 * garbage at the start of the file. Currently
11941 * recognized start of game markers are the move number "1",
11942 * the pattern "gnuchess .* game", the pattern
11943 * "^[#;%] [^ ]* game file", and a PGN tag block.
11944 * A game that starts with one of the latter two patterns
11945 * will also have a move number 1, possibly
11946 * following a position diagram.
11947 * 5-4-02: Let's try being more lenient and allowing a game to
11948 * start with an unnumbered move. Does that break anything?
11950 cm = lastLoadGameStart = EndOfFile;
11952 yyboardindex = forwardMostMove;
11953 cm = (ChessMove) Myylex();
11956 if (cmailMsgLoaded) {
11957 nCmailGames = CMAIL_MAX_GAMES - gn;
11960 DisplayError(_("Game not found in file"), 0);
11967 lastLoadGameStart = cm;
11970 case MoveNumberOne:
11971 switch (lastLoadGameStart) {
11976 case MoveNumberOne:
11978 gn--; /* count this game */
11979 lastLoadGameStart = cm;
11988 switch (lastLoadGameStart) {
11991 case MoveNumberOne:
11993 gn--; /* count this game */
11994 lastLoadGameStart = cm;
11997 lastLoadGameStart = cm; /* game counted already */
12005 yyboardindex = forwardMostMove;
12006 cm = (ChessMove) Myylex();
12007 } while (cm == PGNTag || cm == Comment);
12014 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
12015 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
12016 != CMAIL_OLD_RESULT) {
12018 cmailResult[ CMAIL_MAX_GAMES
12019 - gn - 1] = CMAIL_OLD_RESULT;
12025 /* Only a NormalMove can be at the start of a game
12026 * without a position diagram. */
12027 if (lastLoadGameStart == EndOfFile ) {
12029 lastLoadGameStart = MoveNumberOne;
12038 if (appData.debugMode)
12039 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
12041 if (cm == XBoardGame) {
12042 /* Skip any header junk before position diagram and/or move 1 */
12044 yyboardindex = forwardMostMove;
12045 cm = (ChessMove) Myylex();
12047 if (cm == EndOfFile ||
12048 cm == GNUChessGame || cm == XBoardGame) {
12049 /* Empty game; pretend end-of-file and handle later */
12054 if (cm == MoveNumberOne || cm == PositionDiagram ||
12055 cm == PGNTag || cm == Comment)
12058 } else if (cm == GNUChessGame) {
12059 if (gameInfo.event != NULL) {
12060 free(gameInfo.event);
12062 gameInfo.event = StrSave(yy_text);
12065 startedFromSetupPosition = FALSE;
12066 while (cm == PGNTag) {
12067 if (appData.debugMode)
12068 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
12069 err = ParsePGNTag(yy_text, &gameInfo);
12070 if (!err) numPGNTags++;
12072 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
12073 if(gameInfo.variant != oldVariant) {
12074 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
12075 ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
12076 InitPosition(TRUE);
12077 oldVariant = gameInfo.variant;
12078 if (appData.debugMode)
12079 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
12083 if (gameInfo.fen != NULL) {
12084 Board initial_position;
12085 startedFromSetupPosition = TRUE;
12086 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen)) {
12088 DisplayError(_("Bad FEN position in file"), 0);
12091 CopyBoard(boards[0], initial_position);
12092 if (blackPlaysFirst) {
12093 currentMove = forwardMostMove = backwardMostMove = 1;
12094 CopyBoard(boards[1], initial_position);
12095 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12096 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12097 timeRemaining[0][1] = whiteTimeRemaining;
12098 timeRemaining[1][1] = blackTimeRemaining;
12099 if (commentList[0] != NULL) {
12100 commentList[1] = commentList[0];
12101 commentList[0] = NULL;
12104 currentMove = forwardMostMove = backwardMostMove = 0;
12106 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
12108 initialRulePlies = FENrulePlies;
12109 for( i=0; i< nrCastlingRights; i++ )
12110 initialRights[i] = initial_position[CASTLING][i];
12112 yyboardindex = forwardMostMove;
12113 free(gameInfo.fen);
12114 gameInfo.fen = NULL;
12117 yyboardindex = forwardMostMove;
12118 cm = (ChessMove) Myylex();
12120 /* Handle comments interspersed among the tags */
12121 while (cm == Comment) {
12123 if (appData.debugMode)
12124 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
12126 AppendComment(currentMove, p, FALSE);
12127 yyboardindex = forwardMostMove;
12128 cm = (ChessMove) Myylex();
12132 /* don't rely on existence of Event tag since if game was
12133 * pasted from clipboard the Event tag may not exist
12135 if (numPGNTags > 0){
12137 if (gameInfo.variant == VariantNormal) {
12138 VariantClass v = StringToVariant(gameInfo.event);
12139 // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
12140 if(v < VariantShogi) gameInfo.variant = v;
12143 if( appData.autoDisplayTags ) {
12144 tags = PGNTags(&gameInfo);
12145 TagsPopUp(tags, CmailMsg());
12150 /* Make something up, but don't display it now */
12155 if (cm == PositionDiagram) {
12158 Board initial_position;
12160 if (appData.debugMode)
12161 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
12163 if (!startedFromSetupPosition) {
12165 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
12166 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
12177 initial_position[i][j++] = CharToPiece(*p);
12180 while (*p == ' ' || *p == '\t' ||
12181 *p == '\n' || *p == '\r') p++;
12183 if (strncmp(p, "black", strlen("black"))==0)
12184 blackPlaysFirst = TRUE;
12186 blackPlaysFirst = FALSE;
12187 startedFromSetupPosition = TRUE;
12189 CopyBoard(boards[0], initial_position);
12190 if (blackPlaysFirst) {
12191 currentMove = forwardMostMove = backwardMostMove = 1;
12192 CopyBoard(boards[1], initial_position);
12193 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12194 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12195 timeRemaining[0][1] = whiteTimeRemaining;
12196 timeRemaining[1][1] = blackTimeRemaining;
12197 if (commentList[0] != NULL) {
12198 commentList[1] = commentList[0];
12199 commentList[0] = NULL;
12202 currentMove = forwardMostMove = backwardMostMove = 0;
12205 yyboardindex = forwardMostMove;
12206 cm = (ChessMove) Myylex();
12209 if (first.pr == NoProc) {
12210 StartChessProgram(&first);
12212 InitChessProgram(&first, FALSE);
12213 SendToProgram("force\n", &first);
12214 if (startedFromSetupPosition) {
12215 SendBoard(&first, forwardMostMove);
12216 if (appData.debugMode) {
12217 fprintf(debugFP, "Load Game\n");
12219 DisplayBothClocks();
12222 /* [HGM] server: flag to write setup moves in broadcast file as one */
12223 loadFlag = appData.suppressLoadMoves;
12225 while (cm == Comment) {
12227 if (appData.debugMode)
12228 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
12230 AppendComment(currentMove, p, FALSE);
12231 yyboardindex = forwardMostMove;
12232 cm = (ChessMove) Myylex();
12235 if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
12236 cm == WhiteWins || cm == BlackWins ||
12237 cm == GameIsDrawn || cm == GameUnfinished) {
12238 DisplayMessage("", _("No moves in game"));
12239 if (cmailMsgLoaded) {
12240 if (appData.debugMode)
12241 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
12245 DrawPosition(FALSE, boards[currentMove]);
12246 DisplayBothClocks();
12247 gameMode = EditGame;
12254 // [HGM] PV info: routine tests if comment empty
12255 if (!matchMode && (pausing || appData.timeDelay != 0)) {
12256 DisplayComment(currentMove - 1, commentList[currentMove]);
12258 if (!matchMode && appData.timeDelay != 0)
12259 DrawPosition(FALSE, boards[currentMove]);
12261 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
12262 programStats.ok_to_send = 1;
12265 /* if the first token after the PGN tags is a move
12266 * and not move number 1, retrieve it from the parser
12268 if (cm != MoveNumberOne)
12269 LoadGameOneMove(cm);
12271 /* load the remaining moves from the file */
12272 while (LoadGameOneMove(EndOfFile)) {
12273 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
12274 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
12277 /* rewind to the start of the game */
12278 currentMove = backwardMostMove;
12280 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
12282 if (oldGameMode == AnalyzeFile ||
12283 oldGameMode == AnalyzeMode) {
12284 appData.loadGameIndex = -1; // [HGM] order auto-stepping through games
12286 AnalyzeFileEvent();
12290 if (!matchMode && pos > 0) {
12291 ToNrEvent(pos); // [HGM] no autoplay if selected on position
12293 if (matchMode || appData.timeDelay == 0) {
12295 } else if (appData.timeDelay > 0) {
12296 AutoPlayGameLoop();
12299 if (appData.debugMode)
12300 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
12302 loadFlag = 0; /* [HGM] true game starts */
12306 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
12308 ReloadPosition (int offset)
12310 int positionNumber = lastLoadPositionNumber + offset;
12311 if (lastLoadPositionFP == NULL) {
12312 DisplayError(_("No position has been loaded yet"), 0);
12315 if (positionNumber <= 0) {
12316 DisplayError(_("Can't back up any further"), 0);
12319 return LoadPosition(lastLoadPositionFP, positionNumber,
12320 lastLoadPositionTitle);
12323 /* Load the nth position from the given file */
12325 LoadPositionFromFile (char *filename, int n, char *title)
12330 if (strcmp(filename, "-") == 0) {
12331 return LoadPosition(stdin, n, "stdin");
12333 f = fopen(filename, "rb");
12335 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12336 DisplayError(buf, errno);
12339 return LoadPosition(f, n, title);
12344 /* Load the nth position from the given open file, and close it */
12346 LoadPosition (FILE *f, int positionNumber, char *title)
12348 char *p, line[MSG_SIZ];
12349 Board initial_position;
12350 int i, j, fenMode, pn;
12352 if (gameMode == Training )
12353 SetTrainingModeOff();
12355 if (gameMode != BeginningOfGame) {
12356 Reset(FALSE, TRUE);
12358 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
12359 fclose(lastLoadPositionFP);
12361 if (positionNumber == 0) positionNumber = 1;
12362 lastLoadPositionFP = f;
12363 lastLoadPositionNumber = positionNumber;
12364 safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
12365 if (first.pr == NoProc && !appData.noChessProgram) {
12366 StartChessProgram(&first);
12367 InitChessProgram(&first, FALSE);
12369 pn = positionNumber;
12370 if (positionNumber < 0) {
12371 /* Negative position number means to seek to that byte offset */
12372 if (fseek(f, -positionNumber, 0) == -1) {
12373 DisplayError(_("Can't seek on position file"), 0);
12378 if (fseek(f, 0, 0) == -1) {
12379 if (f == lastLoadPositionFP ?
12380 positionNumber == lastLoadPositionNumber + 1 :
12381 positionNumber == 1) {
12384 DisplayError(_("Can't seek on position file"), 0);
12389 /* See if this file is FEN or old-style xboard */
12390 if (fgets(line, MSG_SIZ, f) == NULL) {
12391 DisplayError(_("Position not found in file"), 0);
12394 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
12395 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
12398 if (fenMode || line[0] == '#') pn--;
12400 /* skip positions before number pn */
12401 if (fgets(line, MSG_SIZ, f) == NULL) {
12403 DisplayError(_("Position not found in file"), 0);
12406 if (fenMode || line[0] == '#') pn--;
12411 if (!ParseFEN(initial_position, &blackPlaysFirst, line)) {
12412 DisplayError(_("Bad FEN position in file"), 0);
12416 (void) fgets(line, MSG_SIZ, f);
12417 (void) fgets(line, MSG_SIZ, f);
12419 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
12420 (void) fgets(line, MSG_SIZ, f);
12421 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
12424 initial_position[i][j++] = CharToPiece(*p);
12428 blackPlaysFirst = FALSE;
12430 (void) fgets(line, MSG_SIZ, f);
12431 if (strncmp(line, "black", strlen("black"))==0)
12432 blackPlaysFirst = TRUE;
12435 startedFromSetupPosition = TRUE;
12437 CopyBoard(boards[0], initial_position);
12438 if (blackPlaysFirst) {
12439 currentMove = forwardMostMove = backwardMostMove = 1;
12440 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12441 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12442 CopyBoard(boards[1], initial_position);
12443 DisplayMessage("", _("Black to play"));
12445 currentMove = forwardMostMove = backwardMostMove = 0;
12446 DisplayMessage("", _("White to play"));
12448 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
12449 if(first.pr != NoProc) { // [HGM] in tourney-mode a position can be loaded before the chess engine is installed
12450 SendToProgram("force\n", &first);
12451 SendBoard(&first, forwardMostMove);
12453 if (appData.debugMode) {
12455 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
12456 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
12457 fprintf(debugFP, "Load Position\n");
12460 if (positionNumber > 1) {
12461 snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
12462 DisplayTitle(line);
12464 DisplayTitle(title);
12466 gameMode = EditGame;
12469 timeRemaining[0][1] = whiteTimeRemaining;
12470 timeRemaining[1][1] = blackTimeRemaining;
12471 DrawPosition(FALSE, boards[currentMove]);
12478 CopyPlayerNameIntoFileName (char **dest, char *src)
12480 while (*src != NULLCHAR && *src != ',') {
12485 *(*dest)++ = *src++;
12491 DefaultFileName (char *ext)
12493 static char def[MSG_SIZ];
12496 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
12498 CopyPlayerNameIntoFileName(&p, gameInfo.white);
12500 CopyPlayerNameIntoFileName(&p, gameInfo.black);
12502 safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
12509 /* Save the current game to the given file */
12511 SaveGameToFile (char *filename, int append)
12515 int result, i, t,tot=0;
12517 if (strcmp(filename, "-") == 0) {
12518 return SaveGame(stdout, 0, NULL);
12520 for(i=0; i<10; i++) { // upto 10 tries
12521 f = fopen(filename, append ? "a" : "w");
12522 if(f && i) fprintf(f, "[Delay \"%d retries, %d msec\"]\n",i,tot);
12523 if(f || errno != 13) break;
12524 DoSleep(t = 5 + random()%11); // wait 5-15 msec
12528 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12529 DisplayError(buf, errno);
12532 safeStrCpy(buf, lastMsg, MSG_SIZ);
12533 DisplayMessage(_("Waiting for access to save file"), "");
12534 flock(fileno(f), LOCK_EX); // [HGM] lock: lock file while we are writing
12535 DisplayMessage(_("Saving game"), "");
12536 if(lseek(fileno(f), 0, SEEK_END) == -1) DisplayError(_("Bad Seek"), errno); // better safe than sorry...
12537 result = SaveGame(f, 0, NULL);
12538 DisplayMessage(buf, "");
12545 SavePart (char *str)
12547 static char buf[MSG_SIZ];
12550 p = strchr(str, ' ');
12551 if (p == NULL) return str;
12552 strncpy(buf, str, p - str);
12553 buf[p - str] = NULLCHAR;
12557 #define PGN_MAX_LINE 75
12559 #define PGN_SIDE_WHITE 0
12560 #define PGN_SIDE_BLACK 1
12563 FindFirstMoveOutOfBook (int side)
12567 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
12568 int index = backwardMostMove;
12569 int has_book_hit = 0;
12571 if( (index % 2) != side ) {
12575 while( index < forwardMostMove ) {
12576 /* Check to see if engine is in book */
12577 int depth = pvInfoList[index].depth;
12578 int score = pvInfoList[index].score;
12584 else if( score == 0 && depth == 63 ) {
12585 in_book = 1; /* Zappa */
12587 else if( score == 2 && depth == 99 ) {
12588 in_book = 1; /* Abrok */
12591 has_book_hit += in_book;
12607 GetOutOfBookInfo (char * buf)
12611 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12613 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
12614 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
12618 if( oob[0] >= 0 || oob[1] >= 0 ) {
12619 for( i=0; i<2; i++ ) {
12623 if( i > 0 && oob[0] >= 0 ) {
12624 strcat( buf, " " );
12627 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
12628 sprintf( buf+strlen(buf), "%s%.2f",
12629 pvInfoList[idx].score >= 0 ? "+" : "",
12630 pvInfoList[idx].score / 100.0 );
12636 /* Save game in PGN style and close the file */
12638 SaveGamePGN (FILE *f)
12640 int i, offset, linelen, newblock;
12643 int movelen, numlen, blank;
12644 char move_buffer[100]; /* [AS] Buffer for move+PV info */
12646 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12648 PrintPGNTags(f, &gameInfo);
12650 if(appData.numberTag && matchMode) fprintf(f, "[Number \"%d\"]\n", nextGame+1); // [HGM] number tag
12652 if (backwardMostMove > 0 || startedFromSetupPosition) {
12653 char *fen = PositionToFEN(backwardMostMove, NULL);
12654 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
12655 fprintf(f, "\n{--------------\n");
12656 PrintPosition(f, backwardMostMove);
12657 fprintf(f, "--------------}\n");
12661 /* [AS] Out of book annotation */
12662 if( appData.saveOutOfBookInfo ) {
12665 GetOutOfBookInfo( buf );
12667 if( buf[0] != '\0' ) {
12668 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
12675 i = backwardMostMove;
12679 while (i < forwardMostMove) {
12680 /* Print comments preceding this move */
12681 if (commentList[i] != NULL) {
12682 if (linelen > 0) fprintf(f, "\n");
12683 fprintf(f, "%s", commentList[i]);
12688 /* Format move number */
12690 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
12693 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
12695 numtext[0] = NULLCHAR;
12697 numlen = strlen(numtext);
12700 /* Print move number */
12701 blank = linelen > 0 && numlen > 0;
12702 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
12711 fprintf(f, "%s", numtext);
12715 safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
12716 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
12719 blank = linelen > 0 && movelen > 0;
12720 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
12729 fprintf(f, "%s", move_buffer);
12730 linelen += movelen;
12732 /* [AS] Add PV info if present */
12733 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
12734 /* [HGM] add time */
12735 char buf[MSG_SIZ]; int seconds;
12737 seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
12743 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
12746 seconds = (seconds + 4)/10; // round to full seconds
12748 snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
12750 snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
12753 snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
12754 pvInfoList[i].score >= 0 ? "+" : "",
12755 pvInfoList[i].score / 100.0,
12756 pvInfoList[i].depth,
12759 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
12761 /* Print score/depth */
12762 blank = linelen > 0 && movelen > 0;
12763 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
12772 fprintf(f, "%s", move_buffer);
12773 linelen += movelen;
12779 /* Start a new line */
12780 if (linelen > 0) fprintf(f, "\n");
12782 /* Print comments after last move */
12783 if (commentList[i] != NULL) {
12784 fprintf(f, "%s\n", commentList[i]);
12788 if (gameInfo.resultDetails != NULL &&
12789 gameInfo.resultDetails[0] != NULLCHAR) {
12790 fprintf(f, "{%s} %s\n\n", gameInfo.resultDetails,
12791 PGNResult(gameInfo.result));
12793 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
12797 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
12801 /* Save game in old style and close the file */
12803 SaveGameOldStyle (FILE *f)
12808 tm = time((time_t *) NULL);
12810 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
12813 if (backwardMostMove > 0 || startedFromSetupPosition) {
12814 fprintf(f, "\n[--------------\n");
12815 PrintPosition(f, backwardMostMove);
12816 fprintf(f, "--------------]\n");
12821 i = backwardMostMove;
12822 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
12824 while (i < forwardMostMove) {
12825 if (commentList[i] != NULL) {
12826 fprintf(f, "[%s]\n", commentList[i]);
12829 if ((i % 2) == 1) {
12830 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
12833 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
12835 if (commentList[i] != NULL) {
12839 if (i >= forwardMostMove) {
12843 fprintf(f, "%s\n", parseList[i]);
12848 if (commentList[i] != NULL) {
12849 fprintf(f, "[%s]\n", commentList[i]);
12852 /* This isn't really the old style, but it's close enough */
12853 if (gameInfo.resultDetails != NULL &&
12854 gameInfo.resultDetails[0] != NULLCHAR) {
12855 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
12856 gameInfo.resultDetails);
12858 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
12865 /* Save the current game to open file f and close the file */
12867 SaveGame (FILE *f, int dummy, char *dummy2)
12869 if (gameMode == EditPosition) EditPositionDone(TRUE);
12870 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
12871 if (appData.oldSaveStyle)
12872 return SaveGameOldStyle(f);
12874 return SaveGamePGN(f);
12877 /* Save the current position to the given file */
12879 SavePositionToFile (char *filename)
12884 if (strcmp(filename, "-") == 0) {
12885 return SavePosition(stdout, 0, NULL);
12887 f = fopen(filename, "a");
12889 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12890 DisplayError(buf, errno);
12893 safeStrCpy(buf, lastMsg, MSG_SIZ);
12894 DisplayMessage(_("Waiting for access to save file"), "");
12895 flock(fileno(f), LOCK_EX); // [HGM] lock
12896 DisplayMessage(_("Saving position"), "");
12897 lseek(fileno(f), 0, SEEK_END); // better safe than sorry...
12898 SavePosition(f, 0, NULL);
12899 DisplayMessage(buf, "");
12905 /* Save the current position to the given open file and close the file */
12907 SavePosition (FILE *f, int dummy, char *dummy2)
12912 if (gameMode == EditPosition) EditPositionDone(TRUE);
12913 if (appData.oldSaveStyle) {
12914 tm = time((time_t *) NULL);
12916 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
12918 fprintf(f, "[--------------\n");
12919 PrintPosition(f, currentMove);
12920 fprintf(f, "--------------]\n");
12922 fen = PositionToFEN(currentMove, NULL);
12923 fprintf(f, "%s\n", fen);
12931 ReloadCmailMsgEvent (int unregister)
12934 static char *inFilename = NULL;
12935 static char *outFilename;
12937 struct stat inbuf, outbuf;
12940 /* Any registered moves are unregistered if unregister is set, */
12941 /* i.e. invoked by the signal handler */
12943 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
12944 cmailMoveRegistered[i] = FALSE;
12945 if (cmailCommentList[i] != NULL) {
12946 free(cmailCommentList[i]);
12947 cmailCommentList[i] = NULL;
12950 nCmailMovesRegistered = 0;
12953 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
12954 cmailResult[i] = CMAIL_NOT_RESULT;
12958 if (inFilename == NULL) {
12959 /* Because the filenames are static they only get malloced once */
12960 /* and they never get freed */
12961 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
12962 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
12964 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
12965 sprintf(outFilename, "%s.out", appData.cmailGameName);
12968 status = stat(outFilename, &outbuf);
12970 cmailMailedMove = FALSE;
12972 status = stat(inFilename, &inbuf);
12973 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
12976 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
12977 counts the games, notes how each one terminated, etc.
12979 It would be nice to remove this kludge and instead gather all
12980 the information while building the game list. (And to keep it
12981 in the game list nodes instead of having a bunch of fixed-size
12982 parallel arrays.) Note this will require getting each game's
12983 termination from the PGN tags, as the game list builder does
12984 not process the game moves. --mann
12986 cmailMsgLoaded = TRUE;
12987 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
12989 /* Load first game in the file or popup game menu */
12990 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
12992 #endif /* !WIN32 */
13000 char string[MSG_SIZ];
13002 if ( cmailMailedMove
13003 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
13004 return TRUE; /* Allow free viewing */
13007 /* Unregister move to ensure that we don't leave RegisterMove */
13008 /* with the move registered when the conditions for registering no */
13010 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
13011 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
13012 nCmailMovesRegistered --;
13014 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
13016 free(cmailCommentList[lastLoadGameNumber - 1]);
13017 cmailCommentList[lastLoadGameNumber - 1] = NULL;
13021 if (cmailOldMove == -1) {
13022 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
13026 if (currentMove > cmailOldMove + 1) {
13027 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
13031 if (currentMove < cmailOldMove) {
13032 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
13036 if (forwardMostMove > currentMove) {
13037 /* Silently truncate extra moves */
13041 if ( (currentMove == cmailOldMove + 1)
13042 || ( (currentMove == cmailOldMove)
13043 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
13044 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
13045 if (gameInfo.result != GameUnfinished) {
13046 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
13049 if (commentList[currentMove] != NULL) {
13050 cmailCommentList[lastLoadGameNumber - 1]
13051 = StrSave(commentList[currentMove]);
13053 safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
13055 if (appData.debugMode)
13056 fprintf(debugFP, "Saving %s for game %d\n",
13057 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
13059 snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
13061 f = fopen(string, "w");
13062 if (appData.oldSaveStyle) {
13063 SaveGameOldStyle(f); /* also closes the file */
13065 snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
13066 f = fopen(string, "w");
13067 SavePosition(f, 0, NULL); /* also closes the file */
13069 fprintf(f, "{--------------\n");
13070 PrintPosition(f, currentMove);
13071 fprintf(f, "--------------}\n\n");
13073 SaveGame(f, 0, NULL); /* also closes the file*/
13076 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
13077 nCmailMovesRegistered ++;
13078 } else if (nCmailGames == 1) {
13079 DisplayError(_("You have not made a move yet"), 0);
13090 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
13091 FILE *commandOutput;
13092 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
13093 int nBytes = 0; /* Suppress warnings on uninitialized variables */
13099 if (! cmailMsgLoaded) {
13100 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
13104 if (nCmailGames == nCmailResults) {
13105 DisplayError(_("No unfinished games"), 0);
13109 #if CMAIL_PROHIBIT_REMAIL
13110 if (cmailMailedMove) {
13111 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);
13112 DisplayError(msg, 0);
13117 if (! (cmailMailedMove || RegisterMove())) return;
13119 if ( cmailMailedMove
13120 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
13121 snprintf(string, MSG_SIZ, partCommandString,
13122 appData.debugMode ? " -v" : "", appData.cmailGameName);
13123 commandOutput = popen(string, "r");
13125 if (commandOutput == NULL) {
13126 DisplayError(_("Failed to invoke cmail"), 0);
13128 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
13129 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
13131 if (nBuffers > 1) {
13132 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
13133 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
13134 nBytes = MSG_SIZ - 1;
13136 (void) memcpy(msg, buffer, nBytes);
13138 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
13140 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
13141 cmailMailedMove = TRUE; /* Prevent >1 moves */
13144 for (i = 0; i < nCmailGames; i ++) {
13145 if (cmailResult[i] == CMAIL_NOT_RESULT) {
13150 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
13152 snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
13154 appData.cmailGameName,
13156 LoadGameFromFile(buffer, 1, buffer, FALSE);
13157 cmailMsgLoaded = FALSE;
13161 DisplayInformation(msg);
13162 pclose(commandOutput);
13165 if ((*cmailMsg) != '\0') {
13166 DisplayInformation(cmailMsg);
13171 #endif /* !WIN32 */
13180 int prependComma = 0;
13182 char string[MSG_SIZ]; /* Space for game-list */
13185 if (!cmailMsgLoaded) return "";
13187 if (cmailMailedMove) {
13188 snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
13190 /* Create a list of games left */
13191 snprintf(string, MSG_SIZ, "[");
13192 for (i = 0; i < nCmailGames; i ++) {
13193 if (! ( cmailMoveRegistered[i]
13194 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
13195 if (prependComma) {
13196 snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
13198 snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
13202 strcat(string, number);
13205 strcat(string, "]");
13207 if (nCmailMovesRegistered + nCmailResults == 0) {
13208 switch (nCmailGames) {
13210 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
13214 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
13218 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
13223 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
13225 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
13230 if (nCmailResults == nCmailGames) {
13231 snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
13233 snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
13238 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
13250 if (gameMode == Training)
13251 SetTrainingModeOff();
13254 cmailMsgLoaded = FALSE;
13255 if (appData.icsActive) {
13256 SendToICS(ics_prefix);
13257 SendToICS("refresh\n");
13262 ExitEvent (int status)
13266 /* Give up on clean exit */
13270 /* Keep trying for clean exit */
13274 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
13276 if (telnetISR != NULL) {
13277 RemoveInputSource(telnetISR);
13279 if (icsPR != NoProc) {
13280 DestroyChildProcess(icsPR, TRUE);
13283 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
13284 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
13286 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
13287 /* make sure this other one finishes before killing it! */
13288 if(endingGame) { int count = 0;
13289 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
13290 while(endingGame && count++ < 10) DoSleep(1);
13291 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
13294 /* Kill off chess programs */
13295 if (first.pr != NoProc) {
13298 DoSleep( appData.delayBeforeQuit );
13299 SendToProgram("quit\n", &first);
13300 DoSleep( appData.delayAfterQuit );
13301 DestroyChildProcess(first.pr, 10 /* [AS] first.useSigterm */ );
13303 if (second.pr != NoProc) {
13304 DoSleep( appData.delayBeforeQuit );
13305 SendToProgram("quit\n", &second);
13306 DoSleep( appData.delayAfterQuit );
13307 DestroyChildProcess(second.pr, 10 /* [AS] second.useSigterm */ );
13309 if (first.isr != NULL) {
13310 RemoveInputSource(first.isr);
13312 if (second.isr != NULL) {
13313 RemoveInputSource(second.isr);
13316 if (pairing.pr != NoProc) SendToProgram("quit\n", &pairing);
13317 if (pairing.isr != NULL) RemoveInputSource(pairing.isr);
13319 ShutDownFrontEnd();
13326 if (appData.debugMode)
13327 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
13331 if (gameMode == MachinePlaysWhite ||
13332 gameMode == MachinePlaysBlack) {
13335 DisplayBothClocks();
13337 if (gameMode == PlayFromGameFile) {
13338 if (appData.timeDelay >= 0)
13339 AutoPlayGameLoop();
13340 } else if (gameMode == IcsExamining && pauseExamInvalid) {
13341 Reset(FALSE, TRUE);
13342 SendToICS(ics_prefix);
13343 SendToICS("refresh\n");
13344 } else if (currentMove < forwardMostMove) {
13345 ForwardInner(forwardMostMove);
13347 pauseExamInvalid = FALSE;
13349 switch (gameMode) {
13353 pauseExamForwardMostMove = forwardMostMove;
13354 pauseExamInvalid = FALSE;
13357 case IcsPlayingWhite:
13358 case IcsPlayingBlack:
13362 case PlayFromGameFile:
13363 (void) StopLoadGameTimer();
13367 case BeginningOfGame:
13368 if (appData.icsActive) return;
13369 /* else fall through */
13370 case MachinePlaysWhite:
13371 case MachinePlaysBlack:
13372 case TwoMachinesPlay:
13373 if (forwardMostMove == 0)
13374 return; /* don't pause if no one has moved */
13375 if ((gameMode == MachinePlaysWhite &&
13376 !WhiteOnMove(forwardMostMove)) ||
13377 (gameMode == MachinePlaysBlack &&
13378 WhiteOnMove(forwardMostMove))) {
13389 EditCommentEvent ()
13391 char title[MSG_SIZ];
13393 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
13394 safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
13396 snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
13397 WhiteOnMove(currentMove - 1) ? " " : ".. ",
13398 parseList[currentMove - 1]);
13401 EditCommentPopUp(currentMove, title, commentList[currentMove]);
13408 char *tags = PGNTags(&gameInfo);
13410 EditTagsPopUp(tags, NULL);
13417 if(second.analyzing) {
13418 SendToProgram("exit\n", &second);
13419 second.analyzing = FALSE;
13421 if (second.pr == NoProc) StartChessProgram(&second);
13422 InitChessProgram(&second, FALSE);
13423 FeedMovesToProgram(&second, currentMove);
13425 SendToProgram("analyze\n", &second);
13426 second.analyzing = TRUE;
13431 AnalyzeModeEvent ()
13433 if (gameMode == AnalyzeMode) { ToggleSecond(); return; }
13434 if (appData.noChessProgram || gameMode == AnalyzeMode)
13437 if (gameMode != AnalyzeFile) {
13438 if (!appData.icsEngineAnalyze) {
13440 if (gameMode != EditGame) return;
13442 ResurrectChessProgram();
13443 SendToProgram("analyze\n", &first);
13444 first.analyzing = TRUE;
13445 /*first.maybeThinking = TRUE;*/
13446 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13447 EngineOutputPopUp();
13449 if (!appData.icsEngineAnalyze) gameMode = AnalyzeMode;
13454 StartAnalysisClock();
13455 GetTimeMark(&lastNodeCountTime);
13460 AnalyzeFileEvent ()
13462 if (appData.noChessProgram || gameMode == AnalyzeFile)
13465 if (gameMode != AnalyzeMode) {
13467 if (gameMode != EditGame) return;
13468 ResurrectChessProgram();
13469 SendToProgram("analyze\n", &first);
13470 first.analyzing = TRUE;
13471 /*first.maybeThinking = TRUE;*/
13472 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
13473 EngineOutputPopUp();
13475 gameMode = AnalyzeFile;
13480 StartAnalysisClock();
13481 GetTimeMark(&lastNodeCountTime);
13483 if(appData.timeDelay > 0) StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
13487 MachineWhiteEvent ()
13490 char *bookHit = NULL;
13492 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
13496 if (gameMode == PlayFromGameFile ||
13497 gameMode == TwoMachinesPlay ||
13498 gameMode == Training ||
13499 gameMode == AnalyzeMode ||
13500 gameMode == EndOfGame)
13503 if (gameMode == EditPosition)
13504 EditPositionDone(TRUE);
13506 if (!WhiteOnMove(currentMove)) {
13507 DisplayError(_("It is not White's turn"), 0);
13511 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
13514 if (gameMode == EditGame || gameMode == AnalyzeMode ||
13515 gameMode == AnalyzeFile)
13518 ResurrectChessProgram(); /* in case it isn't running */
13519 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
13520 gameMode = MachinePlaysWhite;
13523 gameMode = MachinePlaysWhite;
13527 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
13529 if (first.sendName) {
13530 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
13531 SendToProgram(buf, &first);
13533 if (first.sendTime) {
13534 if (first.useColors) {
13535 SendToProgram("black\n", &first); /*gnu kludge*/
13537 SendTimeRemaining(&first, TRUE);
13539 if (first.useColors) {
13540 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
13542 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
13543 SetMachineThinkingEnables();
13544 first.maybeThinking = TRUE;
13548 if (appData.autoFlipView && !flipView) {
13549 flipView = !flipView;
13550 DrawPosition(FALSE, NULL);
13551 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
13554 if(bookHit) { // [HGM] book: simulate book reply
13555 static char bookMove[MSG_SIZ]; // a bit generous?
13557 programStats.nodes = programStats.depth = programStats.time =
13558 programStats.score = programStats.got_only_move = 0;
13559 sprintf(programStats.movelist, "%s (xbook)", bookHit);
13561 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
13562 strcat(bookMove, bookHit);
13563 HandleMachineMove(bookMove, &first);
13568 MachineBlackEvent ()
13571 char *bookHit = NULL;
13573 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
13577 if (gameMode == PlayFromGameFile ||
13578 gameMode == TwoMachinesPlay ||
13579 gameMode == Training ||
13580 gameMode == AnalyzeMode ||
13581 gameMode == EndOfGame)
13584 if (gameMode == EditPosition)
13585 EditPositionDone(TRUE);
13587 if (WhiteOnMove(currentMove)) {
13588 DisplayError(_("It is not Black's turn"), 0);
13592 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
13595 if (gameMode == EditGame || gameMode == AnalyzeMode ||
13596 gameMode == AnalyzeFile)
13599 ResurrectChessProgram(); /* in case it isn't running */
13600 gameMode = MachinePlaysBlack;
13604 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
13606 if (first.sendName) {
13607 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
13608 SendToProgram(buf, &first);
13610 if (first.sendTime) {
13611 if (first.useColors) {
13612 SendToProgram("white\n", &first); /*gnu kludge*/
13614 SendTimeRemaining(&first, FALSE);
13616 if (first.useColors) {
13617 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
13619 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
13620 SetMachineThinkingEnables();
13621 first.maybeThinking = TRUE;
13624 if (appData.autoFlipView && flipView) {
13625 flipView = !flipView;
13626 DrawPosition(FALSE, NULL);
13627 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
13629 if(bookHit) { // [HGM] book: simulate book reply
13630 static char bookMove[MSG_SIZ]; // a bit generous?
13632 programStats.nodes = programStats.depth = programStats.time =
13633 programStats.score = programStats.got_only_move = 0;
13634 sprintf(programStats.movelist, "%s (xbook)", bookHit);
13636 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
13637 strcat(bookMove, bookHit);
13638 HandleMachineMove(bookMove, &first);
13644 DisplayTwoMachinesTitle ()
13647 if (appData.matchGames > 0) {
13648 if(appData.tourneyFile[0]) {
13649 snprintf(buf, MSG_SIZ, "%s %s %s (%d/%d%s)",
13650 gameInfo.white, _("vs."), gameInfo.black,
13651 nextGame+1, appData.matchGames+1,
13652 appData.tourneyType>0 ? "gt" : appData.tourneyType<0 ? "sw" : "rr");
13654 if (first.twoMachinesColor[0] == 'w') {
13655 snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
13656 gameInfo.white, _("vs."), gameInfo.black,
13657 first.matchWins, second.matchWins,
13658 matchGame - 1 - (first.matchWins + second.matchWins));
13660 snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
13661 gameInfo.white, _("vs."), gameInfo.black,
13662 second.matchWins, first.matchWins,
13663 matchGame - 1 - (first.matchWins + second.matchWins));
13666 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
13672 SettingsMenuIfReady ()
13674 if (second.lastPing != second.lastPong) {
13675 DisplayMessage("", _("Waiting for second chess program"));
13676 ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
13680 DisplayMessage("", "");
13681 SettingsPopUp(&second);
13685 WaitForEngine (ChessProgramState *cps, DelayedEventCallback retry)
13688 if (cps->pr == NoProc) {
13689 StartChessProgram(cps);
13690 if (cps->protocolVersion == 1) {
13693 /* kludge: allow timeout for initial "feature" command */
13695 snprintf(buf, MSG_SIZ, _("Starting %s chess program"), _(cps->which));
13696 DisplayMessage("", buf);
13697 ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
13705 TwoMachinesEvent P((void))
13709 ChessProgramState *onmove;
13710 char *bookHit = NULL;
13711 static int stalling = 0;
13715 if (appData.noChessProgram) return;
13717 switch (gameMode) {
13718 case TwoMachinesPlay:
13720 case MachinePlaysWhite:
13721 case MachinePlaysBlack:
13722 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
13723 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
13727 case BeginningOfGame:
13728 case PlayFromGameFile:
13731 if (gameMode != EditGame) return;
13734 EditPositionDone(TRUE);
13745 // forwardMostMove = currentMove;
13746 TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
13748 if(!ResurrectChessProgram()) return; /* in case first program isn't running (unbalances its ping due to InitChessProgram!) */
13750 if(WaitForEngine(&second, TwoMachinesEventIfReady)) return; // (if needed:) started up second engine, so wait for features
13751 if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
13752 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
13756 if(second.protocolVersion >= 2 && !strstr(second.variants, VariantName(gameInfo.variant))) {
13757 DisplayError("second engine does not play this", 0);
13762 InitChessProgram(&second, FALSE); // unbalances ping of second engine
13763 SendToProgram("force\n", &second);
13765 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
13768 GetTimeMark(&now); // [HGM] matchpause: implement match pause after engine load
13769 if(appData.matchPause>10000 || appData.matchPause<10)
13770 appData.matchPause = 10000; /* [HGM] make pause adjustable */
13771 wait = SubtractTimeMarks(&now, &pauseStart);
13772 if(wait < appData.matchPause) {
13773 ScheduleDelayedEvent(TwoMachinesEventIfReady, appData.matchPause - wait);
13776 // we are now committed to starting the game
13778 DisplayMessage("", "");
13779 if (startedFromSetupPosition) {
13780 SendBoard(&second, backwardMostMove);
13781 if (appData.debugMode) {
13782 fprintf(debugFP, "Two Machines\n");
13785 for (i = backwardMostMove; i < forwardMostMove; i++) {
13786 SendMoveToProgram(i, &second);
13789 gameMode = TwoMachinesPlay;
13791 ModeHighlight(); // [HGM] logo: this triggers display update of logos
13793 DisplayTwoMachinesTitle();
13795 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
13800 if(appData.debugMode) fprintf(debugFP, "New game (%d): %s-%s (%c)\n", matchGame, first.tidy, second.tidy, first.twoMachinesColor[0]);
13801 SendToProgram(first.computerString, &first);
13802 if (first.sendName) {
13803 snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
13804 SendToProgram(buf, &first);
13806 SendToProgram(second.computerString, &second);
13807 if (second.sendName) {
13808 snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
13809 SendToProgram(buf, &second);
13813 if (!first.sendTime || !second.sendTime) {
13814 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
13815 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
13817 if (onmove->sendTime) {
13818 if (onmove->useColors) {
13819 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
13821 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
13823 if (onmove->useColors) {
13824 SendToProgram(onmove->twoMachinesColor, onmove);
13826 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
13827 // SendToProgram("go\n", onmove);
13828 onmove->maybeThinking = TRUE;
13829 SetMachineThinkingEnables();
13833 if(bookHit) { // [HGM] book: simulate book reply
13834 static char bookMove[MSG_SIZ]; // a bit generous?
13836 programStats.nodes = programStats.depth = programStats.time =
13837 programStats.score = programStats.got_only_move = 0;
13838 sprintf(programStats.movelist, "%s (xbook)", bookHit);
13840 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
13841 strcat(bookMove, bookHit);
13842 savedMessage = bookMove; // args for deferred call
13843 savedState = onmove;
13844 ScheduleDelayedEvent(DeferredBookMove, 1);
13851 if (gameMode == Training) {
13852 SetTrainingModeOff();
13853 gameMode = PlayFromGameFile;
13854 DisplayMessage("", _("Training mode off"));
13856 gameMode = Training;
13857 animateTraining = appData.animate;
13859 /* make sure we are not already at the end of the game */
13860 if (currentMove < forwardMostMove) {
13861 SetTrainingModeOn();
13862 DisplayMessage("", _("Training mode on"));
13864 gameMode = PlayFromGameFile;
13865 DisplayError(_("Already at end of game"), 0);
13874 if (!appData.icsActive) return;
13875 switch (gameMode) {
13876 case IcsPlayingWhite:
13877 case IcsPlayingBlack:
13880 case BeginningOfGame:
13888 EditPositionDone(TRUE);
13901 gameMode = IcsIdle;
13911 switch (gameMode) {
13913 SetTrainingModeOff();
13915 case MachinePlaysWhite:
13916 case MachinePlaysBlack:
13917 case BeginningOfGame:
13918 SendToProgram("force\n", &first);
13919 SetUserThinkingEnables();
13921 case PlayFromGameFile:
13922 (void) StopLoadGameTimer();
13923 if (gameFileFP != NULL) {
13928 EditPositionDone(TRUE);
13933 SendToProgram("force\n", &first);
13935 case TwoMachinesPlay:
13936 GameEnds(EndOfFile, NULL, GE_PLAYER);
13937 ResurrectChessProgram();
13938 SetUserThinkingEnables();
13941 ResurrectChessProgram();
13943 case IcsPlayingBlack:
13944 case IcsPlayingWhite:
13945 DisplayError(_("Warning: You are still playing a game"), 0);
13948 DisplayError(_("Warning: You are still observing a game"), 0);
13951 DisplayError(_("Warning: You are still examining a game"), 0);
13962 first.offeredDraw = second.offeredDraw = 0;
13964 if (gameMode == PlayFromGameFile) {
13965 whiteTimeRemaining = timeRemaining[0][currentMove];
13966 blackTimeRemaining = timeRemaining[1][currentMove];
13970 if (gameMode == MachinePlaysWhite ||
13971 gameMode == MachinePlaysBlack ||
13972 gameMode == TwoMachinesPlay ||
13973 gameMode == EndOfGame) {
13974 i = forwardMostMove;
13975 while (i > currentMove) {
13976 SendToProgram("undo\n", &first);
13979 if(!adjustedClock) {
13980 whiteTimeRemaining = timeRemaining[0][currentMove];
13981 blackTimeRemaining = timeRemaining[1][currentMove];
13982 DisplayBothClocks();
13984 if (whiteFlag || blackFlag) {
13985 whiteFlag = blackFlag = 0;
13990 gameMode = EditGame;
13997 EditPositionEvent ()
13999 if (gameMode == EditPosition) {
14005 if (gameMode != EditGame) return;
14007 gameMode = EditPosition;
14010 if (currentMove > 0)
14011 CopyBoard(boards[0], boards[currentMove]);
14013 blackPlaysFirst = !WhiteOnMove(currentMove);
14015 currentMove = forwardMostMove = backwardMostMove = 0;
14016 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
14018 if(!appData.pieceMenu) DisplayMessage(_("Click clock to clear board"), "");
14024 /* [DM] icsEngineAnalyze - possible call from other functions */
14025 if (appData.icsEngineAnalyze) {
14026 appData.icsEngineAnalyze = FALSE;
14028 DisplayMessage("",_("Close ICS engine analyze..."));
14030 if (first.analysisSupport && first.analyzing) {
14031 SendToBoth("exit\n");
14032 first.analyzing = second.analyzing = FALSE;
14034 thinkOutput[0] = NULLCHAR;
14038 EditPositionDone (Boolean fakeRights)
14040 int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
14042 startedFromSetupPosition = TRUE;
14043 InitChessProgram(&first, FALSE);
14044 if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
14045 boards[0][EP_STATUS] = EP_NONE;
14046 boards[0][CASTLING][2] = boards[0][CASTLING][5] = BOARD_WIDTH>>1;
14047 if(boards[0][0][BOARD_WIDTH>>1] == king) {
14048 boards[0][CASTLING][1] = boards[0][0][BOARD_LEFT] == WhiteRook ? BOARD_LEFT : NoRights;
14049 boards[0][CASTLING][0] = boards[0][0][BOARD_RGHT-1] == WhiteRook ? BOARD_RGHT-1 : NoRights;
14050 } else boards[0][CASTLING][2] = NoRights;
14051 if(boards[0][BOARD_HEIGHT-1][BOARD_WIDTH>>1] == WHITE_TO_BLACK king) {
14052 boards[0][CASTLING][4] = boards[0][BOARD_HEIGHT-1][BOARD_LEFT] == BlackRook ? BOARD_LEFT : NoRights;
14053 boards[0][CASTLING][3] = boards[0][BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook ? BOARD_RGHT-1 : NoRights;
14054 } else boards[0][CASTLING][5] = NoRights;
14055 if(gameInfo.variant == VariantSChess) {
14057 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // pieces in their original position are assumed virgin
14058 boards[0][VIRGIN][i] = 0;
14059 if(boards[0][0][i] == FIDEArray[0][i-BOARD_LEFT]) boards[0][VIRGIN][i] |= VIRGIN_W;
14060 if(boards[0][BOARD_HEIGHT-1][i] == FIDEArray[1][i-BOARD_LEFT]) boards[0][VIRGIN][i] |= VIRGIN_B;
14064 SendToProgram("force\n", &first);
14065 if (blackPlaysFirst) {
14066 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
14067 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
14068 currentMove = forwardMostMove = backwardMostMove = 1;
14069 CopyBoard(boards[1], boards[0]);
14071 currentMove = forwardMostMove = backwardMostMove = 0;
14073 SendBoard(&first, forwardMostMove);
14074 if (appData.debugMode) {
14075 fprintf(debugFP, "EditPosDone\n");
14078 DisplayMessage("", "");
14079 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
14080 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
14081 gameMode = EditGame;
14083 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
14084 ClearHighlights(); /* [AS] */
14087 /* Pause for `ms' milliseconds */
14088 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
14090 TimeDelay (long ms)
14097 } while (SubtractTimeMarks(&m2, &m1) < ms);
14100 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
14102 SendMultiLineToICS (char *buf)
14104 char temp[MSG_SIZ+1], *p;
14111 strncpy(temp, buf, len);
14116 if (*p == '\n' || *p == '\r')
14121 strcat(temp, "\n");
14123 SendToPlayer(temp, strlen(temp));
14127 SetWhiteToPlayEvent ()
14129 if (gameMode == EditPosition) {
14130 blackPlaysFirst = FALSE;
14131 DisplayBothClocks(); /* works because currentMove is 0 */
14132 } else if (gameMode == IcsExamining) {
14133 SendToICS(ics_prefix);
14134 SendToICS("tomove white\n");
14139 SetBlackToPlayEvent ()
14141 if (gameMode == EditPosition) {
14142 blackPlaysFirst = TRUE;
14143 currentMove = 1; /* kludge */
14144 DisplayBothClocks();
14146 } else if (gameMode == IcsExamining) {
14147 SendToICS(ics_prefix);
14148 SendToICS("tomove black\n");
14153 EditPositionMenuEvent (ChessSquare selection, int x, int y)
14156 ChessSquare piece = boards[0][y][x];
14158 if (gameMode != EditPosition && gameMode != IcsExamining) return;
14160 switch (selection) {
14162 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
14163 SendToICS(ics_prefix);
14164 SendToICS("bsetup clear\n");
14165 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
14166 SendToICS(ics_prefix);
14167 SendToICS("clearboard\n");
14169 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
14170 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
14171 for (y = 0; y < BOARD_HEIGHT; y++) {
14172 if (gameMode == IcsExamining) {
14173 if (boards[currentMove][y][x] != EmptySquare) {
14174 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
14179 boards[0][y][x] = p;
14184 if (gameMode == EditPosition) {
14185 DrawPosition(FALSE, boards[0]);
14190 SetWhiteToPlayEvent();
14194 SetBlackToPlayEvent();
14198 if (gameMode == IcsExamining) {
14199 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
14200 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
14203 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
14204 if(x == BOARD_LEFT-2) {
14205 if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
14206 boards[0][y][1] = 0;
14208 if(x == BOARD_RGHT+1) {
14209 if(y >= gameInfo.holdingsSize) break;
14210 boards[0][y][BOARD_WIDTH-2] = 0;
14213 boards[0][y][x] = EmptySquare;
14214 DrawPosition(FALSE, boards[0]);
14219 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
14220 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
14221 selection = (ChessSquare) (PROMOTED piece);
14222 } else if(piece == EmptySquare) selection = WhiteSilver;
14223 else selection = (ChessSquare)((int)piece - 1);
14227 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
14228 piece > (int)BlackMan && piece <= (int)BlackKing ) {
14229 selection = (ChessSquare) (DEMOTED piece);
14230 } else if(piece == EmptySquare) selection = BlackSilver;
14231 else selection = (ChessSquare)((int)piece + 1);
14236 if(gameInfo.variant == VariantShatranj ||
14237 gameInfo.variant == VariantXiangqi ||
14238 gameInfo.variant == VariantCourier ||
14239 gameInfo.variant == VariantMakruk )
14240 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
14245 if(gameInfo.variant == VariantXiangqi)
14246 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
14247 if(gameInfo.variant == VariantKnightmate)
14248 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
14251 if (gameMode == IcsExamining) {
14252 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
14253 snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
14254 PieceToChar(selection), AAA + x, ONE + y);
14257 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
14259 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
14260 n = PieceToNumber(selection - BlackPawn);
14261 if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
14262 boards[0][BOARD_HEIGHT-1-n][0] = selection;
14263 boards[0][BOARD_HEIGHT-1-n][1]++;
14265 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
14266 n = PieceToNumber(selection);
14267 if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
14268 boards[0][n][BOARD_WIDTH-1] = selection;
14269 boards[0][n][BOARD_WIDTH-2]++;
14272 boards[0][y][x] = selection;
14273 DrawPosition(TRUE, boards[0]);
14275 fromX = fromY = -1;
14283 DropMenuEvent (ChessSquare selection, int x, int y)
14285 ChessMove moveType;
14287 switch (gameMode) {
14288 case IcsPlayingWhite:
14289 case MachinePlaysBlack:
14290 if (!WhiteOnMove(currentMove)) {
14291 DisplayMoveError(_("It is Black's turn"));
14294 moveType = WhiteDrop;
14296 case IcsPlayingBlack:
14297 case MachinePlaysWhite:
14298 if (WhiteOnMove(currentMove)) {
14299 DisplayMoveError(_("It is White's turn"));
14302 moveType = BlackDrop;
14305 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
14311 if (moveType == BlackDrop && selection < BlackPawn) {
14312 selection = (ChessSquare) ((int) selection
14313 + (int) BlackPawn - (int) WhitePawn);
14315 if (boards[currentMove][y][x] != EmptySquare) {
14316 DisplayMoveError(_("That square is occupied"));
14320 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
14326 /* Accept a pending offer of any kind from opponent */
14328 if (appData.icsActive) {
14329 SendToICS(ics_prefix);
14330 SendToICS("accept\n");
14331 } else if (cmailMsgLoaded) {
14332 if (currentMove == cmailOldMove &&
14333 commentList[cmailOldMove] != NULL &&
14334 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
14335 "Black offers a draw" : "White offers a draw")) {
14337 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
14338 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
14340 DisplayError(_("There is no pending offer on this move"), 0);
14341 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
14344 /* Not used for offers from chess program */
14351 /* Decline a pending offer of any kind from opponent */
14353 if (appData.icsActive) {
14354 SendToICS(ics_prefix);
14355 SendToICS("decline\n");
14356 } else if (cmailMsgLoaded) {
14357 if (currentMove == cmailOldMove &&
14358 commentList[cmailOldMove] != NULL &&
14359 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
14360 "Black offers a draw" : "White offers a draw")) {
14362 AppendComment(cmailOldMove, "Draw declined", TRUE);
14363 DisplayComment(cmailOldMove - 1, "Draw declined");
14366 DisplayError(_("There is no pending offer on this move"), 0);
14369 /* Not used for offers from chess program */
14376 /* Issue ICS rematch command */
14377 if (appData.icsActive) {
14378 SendToICS(ics_prefix);
14379 SendToICS("rematch\n");
14386 /* Call your opponent's flag (claim a win on time) */
14387 if (appData.icsActive) {
14388 SendToICS(ics_prefix);
14389 SendToICS("flag\n");
14391 switch (gameMode) {
14394 case MachinePlaysWhite:
14397 GameEnds(GameIsDrawn, "Both players ran out of time",
14400 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
14402 DisplayError(_("Your opponent is not out of time"), 0);
14405 case MachinePlaysBlack:
14408 GameEnds(GameIsDrawn, "Both players ran out of time",
14411 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
14413 DisplayError(_("Your opponent is not out of time"), 0);
14421 ClockClick (int which)
14422 { // [HGM] code moved to back-end from winboard.c
14423 if(which) { // black clock
14424 if (gameMode == EditPosition || gameMode == IcsExamining) {
14425 if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
14426 SetBlackToPlayEvent();
14427 } else if ((gameMode == AnalyzeMode || gameMode == EditGame) && !blackFlag && WhiteOnMove(currentMove)) {
14428 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move: if not out of time, enters null move
14429 } else if (shiftKey) {
14430 AdjustClock(which, -1);
14431 } else if (gameMode == IcsPlayingWhite ||
14432 gameMode == MachinePlaysBlack) {
14435 } else { // white clock
14436 if (gameMode == EditPosition || gameMode == IcsExamining) {
14437 if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
14438 SetWhiteToPlayEvent();
14439 } else if ((gameMode == AnalyzeMode || gameMode == EditGame) && !whiteFlag && !WhiteOnMove(currentMove)) {
14440 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move
14441 } else if (shiftKey) {
14442 AdjustClock(which, -1);
14443 } else if (gameMode == IcsPlayingBlack ||
14444 gameMode == MachinePlaysWhite) {
14453 /* Offer draw or accept pending draw offer from opponent */
14455 if (appData.icsActive) {
14456 /* Note: tournament rules require draw offers to be
14457 made after you make your move but before you punch
14458 your clock. Currently ICS doesn't let you do that;
14459 instead, you immediately punch your clock after making
14460 a move, but you can offer a draw at any time. */
14462 SendToICS(ics_prefix);
14463 SendToICS("draw\n");
14464 userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
14465 } else if (cmailMsgLoaded) {
14466 if (currentMove == cmailOldMove &&
14467 commentList[cmailOldMove] != NULL &&
14468 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
14469 "Black offers a draw" : "White offers a draw")) {
14470 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
14471 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
14472 } else if (currentMove == cmailOldMove + 1) {
14473 char *offer = WhiteOnMove(cmailOldMove) ?
14474 "White offers a draw" : "Black offers a draw";
14475 AppendComment(currentMove, offer, TRUE);
14476 DisplayComment(currentMove - 1, offer);
14477 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
14479 DisplayError(_("You must make your move before offering a draw"), 0);
14480 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
14482 } else if (first.offeredDraw) {
14483 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
14485 if (first.sendDrawOffers) {
14486 SendToProgram("draw\n", &first);
14487 userOfferedDraw = TRUE;
14495 /* Offer Adjourn or accept pending Adjourn offer from opponent */
14497 if (appData.icsActive) {
14498 SendToICS(ics_prefix);
14499 SendToICS("adjourn\n");
14501 /* Currently GNU Chess doesn't offer or accept Adjourns */
14509 /* Offer Abort or accept pending Abort offer from opponent */
14511 if (appData.icsActive) {
14512 SendToICS(ics_prefix);
14513 SendToICS("abort\n");
14515 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
14522 /* Resign. You can do this even if it's not your turn. */
14524 if (appData.icsActive) {
14525 SendToICS(ics_prefix);
14526 SendToICS("resign\n");
14528 switch (gameMode) {
14529 case MachinePlaysWhite:
14530 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
14532 case MachinePlaysBlack:
14533 GameEnds(BlackWins, "White resigns", GE_PLAYER);
14536 if (cmailMsgLoaded) {
14538 if (WhiteOnMove(cmailOldMove)) {
14539 GameEnds(BlackWins, "White resigns", GE_PLAYER);
14541 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
14543 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
14554 StopObservingEvent ()
14556 /* Stop observing current games */
14557 SendToICS(ics_prefix);
14558 SendToICS("unobserve\n");
14562 StopExaminingEvent ()
14564 /* Stop observing current game */
14565 SendToICS(ics_prefix);
14566 SendToICS("unexamine\n");
14570 ForwardInner (int target)
14572 int limit; int oldSeekGraphUp = seekGraphUp;
14574 if (appData.debugMode)
14575 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
14576 target, currentMove, forwardMostMove);
14578 if (gameMode == EditPosition)
14581 seekGraphUp = FALSE;
14582 MarkTargetSquares(1);
14584 if (gameMode == PlayFromGameFile && !pausing)
14587 if (gameMode == IcsExamining && pausing)
14588 limit = pauseExamForwardMostMove;
14590 limit = forwardMostMove;
14592 if (target > limit) target = limit;
14594 if (target > 0 && moveList[target - 1][0]) {
14595 int fromX, fromY, toX, toY;
14596 toX = moveList[target - 1][2] - AAA;
14597 toY = moveList[target - 1][3] - ONE;
14598 if (moveList[target - 1][1] == '@') {
14599 if (appData.highlightLastMove) {
14600 SetHighlights(-1, -1, toX, toY);
14603 fromX = moveList[target - 1][0] - AAA;
14604 fromY = moveList[target - 1][1] - ONE;
14605 if (target == currentMove + 1) {
14606 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
14608 if (appData.highlightLastMove) {
14609 SetHighlights(fromX, fromY, toX, toY);
14613 if (gameMode == EditGame || gameMode == AnalyzeMode ||
14614 gameMode == Training || gameMode == PlayFromGameFile ||
14615 gameMode == AnalyzeFile) {
14616 while (currentMove < target) {
14617 if(second.analyzing) SendMoveToProgram(currentMove, &second);
14618 SendMoveToProgram(currentMove++, &first);
14621 currentMove = target;
14624 if (gameMode == EditGame || gameMode == EndOfGame) {
14625 whiteTimeRemaining = timeRemaining[0][currentMove];
14626 blackTimeRemaining = timeRemaining[1][currentMove];
14628 DisplayBothClocks();
14629 DisplayMove(currentMove - 1);
14630 DrawPosition(oldSeekGraphUp, boards[currentMove]);
14631 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
14632 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
14633 DisplayComment(currentMove - 1, commentList[currentMove]);
14635 ClearMap(); // [HGM] exclude: invalidate map
14642 if (gameMode == IcsExamining && !pausing) {
14643 SendToICS(ics_prefix);
14644 SendToICS("forward\n");
14646 ForwardInner(currentMove + 1);
14653 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14654 /* to optimze, we temporarily turn off analysis mode while we feed
14655 * the remaining moves to the engine. Otherwise we get analysis output
14658 if (first.analysisSupport) {
14659 SendToProgram("exit\nforce\n", &first);
14660 first.analyzing = FALSE;
14664 if (gameMode == IcsExamining && !pausing) {
14665 SendToICS(ics_prefix);
14666 SendToICS("forward 999999\n");
14668 ForwardInner(forwardMostMove);
14671 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14672 /* we have fed all the moves, so reactivate analysis mode */
14673 SendToProgram("analyze\n", &first);
14674 first.analyzing = TRUE;
14675 /*first.maybeThinking = TRUE;*/
14676 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14681 BackwardInner (int target)
14683 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
14685 if (appData.debugMode)
14686 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
14687 target, currentMove, forwardMostMove);
14689 if (gameMode == EditPosition) return;
14690 seekGraphUp = FALSE;
14691 MarkTargetSquares(1);
14692 if (currentMove <= backwardMostMove) {
14694 DrawPosition(full_redraw, boards[currentMove]);
14697 if (gameMode == PlayFromGameFile && !pausing)
14700 if (moveList[target][0]) {
14701 int fromX, fromY, toX, toY;
14702 toX = moveList[target][2] - AAA;
14703 toY = moveList[target][3] - ONE;
14704 if (moveList[target][1] == '@') {
14705 if (appData.highlightLastMove) {
14706 SetHighlights(-1, -1, toX, toY);
14709 fromX = moveList[target][0] - AAA;
14710 fromY = moveList[target][1] - ONE;
14711 if (target == currentMove - 1) {
14712 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
14714 if (appData.highlightLastMove) {
14715 SetHighlights(fromX, fromY, toX, toY);
14719 if (gameMode == EditGame || gameMode==AnalyzeMode ||
14720 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
14721 while (currentMove > target) {
14722 if(moveList[currentMove-1][1] == '@' && moveList[currentMove-1][0] == '@') {
14723 // null move cannot be undone. Reload program with move history before it.
14725 for(i=target; i>backwardMostMove; i--) { // seek back to start or previous null move
14726 if(moveList[i-1][1] == '@' && moveList[i-1][0] == '@') break;
14728 SendBoard(&first, i);
14729 if(second.analyzing) SendBoard(&second, i);
14730 for(currentMove=i; currentMove<target; currentMove++) {
14731 SendMoveToProgram(currentMove, &first);
14732 if(second.analyzing) SendMoveToProgram(currentMove, &second);
14736 SendToBoth("undo\n");
14740 currentMove = target;
14743 if (gameMode == EditGame || gameMode == EndOfGame) {
14744 whiteTimeRemaining = timeRemaining[0][currentMove];
14745 blackTimeRemaining = timeRemaining[1][currentMove];
14747 DisplayBothClocks();
14748 DisplayMove(currentMove - 1);
14749 DrawPosition(full_redraw, boards[currentMove]);
14750 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
14751 // [HGM] PV info: routine tests if comment empty
14752 DisplayComment(currentMove - 1, commentList[currentMove]);
14753 ClearMap(); // [HGM] exclude: invalidate map
14759 if (gameMode == IcsExamining && !pausing) {
14760 SendToICS(ics_prefix);
14761 SendToICS("backward\n");
14763 BackwardInner(currentMove - 1);
14770 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14771 /* to optimize, we temporarily turn off analysis mode while we undo
14772 * all the moves. Otherwise we get analysis output after each undo.
14774 if (first.analysisSupport) {
14775 SendToProgram("exit\nforce\n", &first);
14776 first.analyzing = FALSE;
14780 if (gameMode == IcsExamining && !pausing) {
14781 SendToICS(ics_prefix);
14782 SendToICS("backward 999999\n");
14784 BackwardInner(backwardMostMove);
14787 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
14788 /* we have fed all the moves, so reactivate analysis mode */
14789 SendToProgram("analyze\n", &first);
14790 first.analyzing = TRUE;
14791 /*first.maybeThinking = TRUE;*/
14792 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14799 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
14800 if (to >= forwardMostMove) to = forwardMostMove;
14801 if (to <= backwardMostMove) to = backwardMostMove;
14802 if (to < currentMove) {
14810 RevertEvent (Boolean annotate)
14812 if(PopTail(annotate)) { // [HGM] vari: restore old game tail
14815 if (gameMode != IcsExamining) {
14816 DisplayError(_("You are not examining a game"), 0);
14820 DisplayError(_("You can't revert while pausing"), 0);
14823 SendToICS(ics_prefix);
14824 SendToICS("revert\n");
14828 RetractMoveEvent ()
14830 switch (gameMode) {
14831 case MachinePlaysWhite:
14832 case MachinePlaysBlack:
14833 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
14834 DisplayError(_("Wait until your turn,\nor select Move Now"), 0);
14837 if (forwardMostMove < 2) return;
14838 currentMove = forwardMostMove = forwardMostMove - 2;
14839 whiteTimeRemaining = timeRemaining[0][currentMove];
14840 blackTimeRemaining = timeRemaining[1][currentMove];
14841 DisplayBothClocks();
14842 DisplayMove(currentMove - 1);
14843 ClearHighlights();/*!! could figure this out*/
14844 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
14845 SendToProgram("remove\n", &first);
14846 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
14849 case BeginningOfGame:
14853 case IcsPlayingWhite:
14854 case IcsPlayingBlack:
14855 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
14856 SendToICS(ics_prefix);
14857 SendToICS("takeback 2\n");
14859 SendToICS(ics_prefix);
14860 SendToICS("takeback 1\n");
14869 ChessProgramState *cps;
14871 switch (gameMode) {
14872 case MachinePlaysWhite:
14873 if (!WhiteOnMove(forwardMostMove)) {
14874 DisplayError(_("It is your turn"), 0);
14879 case MachinePlaysBlack:
14880 if (WhiteOnMove(forwardMostMove)) {
14881 DisplayError(_("It is your turn"), 0);
14886 case TwoMachinesPlay:
14887 if (WhiteOnMove(forwardMostMove) ==
14888 (first.twoMachinesColor[0] == 'w')) {
14894 case BeginningOfGame:
14898 SendToProgram("?\n", cps);
14902 TruncateGameEvent ()
14905 if (gameMode != EditGame) return;
14912 CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
14913 if (forwardMostMove > currentMove) {
14914 if (gameInfo.resultDetails != NULL) {
14915 free(gameInfo.resultDetails);
14916 gameInfo.resultDetails = NULL;
14917 gameInfo.result = GameUnfinished;
14919 forwardMostMove = currentMove;
14920 HistorySet(parseList, backwardMostMove, forwardMostMove,
14928 if (appData.noChessProgram) return;
14929 switch (gameMode) {
14930 case MachinePlaysWhite:
14931 if (WhiteOnMove(forwardMostMove)) {
14932 DisplayError(_("Wait until your turn"), 0);
14936 case BeginningOfGame:
14937 case MachinePlaysBlack:
14938 if (!WhiteOnMove(forwardMostMove)) {
14939 DisplayError(_("Wait until your turn"), 0);
14944 DisplayError(_("No hint available"), 0);
14947 SendToProgram("hint\n", &first);
14948 hintRequested = TRUE;
14954 if (appData.noChessProgram) return;
14955 switch (gameMode) {
14956 case MachinePlaysWhite:
14957 if (WhiteOnMove(forwardMostMove)) {
14958 DisplayError(_("Wait until your turn"), 0);
14962 case BeginningOfGame:
14963 case MachinePlaysBlack:
14964 if (!WhiteOnMove(forwardMostMove)) {
14965 DisplayError(_("Wait until your turn"), 0);
14970 EditPositionDone(TRUE);
14972 case TwoMachinesPlay:
14977 SendToProgram("bk\n", &first);
14978 bookOutput[0] = NULLCHAR;
14979 bookRequested = TRUE;
14985 char *tags = PGNTags(&gameInfo);
14986 TagsPopUp(tags, CmailMsg());
14990 /* end button procedures */
14993 PrintPosition (FILE *fp, int move)
14997 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
14998 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
14999 char c = PieceToChar(boards[move][i][j]);
15000 fputc(c == 'x' ? '.' : c, fp);
15001 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
15004 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
15005 fprintf(fp, "white to play\n");
15007 fprintf(fp, "black to play\n");
15011 PrintOpponents (FILE *fp)
15013 if (gameInfo.white != NULL) {
15014 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
15020 /* Find last component of program's own name, using some heuristics */
15022 TidyProgramName (char *prog, char *host, char buf[MSG_SIZ])
15025 int local = (strcmp(host, "localhost") == 0);
15026 while (!local && (p = strchr(prog, ';')) != NULL) {
15028 while (*p == ' ') p++;
15031 if (*prog == '"' || *prog == '\'') {
15032 q = strchr(prog + 1, *prog);
15034 q = strchr(prog, ' ');
15036 if (q == NULL) q = prog + strlen(prog);
15038 while (p >= prog && *p != '/' && *p != '\\') p--;
15040 if(p == prog && *p == '"') p++;
15042 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) *q = c, q -= 4; else *q = c;
15043 memcpy(buf, p, q - p);
15044 buf[q - p] = NULLCHAR;
15052 TimeControlTagValue ()
15055 if (!appData.clockMode) {
15056 safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
15057 } else if (movesPerSession > 0) {
15058 snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
15059 } else if (timeIncrement == 0) {
15060 snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
15062 snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
15064 return StrSave(buf);
15070 /* This routine is used only for certain modes */
15071 VariantClass v = gameInfo.variant;
15072 ChessMove r = GameUnfinished;
15075 if(keepInfo) return;
15077 if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
15078 r = gameInfo.result;
15079 p = gameInfo.resultDetails;
15080 gameInfo.resultDetails = NULL;
15082 ClearGameInfo(&gameInfo);
15083 gameInfo.variant = v;
15085 switch (gameMode) {
15086 case MachinePlaysWhite:
15087 gameInfo.event = StrSave( appData.pgnEventHeader );
15088 gameInfo.site = StrSave(HostName());
15089 gameInfo.date = PGNDate();
15090 gameInfo.round = StrSave("-");
15091 gameInfo.white = StrSave(first.tidy);
15092 gameInfo.black = StrSave(UserName());
15093 gameInfo.timeControl = TimeControlTagValue();
15096 case MachinePlaysBlack:
15097 gameInfo.event = StrSave( appData.pgnEventHeader );
15098 gameInfo.site = StrSave(HostName());
15099 gameInfo.date = PGNDate();
15100 gameInfo.round = StrSave("-");
15101 gameInfo.white = StrSave(UserName());
15102 gameInfo.black = StrSave(first.tidy);
15103 gameInfo.timeControl = TimeControlTagValue();
15106 case TwoMachinesPlay:
15107 gameInfo.event = StrSave( appData.pgnEventHeader );
15108 gameInfo.site = StrSave(HostName());
15109 gameInfo.date = PGNDate();
15112 snprintf(buf, MSG_SIZ, "%d", roundNr);
15113 gameInfo.round = StrSave(buf);
15115 gameInfo.round = StrSave("-");
15117 if (first.twoMachinesColor[0] == 'w') {
15118 gameInfo.white = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
15119 gameInfo.black = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
15121 gameInfo.white = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
15122 gameInfo.black = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
15124 gameInfo.timeControl = TimeControlTagValue();
15128 gameInfo.event = StrSave("Edited game");
15129 gameInfo.site = StrSave(HostName());
15130 gameInfo.date = PGNDate();
15131 gameInfo.round = StrSave("-");
15132 gameInfo.white = StrSave("-");
15133 gameInfo.black = StrSave("-");
15134 gameInfo.result = r;
15135 gameInfo.resultDetails = p;
15139 gameInfo.event = StrSave("Edited position");
15140 gameInfo.site = StrSave(HostName());
15141 gameInfo.date = PGNDate();
15142 gameInfo.round = StrSave("-");
15143 gameInfo.white = StrSave("-");
15144 gameInfo.black = StrSave("-");
15147 case IcsPlayingWhite:
15148 case IcsPlayingBlack:
15153 case PlayFromGameFile:
15154 gameInfo.event = StrSave("Game from non-PGN file");
15155 gameInfo.site = StrSave(HostName());
15156 gameInfo.date = PGNDate();
15157 gameInfo.round = StrSave("-");
15158 gameInfo.white = StrSave("?");
15159 gameInfo.black = StrSave("?");
15168 ReplaceComment (int index, char *text)
15174 if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
15175 pvInfoList[index-1].depth == len &&
15176 fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
15177 (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
15178 while (*text == '\n') text++;
15179 len = strlen(text);
15180 while (len > 0 && text[len - 1] == '\n') len--;
15182 if (commentList[index] != NULL)
15183 free(commentList[index]);
15186 commentList[index] = NULL;
15189 if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
15190 *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
15191 *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
15192 commentList[index] = (char *) malloc(len + 2);
15193 strncpy(commentList[index], text, len);
15194 commentList[index][len] = '\n';
15195 commentList[index][len + 1] = NULLCHAR;
15197 // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
15199 commentList[index] = (char *) malloc(len + 7);
15200 safeStrCpy(commentList[index], "{\n", 3);
15201 safeStrCpy(commentList[index]+2, text, len+1);
15202 commentList[index][len+2] = NULLCHAR;
15203 while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
15204 strcat(commentList[index], "\n}\n");
15209 CrushCRs (char *text)
15217 if (ch == '\r') continue;
15219 } while (ch != '\0');
15223 AppendComment (int index, char *text, Boolean addBraces)
15224 /* addBraces tells if we should add {} */
15229 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces); fflush(debugFP);
15230 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
15233 while (*text == '\n') text++;
15234 len = strlen(text);
15235 while (len > 0 && text[len - 1] == '\n') len--;
15236 text[len] = NULLCHAR;
15238 if (len == 0) return;
15240 if (commentList[index] != NULL) {
15241 Boolean addClosingBrace = addBraces;
15242 old = commentList[index];
15243 oldlen = strlen(old);
15244 while(commentList[index][oldlen-1] == '\n')
15245 commentList[index][--oldlen] = NULLCHAR;
15246 commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
15247 safeStrCpy(commentList[index], old, oldlen + len + 6);
15249 // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
15250 if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
15251 if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
15252 while (*text == '\n') { text++; len--; }
15253 commentList[index][--oldlen] = NULLCHAR;
15255 if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
15256 else strcat(commentList[index], "\n");
15257 strcat(commentList[index], text);
15258 if(addClosingBrace) strcat(commentList[index], addClosingBrace == 2 ? ")\n" : "\n}\n");
15259 else strcat(commentList[index], "\n");
15261 commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
15263 safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
15264 else commentList[index][0] = NULLCHAR;
15265 strcat(commentList[index], text);
15266 strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
15267 if(addBraces == TRUE) strcat(commentList[index], "}\n");
15272 FindStr (char * text, char * sub_text)
15274 char * result = strstr( text, sub_text );
15276 if( result != NULL ) {
15277 result += strlen( sub_text );
15283 /* [AS] Try to extract PV info from PGN comment */
15284 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
15286 GetInfoFromComment (int index, char * text)
15288 char * sep = text, *p;
15290 if( text != NULL && index > 0 ) {
15293 int time = -1, sec = 0, deci;
15294 char * s_eval = FindStr( text, "[%eval " );
15295 char * s_emt = FindStr( text, "[%emt " );
15297 if( s_eval != NULL || s_emt != NULL ) {
15301 if( s_eval != NULL ) {
15302 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
15306 if( delim != ']' ) {
15311 if( s_emt != NULL ) {
15316 /* We expect something like: [+|-]nnn.nn/dd */
15319 if(*text != '{') return text; // [HGM] braces: must be normal comment
15321 sep = strchr( text, '/' );
15322 if( sep == NULL || sep < (text+4) ) {
15327 if(p[1] == '(') { // comment starts with PV
15328 p = strchr(p, ')'); // locate end of PV
15329 if(p == NULL || sep < p+5) return text;
15330 // at this point we have something like "{(.*) +0.23/6 ..."
15331 p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
15332 *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
15333 // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
15335 time = -1; sec = -1; deci = -1;
15336 if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
15337 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
15338 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
15339 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
15343 if( score_lo < 0 || score_lo >= 100 ) {
15347 if(sec >= 0) time = 600*time + 10*sec; else
15348 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
15350 score = score >= 0 ? score*100 + score_lo : score*100 - score_lo;
15352 /* [HGM] PV time: now locate end of PV info */
15353 while( *++sep >= '0' && *sep <= '9'); // strip depth
15355 while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
15357 while( *++sep >= '0' && *sep <= '9'); // strip seconds
15359 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
15360 while(*sep == ' ' || *sep == '\n' || *sep == '\r') sep++;
15371 pvInfoList[index-1].depth = depth;
15372 pvInfoList[index-1].score = score;
15373 pvInfoList[index-1].time = 10*time; // centi-sec
15374 if(*sep == '}') *sep = 0; else *--sep = '{';
15375 if(p != text) { while(*p++ = *sep++); sep = text; } // squeeze out space between PV and comment, and return both
15381 SendToProgram (char *message, ChessProgramState *cps)
15383 int count, outCount, error;
15386 if (cps->pr == NoProc) return;
15389 if (appData.debugMode) {
15392 fprintf(debugFP, "%ld >%-6s: %s",
15393 SubtractTimeMarks(&now, &programStartTime),
15394 cps->which, message);
15396 fprintf(serverFP, "%ld >%-6s: %s",
15397 SubtractTimeMarks(&now, &programStartTime),
15398 cps->which, message), fflush(serverFP);
15401 count = strlen(message);
15402 outCount = OutputToProcess(cps->pr, message, count, &error);
15403 if (outCount < count && !exiting
15404 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
15405 if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
15406 snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
15407 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
15408 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
15409 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
15410 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
15411 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
15413 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
15414 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
15415 gameInfo.result = res;
15417 gameInfo.resultDetails = StrSave(buf);
15419 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
15420 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
15425 ReceiveFromProgram (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
15429 ChessProgramState *cps = (ChessProgramState *)closure;
15431 if (isr != cps->isr) return; /* Killed intentionally */
15434 RemoveInputSource(cps->isr);
15435 snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
15436 _(cps->which), cps->program);
15437 if(LoadError(cps->userError ? NULL : buf, cps)) return; // [HGM] should not generate fatal error during engine load
15438 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
15439 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
15440 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
15441 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
15442 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
15444 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
15445 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
15446 gameInfo.result = res;
15448 gameInfo.resultDetails = StrSave(buf);
15450 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
15451 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
15453 snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
15454 _(cps->which), cps->program);
15455 RemoveInputSource(cps->isr);
15457 /* [AS] Program is misbehaving badly... kill it */
15458 if( count == -2 ) {
15459 DestroyChildProcess( cps->pr, 9 );
15463 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
15468 if ((end_str = strchr(message, '\r')) != NULL)
15469 *end_str = NULLCHAR;
15470 if ((end_str = strchr(message, '\n')) != NULL)
15471 *end_str = NULLCHAR;
15473 if (appData.debugMode) {
15474 TimeMark now; int print = 1;
15475 char *quote = ""; char c; int i;
15477 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
15478 char start = message[0];
15479 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
15480 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
15481 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
15482 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
15483 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
15484 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
15485 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
15486 sscanf(message, "setboard %c", &c)!=1 && sscanf(message, "setup %c", &c)!=1 &&
15487 sscanf(message, "hint: %c", &c)!=1 &&
15488 sscanf(message, "pong %c", &c)!=1 && start != '#') {
15489 quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
15490 print = (appData.engineComments >= 2);
15492 message[0] = start; // restore original message
15496 fprintf(debugFP, "%ld <%-6s: %s%s\n",
15497 SubtractTimeMarks(&now, &programStartTime), cps->which,
15501 fprintf(serverFP, "%ld <%-6s: %s%s\n",
15502 SubtractTimeMarks(&now, &programStartTime), cps->which,
15504 message), fflush(serverFP);
15508 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
15509 if (appData.icsEngineAnalyze) {
15510 if (strstr(message, "whisper") != NULL ||
15511 strstr(message, "kibitz") != NULL ||
15512 strstr(message, "tellics") != NULL) return;
15515 HandleMachineMove(message, cps);
15520 SendTimeControl (ChessProgramState *cps, int mps, long tc, int inc, int sd, int st)
15525 if( timeControl_2 > 0 ) {
15526 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
15527 tc = timeControl_2;
15530 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
15531 inc /= cps->timeOdds;
15532 st /= cps->timeOdds;
15534 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
15537 /* Set exact time per move, normally using st command */
15538 if (cps->stKludge) {
15539 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
15541 if (seconds == 0) {
15542 snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
15544 snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
15547 snprintf(buf, MSG_SIZ, "st %d\n", st);
15550 /* Set conventional or incremental time control, using level command */
15551 if (seconds == 0) {
15552 /* Note old gnuchess bug -- minutes:seconds used to not work.
15553 Fixed in later versions, but still avoid :seconds
15554 when seconds is 0. */
15555 snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
15557 snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
15558 seconds, inc/1000.);
15561 SendToProgram(buf, cps);
15563 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
15564 /* Orthogonally, limit search to given depth */
15566 if (cps->sdKludge) {
15567 snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
15569 snprintf(buf, MSG_SIZ, "sd %d\n", sd);
15571 SendToProgram(buf, cps);
15574 if(cps->nps >= 0) { /* [HGM] nps */
15575 if(cps->supportsNPS == FALSE)
15576 cps->nps = -1; // don't use if engine explicitly says not supported!
15578 snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
15579 SendToProgram(buf, cps);
15584 ChessProgramState *
15586 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
15588 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
15589 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
15595 SendTimeRemaining (ChessProgramState *cps, int machineWhite)
15597 char message[MSG_SIZ];
15600 /* Note: this routine must be called when the clocks are stopped
15601 or when they have *just* been set or switched; otherwise
15602 it will be off by the time since the current tick started.
15604 if (machineWhite) {
15605 time = whiteTimeRemaining / 10;
15606 otime = blackTimeRemaining / 10;
15608 time = blackTimeRemaining / 10;
15609 otime = whiteTimeRemaining / 10;
15611 /* [HGM] translate opponent's time by time-odds factor */
15612 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
15614 if (time <= 0) time = 1;
15615 if (otime <= 0) otime = 1;
15617 snprintf(message, MSG_SIZ, "time %ld\n", time);
15618 SendToProgram(message, cps);
15620 snprintf(message, MSG_SIZ, "otim %ld\n", otime);
15621 SendToProgram(message, cps);
15625 BoolFeature (char **p, char *name, int *loc, ChessProgramState *cps)
15628 int len = strlen(name);
15631 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
15633 sscanf(*p, "%d", &val);
15635 while (**p && **p != ' ')
15637 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15638 SendToProgram(buf, cps);
15645 IntFeature (char **p, char *name, int *loc, ChessProgramState *cps)
15648 int len = strlen(name);
15649 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
15651 sscanf(*p, "%d", loc);
15652 while (**p && **p != ' ') (*p)++;
15653 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15654 SendToProgram(buf, cps);
15661 StringFeature (char **p, char *name, char loc[], ChessProgramState *cps)
15664 int len = strlen(name);
15665 if (strncmp((*p), name, len) == 0
15666 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
15668 sscanf(*p, "%[^\"]", loc);
15669 while (**p && **p != '\"') (*p)++;
15670 if (**p == '\"') (*p)++;
15671 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
15672 SendToProgram(buf, cps);
15679 ParseOption (Option *opt, ChessProgramState *cps)
15680 // [HGM] options: process the string that defines an engine option, and determine
15681 // name, type, default value, and allowed value range
15683 char *p, *q, buf[MSG_SIZ];
15684 int n, min = (-1)<<31, max = 1<<31, def;
15686 if(p = strstr(opt->name, " -spin ")) {
15687 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
15688 if(max < min) max = min; // enforce consistency
15689 if(def < min) def = min;
15690 if(def > max) def = max;
15695 } else if((p = strstr(opt->name, " -slider "))) {
15696 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
15697 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
15698 if(max < min) max = min; // enforce consistency
15699 if(def < min) def = min;
15700 if(def > max) def = max;
15704 opt->type = Spin; // Slider;
15705 } else if((p = strstr(opt->name, " -string "))) {
15706 opt->textValue = p+9;
15707 opt->type = TextBox;
15708 } else if((p = strstr(opt->name, " -file "))) {
15709 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
15710 opt->textValue = p+7;
15711 opt->type = FileName; // FileName;
15712 } else if((p = strstr(opt->name, " -path "))) {
15713 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
15714 opt->textValue = p+7;
15715 opt->type = PathName; // PathName;
15716 } else if(p = strstr(opt->name, " -check ")) {
15717 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
15718 opt->value = (def != 0);
15719 opt->type = CheckBox;
15720 } else if(p = strstr(opt->name, " -combo ")) {
15721 opt->textValue = (char*) (opt->choice = &cps->comboList[cps->comboCnt]); // cheat with pointer type
15722 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
15723 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
15724 opt->value = n = 0;
15725 while(q = StrStr(q, " /// ")) {
15726 n++; *q = 0; // count choices, and null-terminate each of them
15728 if(*q == '*') { // remember default, which is marked with * prefix
15732 cps->comboList[cps->comboCnt++] = q;
15734 cps->comboList[cps->comboCnt++] = NULL;
15736 opt->type = ComboBox;
15737 } else if(p = strstr(opt->name, " -button")) {
15738 opt->type = Button;
15739 } else if(p = strstr(opt->name, " -save")) {
15740 opt->type = SaveButton;
15741 } else return FALSE;
15742 *p = 0; // terminate option name
15743 // now look if the command-line options define a setting for this engine option.
15744 if(cps->optionSettings && cps->optionSettings[0])
15745 p = strstr(cps->optionSettings, opt->name); else p = NULL;
15746 if(p && (p == cps->optionSettings || p[-1] == ',')) {
15747 snprintf(buf, MSG_SIZ, "option %s", p);
15748 if(p = strstr(buf, ",")) *p = 0;
15749 if(q = strchr(buf, '=')) switch(opt->type) {
15751 for(n=0; n<opt->max; n++)
15752 if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
15755 safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
15759 opt->value = atoi(q+1);
15764 SendToProgram(buf, cps);
15770 FeatureDone (ChessProgramState *cps, int val)
15772 DelayedEventCallback cb = GetDelayedEvent();
15773 if ((cb == InitBackEnd3 && cps == &first) ||
15774 (cb == SettingsMenuIfReady && cps == &second) ||
15775 (cb == LoadEngine) ||
15776 (cb == TwoMachinesEventIfReady)) {
15777 CancelDelayedEvent();
15778 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
15780 cps->initDone = val;
15783 /* Parse feature command from engine */
15785 ParseFeatures (char *args, ChessProgramState *cps)
15793 while (*p == ' ') p++;
15794 if (*p == NULLCHAR) return;
15796 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
15797 if (BoolFeature(&p, "xedit", &cps->extendedEdit, cps)) continue;
15798 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
15799 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
15800 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
15801 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
15802 if (BoolFeature(&p, "reuse", &val, cps)) {
15803 /* Engine can disable reuse, but can't enable it if user said no */
15804 if (!val) cps->reuse = FALSE;
15807 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
15808 if (StringFeature(&p, "myname", cps->tidy, cps)) {
15809 if (gameMode == TwoMachinesPlay) {
15810 DisplayTwoMachinesTitle();
15816 if (StringFeature(&p, "variants", cps->variants, cps)) continue;
15817 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
15818 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
15819 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
15820 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
15821 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
15822 if (BoolFeature(&p, "exclude", &cps->excludeMoves, cps)) continue;
15823 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
15824 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
15825 if (BoolFeature(&p, "pause", &val, cps)) continue; /* unused at present */
15826 if (IntFeature(&p, "done", &val, cps)) {
15827 FeatureDone(cps, val);
15830 /* Added by Tord: */
15831 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
15832 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
15833 /* End of additions by Tord */
15835 /* [HGM] added features: */
15836 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
15837 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
15838 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
15839 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
15840 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
15841 if (StringFeature(&p, "egt", cps->egtFormats, cps)) continue;
15842 if (StringFeature(&p, "option", buf, cps)) {
15843 FREE(cps->option[cps->nrOptions].name);
15844 cps->option[cps->nrOptions].name = malloc(MSG_SIZ);
15845 safeStrCpy(cps->option[cps->nrOptions].name, buf, MSG_SIZ);
15846 if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
15847 snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
15848 SendToProgram(buf, cps);
15851 if(cps->nrOptions >= MAX_OPTIONS) {
15853 snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
15854 DisplayError(buf, 0);
15858 /* End of additions by HGM */
15860 /* unknown feature: complain and skip */
15862 while (*q && *q != '=') q++;
15863 snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
15864 SendToProgram(buf, cps);
15870 while (*p && *p != '\"') p++;
15871 if (*p == '\"') p++;
15873 while (*p && *p != ' ') p++;
15881 PeriodicUpdatesEvent (int newState)
15883 if (newState == appData.periodicUpdates)
15886 appData.periodicUpdates=newState;
15888 /* Display type changes, so update it now */
15889 // DisplayAnalysis();
15891 /* Get the ball rolling again... */
15893 AnalysisPeriodicEvent(1);
15894 StartAnalysisClock();
15899 PonderNextMoveEvent (int newState)
15901 if (newState == appData.ponderNextMove) return;
15902 if (gameMode == EditPosition) EditPositionDone(TRUE);
15904 SendToProgram("hard\n", &first);
15905 if (gameMode == TwoMachinesPlay) {
15906 SendToProgram("hard\n", &second);
15909 SendToProgram("easy\n", &first);
15910 thinkOutput[0] = NULLCHAR;
15911 if (gameMode == TwoMachinesPlay) {
15912 SendToProgram("easy\n", &second);
15915 appData.ponderNextMove = newState;
15919 NewSettingEvent (int option, int *feature, char *command, int value)
15923 if (gameMode == EditPosition) EditPositionDone(TRUE);
15924 snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
15925 if(feature == NULL || *feature) SendToProgram(buf, &first);
15926 if (gameMode == TwoMachinesPlay) {
15927 if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
15932 ShowThinkingEvent ()
15933 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
15935 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
15936 int newState = appData.showThinking
15937 // [HGM] thinking: other features now need thinking output as well
15938 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
15940 if (oldState == newState) return;
15941 oldState = newState;
15942 if (gameMode == EditPosition) EditPositionDone(TRUE);
15944 SendToProgram("post\n", &first);
15945 if (gameMode == TwoMachinesPlay) {
15946 SendToProgram("post\n", &second);
15949 SendToProgram("nopost\n", &first);
15950 thinkOutput[0] = NULLCHAR;
15951 if (gameMode == TwoMachinesPlay) {
15952 SendToProgram("nopost\n", &second);
15955 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
15959 AskQuestionEvent (char *title, char *question, char *replyPrefix, char *which)
15961 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
15962 if (pr == NoProc) return;
15963 AskQuestion(title, question, replyPrefix, pr);
15967 TypeInEvent (char firstChar)
15969 if ((gameMode == BeginningOfGame && !appData.icsActive) ||
15970 gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
15971 gameMode == AnalyzeMode || gameMode == EditGame ||
15972 gameMode == EditPosition || gameMode == IcsExamining ||
15973 gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
15974 isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
15975 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
15976 gameMode == IcsObserving || gameMode == TwoMachinesPlay ) ||
15977 gameMode == Training) PopUpMoveDialog(firstChar);
15981 TypeInDoneEvent (char *move)
15984 int n, fromX, fromY, toX, toY;
15986 ChessMove moveType;
15989 if(gameMode == EditPosition && ParseFEN(board, &n, move) ) {
15990 EditPositionPasteFEN(move);
15993 // [HGM] movenum: allow move number to be typed in any mode
15994 if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
15998 // undocumented kludge: allow command-line option to be typed in!
15999 // (potentially fatal, and does not implement the effect of the option.)
16000 // should only be used for options that are values on which future decisions will be made,
16001 // and definitely not on options that would be used during initialization.
16002 if(strstr(move, "!!! -") == move) {
16003 ParseArgsFromString(move+4);
16007 if (gameMode != EditGame && currentMove != forwardMostMove &&
16008 gameMode != Training) {
16009 DisplayMoveError(_("Displayed move is not current"));
16011 int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
16012 &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
16013 if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
16014 if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
16015 &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
16016 UserMoveEvent(fromX, fromY, toX, toY, promoChar);
16018 DisplayMoveError(_("Could not parse move"));
16024 DisplayMove (int moveNumber)
16026 char message[MSG_SIZ];
16028 char cpThinkOutput[MSG_SIZ];
16030 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
16032 if (moveNumber == forwardMostMove - 1 ||
16033 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
16035 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
16037 if (strchr(cpThinkOutput, '\n')) {
16038 *strchr(cpThinkOutput, '\n') = NULLCHAR;
16041 *cpThinkOutput = NULLCHAR;
16044 /* [AS] Hide thinking from human user */
16045 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
16046 *cpThinkOutput = NULLCHAR;
16047 if( thinkOutput[0] != NULLCHAR ) {
16050 for( i=0; i<=hiddenThinkOutputState; i++ ) {
16051 cpThinkOutput[i] = '.';
16053 cpThinkOutput[i] = NULLCHAR;
16054 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
16058 if (moveNumber == forwardMostMove - 1 &&
16059 gameInfo.resultDetails != NULL) {
16060 if (gameInfo.resultDetails[0] == NULLCHAR) {
16061 snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
16063 snprintf(res, MSG_SIZ, " {%s} %s",
16064 T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
16070 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
16071 DisplayMessage(res, cpThinkOutput);
16073 snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
16074 WhiteOnMove(moveNumber) ? " " : ".. ",
16075 parseList[moveNumber], res);
16076 DisplayMessage(message, cpThinkOutput);
16081 DisplayComment (int moveNumber, char *text)
16083 char title[MSG_SIZ];
16085 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
16086 safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
16088 snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
16089 WhiteOnMove(moveNumber) ? " " : ".. ",
16090 parseList[moveNumber]);
16092 if (text != NULL && (appData.autoDisplayComment || commentUp))
16093 CommentPopUp(title, text);
16096 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
16097 * might be busy thinking or pondering. It can be omitted if your
16098 * gnuchess is configured to stop thinking immediately on any user
16099 * input. However, that gnuchess feature depends on the FIONREAD
16100 * ioctl, which does not work properly on some flavors of Unix.
16103 Attention (ChessProgramState *cps)
16106 if (!cps->useSigint) return;
16107 if (appData.noChessProgram || (cps->pr == NoProc)) return;
16108 switch (gameMode) {
16109 case MachinePlaysWhite:
16110 case MachinePlaysBlack:
16111 case TwoMachinesPlay:
16112 case IcsPlayingWhite:
16113 case IcsPlayingBlack:
16116 /* Skip if we know it isn't thinking */
16117 if (!cps->maybeThinking) return;
16118 if (appData.debugMode)
16119 fprintf(debugFP, "Interrupting %s\n", cps->which);
16120 InterruptChildProcess(cps->pr);
16121 cps->maybeThinking = FALSE;
16126 #endif /*ATTENTION*/
16132 if (whiteTimeRemaining <= 0) {
16135 if (appData.icsActive) {
16136 if (appData.autoCallFlag &&
16137 gameMode == IcsPlayingBlack && !blackFlag) {
16138 SendToICS(ics_prefix);
16139 SendToICS("flag\n");
16143 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
16145 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
16146 if (appData.autoCallFlag) {
16147 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
16154 if (blackTimeRemaining <= 0) {
16157 if (appData.icsActive) {
16158 if (appData.autoCallFlag &&
16159 gameMode == IcsPlayingWhite && !whiteFlag) {
16160 SendToICS(ics_prefix);
16161 SendToICS("flag\n");
16165 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
16167 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
16168 if (appData.autoCallFlag) {
16169 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
16180 CheckTimeControl ()
16182 if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
16183 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
16186 * add time to clocks when time control is achieved ([HGM] now also used for increment)
16188 if ( !WhiteOnMove(forwardMostMove) ) {
16189 /* White made time control */
16190 lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
16191 whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
16192 /* [HGM] time odds: correct new time quota for time odds! */
16193 / WhitePlayer()->timeOdds;
16194 lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
16196 lastBlack -= blackTimeRemaining;
16197 /* Black made time control */
16198 blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
16199 / WhitePlayer()->other->timeOdds;
16200 lastWhite = whiteTimeRemaining;
16205 DisplayBothClocks ()
16207 int wom = gameMode == EditPosition ?
16208 !blackPlaysFirst : WhiteOnMove(currentMove);
16209 DisplayWhiteClock(whiteTimeRemaining, wom);
16210 DisplayBlackClock(blackTimeRemaining, !wom);
16214 /* Timekeeping seems to be a portability nightmare. I think everyone
16215 has ftime(), but I'm really not sure, so I'm including some ifdefs
16216 to use other calls if you don't. Clocks will be less accurate if
16217 you have neither ftime nor gettimeofday.
16220 /* VS 2008 requires the #include outside of the function */
16221 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
16222 #include <sys/timeb.h>
16225 /* Get the current time as a TimeMark */
16227 GetTimeMark (TimeMark *tm)
16229 #if HAVE_GETTIMEOFDAY
16231 struct timeval timeVal;
16232 struct timezone timeZone;
16234 gettimeofday(&timeVal, &timeZone);
16235 tm->sec = (long) timeVal.tv_sec;
16236 tm->ms = (int) (timeVal.tv_usec / 1000L);
16238 #else /*!HAVE_GETTIMEOFDAY*/
16241 // include <sys/timeb.h> / moved to just above start of function
16242 struct timeb timeB;
16245 tm->sec = (long) timeB.time;
16246 tm->ms = (int) timeB.millitm;
16248 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
16249 tm->sec = (long) time(NULL);
16255 /* Return the difference in milliseconds between two
16256 time marks. We assume the difference will fit in a long!
16259 SubtractTimeMarks (TimeMark *tm2, TimeMark *tm1)
16261 return 1000L*(tm2->sec - tm1->sec) +
16262 (long) (tm2->ms - tm1->ms);
16267 * Code to manage the game clocks.
16269 * In tournament play, black starts the clock and then white makes a move.
16270 * We give the human user a slight advantage if he is playing white---the
16271 * clocks don't run until he makes his first move, so it takes zero time.
16272 * Also, we don't account for network lag, so we could get out of sync
16273 * with GNU Chess's clock -- but then, referees are always right.
16276 static TimeMark tickStartTM;
16277 static long intendedTickLength;
16280 NextTickLength (long timeRemaining)
16282 long nominalTickLength, nextTickLength;
16284 if (timeRemaining > 0L && timeRemaining <= 10000L)
16285 nominalTickLength = 100L;
16287 nominalTickLength = 1000L;
16288 nextTickLength = timeRemaining % nominalTickLength;
16289 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
16291 return nextTickLength;
16294 /* Adjust clock one minute up or down */
16296 AdjustClock (Boolean which, int dir)
16298 if(appData.autoCallFlag) { DisplayError(_("Clock adjustment not allowed in auto-flag mode"), 0); return; }
16299 if(which) blackTimeRemaining += 60000*dir;
16300 else whiteTimeRemaining += 60000*dir;
16301 DisplayBothClocks();
16302 adjustedClock = TRUE;
16305 /* Stop clocks and reset to a fresh time control */
16309 (void) StopClockTimer();
16310 if (appData.icsActive) {
16311 whiteTimeRemaining = blackTimeRemaining = 0;
16312 } else if (searchTime) {
16313 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
16314 blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
16315 } else { /* [HGM] correct new time quote for time odds */
16316 whiteTC = blackTC = fullTimeControlString;
16317 whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
16318 blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
16320 if (whiteFlag || blackFlag) {
16322 whiteFlag = blackFlag = FALSE;
16324 lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
16325 DisplayBothClocks();
16326 adjustedClock = FALSE;
16329 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
16331 /* Decrement running clock by amount of time that has passed */
16335 long timeRemaining;
16336 long lastTickLength, fudge;
16339 if (!appData.clockMode) return;
16340 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
16344 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
16346 /* Fudge if we woke up a little too soon */
16347 fudge = intendedTickLength - lastTickLength;
16348 if (fudge < 0 || fudge > FUDGE) fudge = 0;
16350 if (WhiteOnMove(forwardMostMove)) {
16351 if(whiteNPS >= 0) lastTickLength = 0;
16352 timeRemaining = whiteTimeRemaining -= lastTickLength;
16353 if(timeRemaining < 0 && !appData.icsActive) {
16354 GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
16355 if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
16356 whiteStartMove = forwardMostMove; whiteTC = nextSession;
16357 lastWhite= timeRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
16360 DisplayWhiteClock(whiteTimeRemaining - fudge,
16361 WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
16363 if(blackNPS >= 0) lastTickLength = 0;
16364 timeRemaining = blackTimeRemaining -= lastTickLength;
16365 if(timeRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
16366 GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
16368 blackStartMove = forwardMostMove;
16369 lastBlack = timeRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
16372 DisplayBlackClock(blackTimeRemaining - fudge,
16373 !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
16375 if (CheckFlags()) return;
16377 if(twoBoards) { // count down secondary board's clocks as well
16378 activePartnerTime -= lastTickLength;
16380 if(activePartner == 'W')
16381 DisplayWhiteClock(activePartnerTime, TRUE); // the counting clock is always the highlighted one!
16383 DisplayBlackClock(activePartnerTime, TRUE);
16388 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
16389 StartClockTimer(intendedTickLength);
16391 /* if the time remaining has fallen below the alarm threshold, sound the
16392 * alarm. if the alarm has sounded and (due to a takeback or time control
16393 * with increment) the time remaining has increased to a level above the
16394 * threshold, reset the alarm so it can sound again.
16397 if (appData.icsActive && appData.icsAlarm) {
16399 /* make sure we are dealing with the user's clock */
16400 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
16401 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
16404 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
16405 alarmSounded = FALSE;
16406 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
16408 alarmSounded = TRUE;
16414 /* A player has just moved, so stop the previously running
16415 clock and (if in clock mode) start the other one.
16416 We redisplay both clocks in case we're in ICS mode, because
16417 ICS gives us an update to both clocks after every move.
16418 Note that this routine is called *after* forwardMostMove
16419 is updated, so the last fractional tick must be subtracted
16420 from the color that is *not* on move now.
16423 SwitchClocks (int newMoveNr)
16425 long lastTickLength;
16427 int flagged = FALSE;
16431 if (StopClockTimer() && appData.clockMode) {
16432 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
16433 if (!WhiteOnMove(forwardMostMove)) {
16434 if(blackNPS >= 0) lastTickLength = 0;
16435 blackTimeRemaining -= lastTickLength;
16436 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
16437 // if(pvInfoList[forwardMostMove].time == -1)
16438 pvInfoList[forwardMostMove].time = // use GUI time
16439 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
16441 if(whiteNPS >= 0) lastTickLength = 0;
16442 whiteTimeRemaining -= lastTickLength;
16443 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
16444 // if(pvInfoList[forwardMostMove].time == -1)
16445 pvInfoList[forwardMostMove].time =
16446 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
16448 flagged = CheckFlags();
16450 forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
16451 CheckTimeControl();
16453 if (flagged || !appData.clockMode) return;
16455 switch (gameMode) {
16456 case MachinePlaysBlack:
16457 case MachinePlaysWhite:
16458 case BeginningOfGame:
16459 if (pausing) return;
16463 case PlayFromGameFile:
16471 if (searchTime) { // [HGM] st: set clock of player that has to move to max time
16472 if(WhiteOnMove(forwardMostMove))
16473 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
16474 else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
16478 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
16479 whiteTimeRemaining : blackTimeRemaining);
16480 StartClockTimer(intendedTickLength);
16484 /* Stop both clocks */
16488 long lastTickLength;
16491 if (!StopClockTimer()) return;
16492 if (!appData.clockMode) return;
16496 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
16497 if (WhiteOnMove(forwardMostMove)) {
16498 if(whiteNPS >= 0) lastTickLength = 0;
16499 whiteTimeRemaining -= lastTickLength;
16500 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
16502 if(blackNPS >= 0) lastTickLength = 0;
16503 blackTimeRemaining -= lastTickLength;
16504 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
16509 /* Start clock of player on move. Time may have been reset, so
16510 if clock is already running, stop and restart it. */
16514 (void) StopClockTimer(); /* in case it was running already */
16515 DisplayBothClocks();
16516 if (CheckFlags()) return;
16518 if (!appData.clockMode) return;
16519 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
16521 GetTimeMark(&tickStartTM);
16522 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
16523 whiteTimeRemaining : blackTimeRemaining);
16525 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
16526 whiteNPS = blackNPS = -1;
16527 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
16528 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
16529 whiteNPS = first.nps;
16530 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
16531 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
16532 blackNPS = first.nps;
16533 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
16534 whiteNPS = second.nps;
16535 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
16536 blackNPS = second.nps;
16537 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
16539 StartClockTimer(intendedTickLength);
16543 TimeString (long ms)
16545 long second, minute, hour, day;
16547 static char buf[32];
16549 if (ms > 0 && ms <= 9900) {
16550 /* convert milliseconds to tenths, rounding up */
16551 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
16553 snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
16557 /* convert milliseconds to seconds, rounding up */
16558 /* use floating point to avoid strangeness of integer division
16559 with negative dividends on many machines */
16560 second = (long) floor(((double) (ms + 999L)) / 1000.0);
16567 day = second / (60 * 60 * 24);
16568 second = second % (60 * 60 * 24);
16569 hour = second / (60 * 60);
16570 second = second % (60 * 60);
16571 minute = second / 60;
16572 second = second % 60;
16575 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ",
16576 sign, day, hour, minute, second);
16578 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
16580 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second);
16587 * This is necessary because some C libraries aren't ANSI C compliant yet.
16590 StrStr (char *string, char *match)
16594 length = strlen(match);
16596 for (i = strlen(string) - length; i >= 0; i--, string++)
16597 if (!strncmp(match, string, length))
16604 StrCaseStr (char *string, char *match)
16608 length = strlen(match);
16610 for (i = strlen(string) - length; i >= 0; i--, string++) {
16611 for (j = 0; j < length; j++) {
16612 if (ToLower(match[j]) != ToLower(string[j]))
16615 if (j == length) return string;
16623 StrCaseCmp (char *s1, char *s2)
16628 c1 = ToLower(*s1++);
16629 c2 = ToLower(*s2++);
16630 if (c1 > c2) return 1;
16631 if (c1 < c2) return -1;
16632 if (c1 == NULLCHAR) return 0;
16640 return isupper(c) ? tolower(c) : c;
16647 return islower(c) ? toupper(c) : c;
16649 #endif /* !_amigados */
16656 if ((ret = (char *) malloc(strlen(s) + 1)))
16658 safeStrCpy(ret, s, strlen(s)+1);
16664 StrSavePtr (char *s, char **savePtr)
16669 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
16670 safeStrCpy(*savePtr, s, strlen(s)+1);
16682 clock = time((time_t *)NULL);
16683 tm = localtime(&clock);
16684 snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
16685 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
16686 return StrSave(buf);
16691 PositionToFEN (int move, char *overrideCastling)
16693 int i, j, fromX, fromY, toX, toY;
16700 whiteToPlay = (gameMode == EditPosition) ?
16701 !blackPlaysFirst : (move % 2 == 0);
16704 /* Piece placement data */
16705 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
16706 if(MSG_SIZ - (p - buf) < BOARD_RGHT - BOARD_LEFT + 20) { *p = 0; return StrSave(buf); }
16708 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
16709 if (boards[move][i][j] == EmptySquare) {
16711 } else { ChessSquare piece = boards[move][i][j];
16712 if (emptycount > 0) {
16713 if(emptycount<10) /* [HGM] can be >= 10 */
16714 *p++ = '0' + emptycount;
16715 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
16718 if(PieceToChar(piece) == '+') {
16719 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
16721 piece = (ChessSquare)(DEMOTED piece);
16723 *p++ = PieceToChar(piece);
16725 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
16726 p[-1] = PieceToChar((ChessSquare)(DEMOTED piece));
16731 if (emptycount > 0) {
16732 if(emptycount<10) /* [HGM] can be >= 10 */
16733 *p++ = '0' + emptycount;
16734 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
16741 /* [HGM] print Crazyhouse or Shogi holdings */
16742 if( gameInfo.holdingsWidth ) {
16743 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
16745 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
16746 piece = boards[move][i][BOARD_WIDTH-1];
16747 if( piece != EmptySquare )
16748 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
16749 *p++ = PieceToChar(piece);
16751 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
16752 piece = boards[move][BOARD_HEIGHT-i-1][0];
16753 if( piece != EmptySquare )
16754 for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
16755 *p++ = PieceToChar(piece);
16758 if( q == p ) *p++ = '-';
16764 *p++ = whiteToPlay ? 'w' : 'b';
16767 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
16768 while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' '; else --p;
16770 if(nrCastlingRights) {
16772 if(gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom) {
16773 /* [HGM] write directly from rights */
16774 if(boards[move][CASTLING][2] != NoRights &&
16775 boards[move][CASTLING][0] != NoRights )
16776 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
16777 if(boards[move][CASTLING][2] != NoRights &&
16778 boards[move][CASTLING][1] != NoRights )
16779 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
16780 if(boards[move][CASTLING][5] != NoRights &&
16781 boards[move][CASTLING][3] != NoRights )
16782 *p++ = boards[move][CASTLING][3] + AAA;
16783 if(boards[move][CASTLING][5] != NoRights &&
16784 boards[move][CASTLING][4] != NoRights )
16785 *p++ = boards[move][CASTLING][4] + AAA;
16788 /* [HGM] write true castling rights */
16789 if( nrCastlingRights == 6 ) {
16791 if(boards[move][CASTLING][0] == BOARD_RGHT-1 &&
16792 boards[move][CASTLING][2] != NoRights ) k = 1, *p++ = 'K';
16793 q = (boards[move][CASTLING][1] == BOARD_LEFT &&
16794 boards[move][CASTLING][2] != NoRights );
16795 if(gameInfo.variant == VariantSChess) { // for S-Chess, indicate all vrgin backrank pieces
16796 for(i=j=0; i<BOARD_HEIGHT; i++) j += boards[move][i][BOARD_RGHT]; // count white held pieces
16797 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q && j; i--)
16798 if((boards[move][0][i] != WhiteKing || k+q == 0) &&
16799 boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
16803 if(boards[move][CASTLING][3] == BOARD_RGHT-1 &&
16804 boards[move][CASTLING][5] != NoRights ) k = 1, *p++ = 'k';
16805 q = (boards[move][CASTLING][4] == BOARD_LEFT &&
16806 boards[move][CASTLING][5] != NoRights );
16807 if(gameInfo.variant == VariantSChess) {
16808 for(i=j=0; i<BOARD_HEIGHT; i++) j += boards[move][i][BOARD_LEFT-1]; // count black held pieces
16809 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q && j; i--)
16810 if((boards[move][BOARD_HEIGHT-1][i] != BlackKing || k+q == 0) &&
16811 boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
16816 if (q == p) *p++ = '-'; /* No castling rights */
16820 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
16821 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
16822 /* En passant target square */
16823 if (move > backwardMostMove) {
16824 fromX = moveList[move - 1][0] - AAA;
16825 fromY = moveList[move - 1][1] - ONE;
16826 toX = moveList[move - 1][2] - AAA;
16827 toY = moveList[move - 1][3] - ONE;
16828 if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
16829 toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
16830 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
16832 /* 2-square pawn move just happened */
16834 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
16838 } else if(move == backwardMostMove) {
16839 // [HGM] perhaps we should always do it like this, and forget the above?
16840 if((signed char)boards[move][EP_STATUS] >= 0) {
16841 *p++ = boards[move][EP_STATUS] + AAA;
16842 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
16853 /* [HGM] find reversible plies */
16854 { int i = 0, j=move;
16856 if (appData.debugMode) { int k;
16857 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
16858 for(k=backwardMostMove; k<=forwardMostMove; k++)
16859 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
16863 while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
16864 if( j == backwardMostMove ) i += initialRulePlies;
16865 sprintf(p, "%d ", i);
16866 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
16868 /* Fullmove number */
16869 sprintf(p, "%d", (move / 2) + 1);
16871 return StrSave(buf);
16875 ParseFEN (Board board, int *blackPlaysFirst, char *fen)
16879 int emptycount, virgin[BOARD_FILES];
16884 /* [HGM] by default clear Crazyhouse holdings, if present */
16885 if(gameInfo.holdingsWidth) {
16886 for(i=0; i<BOARD_HEIGHT; i++) {
16887 board[i][0] = EmptySquare; /* black holdings */
16888 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
16889 board[i][1] = (ChessSquare) 0; /* black counts */
16890 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
16894 /* Piece placement data */
16895 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
16898 if (*p == '/' || *p == ' ' || (*p == '[' && i == 0) ) {
16899 if (*p == '/') p++;
16900 emptycount = gameInfo.boardWidth - j;
16901 while (emptycount--)
16902 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
16904 #if(BOARD_FILES >= 10)
16905 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
16906 p++; emptycount=10;
16907 if (j + emptycount > gameInfo.boardWidth) return FALSE;
16908 while (emptycount--)
16909 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
16911 } else if (isdigit(*p)) {
16912 emptycount = *p++ - '0';
16913 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
16914 if (j + emptycount > gameInfo.boardWidth) return FALSE;
16915 while (emptycount--)
16916 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
16917 } else if (*p == '+' || isalpha(*p)) {
16918 if (j >= gameInfo.boardWidth) return FALSE;
16920 piece = CharToPiece(*++p);
16921 if(piece == EmptySquare) return FALSE; /* unknown piece */
16922 piece = (ChessSquare) (PROMOTED piece ); p++;
16923 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
16924 } else piece = CharToPiece(*p++);
16926 if(piece==EmptySquare) return FALSE; /* unknown piece */
16927 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
16928 piece = (ChessSquare) (PROMOTED piece);
16929 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
16932 board[i][(j++)+gameInfo.holdingsWidth] = piece;
16938 while (*p == '/' || *p == ' ') p++;
16940 /* [HGM] look for Crazyhouse holdings here */
16941 while(*p==' ') p++;
16942 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
16944 if(*p == '-' ) p++; /* empty holdings */ else {
16945 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
16946 /* if we would allow FEN reading to set board size, we would */
16947 /* have to add holdings and shift the board read so far here */
16948 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
16950 if((int) piece >= (int) BlackPawn ) {
16951 i = (int)piece - (int)BlackPawn;
16952 i = PieceToNumber((ChessSquare)i);
16953 if( i >= gameInfo.holdingsSize ) return FALSE;
16954 board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
16955 board[BOARD_HEIGHT-1-i][1]++; /* black counts */
16957 i = (int)piece - (int)WhitePawn;
16958 i = PieceToNumber((ChessSquare)i);
16959 if( i >= gameInfo.holdingsSize ) return FALSE;
16960 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
16961 board[i][BOARD_WIDTH-2]++; /* black holdings */
16968 while(*p == ' ') p++;
16972 if(appData.colorNickNames) {
16973 if( c == appData.colorNickNames[0] ) c = 'w'; else
16974 if( c == appData.colorNickNames[1] ) c = 'b';
16978 *blackPlaysFirst = FALSE;
16981 *blackPlaysFirst = TRUE;
16987 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
16988 /* return the extra info in global variiables */
16990 /* set defaults in case FEN is incomplete */
16991 board[EP_STATUS] = EP_UNKNOWN;
16992 for(i=0; i<nrCastlingRights; i++ ) {
16993 board[CASTLING][i] =
16994 gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom ? NoRights : initialRights[i];
16995 } /* assume possible unless obviously impossible */
16996 if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
16997 if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
16998 if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
16999 && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
17000 if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
17001 if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
17002 if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
17003 && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
17006 while(*p==' ') p++;
17007 if(nrCastlingRights) {
17008 if(gameInfo.variant == VariantSChess) for(i=0; i<BOARD_FILES; i++) virgin[i] = 0;
17009 if(*p >= 'A' && *p <= 'Z' || *p >= 'a' && *p <= 'z' || *p=='-') {
17010 /* castling indicator present, so default becomes no castlings */
17011 for(i=0; i<nrCastlingRights; i++ ) {
17012 board[CASTLING][i] = NoRights;
17015 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
17016 (gameInfo.variant == VariantFischeRandom || gameInfo.variant == VariantCapaRandom || gameInfo.variant == VariantSChess) &&
17017 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
17018 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
17019 int c = *p++, whiteKingFile=NoRights, blackKingFile=NoRights;
17021 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
17022 if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
17023 if(board[0 ][i] == WhiteKing) whiteKingFile = i;
17025 if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
17026 whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
17027 if(whiteKingFile == NoRights || board[0][whiteKingFile] != WhiteUnicorn
17028 && board[0][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
17029 if(blackKingFile == NoRights || board[BOARD_HEIGHT-1][blackKingFile] != BlackUnicorn
17030 && board[BOARD_HEIGHT-1][blackKingFile] != BlackKing) blackKingFile = NoRights;
17033 for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
17034 board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
17035 board[CASTLING][2] = whiteKingFile;
17036 if(board[CASTLING][0] != NoRights) virgin[board[CASTLING][0]] |= VIRGIN_W;
17037 if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
17040 for(i=BOARD_LEFT; i<BOARD_RGHT && board[0][i]!=WhiteRook && i<whiteKingFile; i++);
17041 board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
17042 board[CASTLING][2] = whiteKingFile;
17043 if(board[CASTLING][1] != NoRights) virgin[board[CASTLING][1]] |= VIRGIN_W;
17044 if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
17047 for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
17048 board[CASTLING][3] = i != blackKingFile ? i : NoRights;
17049 board[CASTLING][5] = blackKingFile;
17050 if(board[CASTLING][3] != NoRights) virgin[board[CASTLING][3]] |= VIRGIN_B;
17051 if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
17054 for(i=BOARD_LEFT; i<BOARD_RGHT && board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
17055 board[CASTLING][4] = i != blackKingFile ? i : NoRights;
17056 board[CASTLING][5] = blackKingFile;
17057 if(board[CASTLING][4] != NoRights) virgin[board[CASTLING][4]] |= VIRGIN_B;
17058 if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
17061 default: /* FRC castlings */
17062 if(c >= 'a') { /* black rights */
17063 if(gameInfo.variant == VariantSChess) { virgin[c-AAA] |= VIRGIN_B; break; } // in S-Chess castlings are always kq, so just virginity
17064 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
17065 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
17066 if(i == BOARD_RGHT) break;
17067 board[CASTLING][5] = i;
17069 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
17070 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
17072 board[CASTLING][3] = c;
17074 board[CASTLING][4] = c;
17075 } else { /* white rights */
17076 if(gameInfo.variant == VariantSChess) { virgin[c-AAA-'A'+'a'] |= VIRGIN_W; break; } // in S-Chess castlings are always KQ
17077 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
17078 if(board[0][i] == WhiteKing) break;
17079 if(i == BOARD_RGHT) break;
17080 board[CASTLING][2] = i;
17081 c -= AAA - 'a' + 'A';
17082 if(board[0][c] >= WhiteKing) break;
17084 board[CASTLING][0] = c;
17086 board[CASTLING][1] = c;
17090 for(i=0; i<nrCastlingRights; i++)
17091 if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
17092 if(gameInfo.variant == VariantSChess) for(i=0; i<BOARD_FILES; i++) board[VIRGIN][i] = virgin[i];
17093 if (appData.debugMode) {
17094 fprintf(debugFP, "FEN castling rights:");
17095 for(i=0; i<nrCastlingRights; i++)
17096 fprintf(debugFP, " %d", board[CASTLING][i]);
17097 fprintf(debugFP, "\n");
17100 while(*p==' ') p++;
17103 /* read e.p. field in games that know e.p. capture */
17104 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
17105 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier && gameInfo.variant != VariantMakruk ) {
17107 p++; board[EP_STATUS] = EP_NONE;
17109 char c = *p++ - AAA;
17111 if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
17112 if(*p >= '0' && *p <='9') p++;
17113 board[EP_STATUS] = c;
17118 if(sscanf(p, "%d", &i) == 1) {
17119 FENrulePlies = i; /* 50-move ply counter */
17120 /* (The move number is still ignored) */
17127 EditPositionPasteFEN (char *fen)
17130 Board initial_position;
17132 if (!ParseFEN(initial_position, &blackPlaysFirst, fen)) {
17133 DisplayError(_("Bad FEN position in clipboard"), 0);
17136 int savedBlackPlaysFirst = blackPlaysFirst;
17137 EditPositionEvent();
17138 blackPlaysFirst = savedBlackPlaysFirst;
17139 CopyBoard(boards[0], initial_position);
17140 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
17141 EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
17142 DisplayBothClocks();
17143 DrawPosition(FALSE, boards[currentMove]);
17148 static char cseq[12] = "\\ ";
17151 set_cont_sequence (char *new_seq)
17156 // handle bad attempts to set the sequence
17158 return 0; // acceptable error - no debug
17160 len = strlen(new_seq);
17161 ret = (len > 0) && (len < sizeof(cseq));
17163 safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
17164 else if (appData.debugMode)
17165 fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
17170 reformat a source message so words don't cross the width boundary. internal
17171 newlines are not removed. returns the wrapped size (no null character unless
17172 included in source message). If dest is NULL, only calculate the size required
17173 for the dest buffer. lp argument indicats line position upon entry, and it's
17174 passed back upon exit.
17177 wrap (char *dest, char *src, int count, int width, int *lp)
17179 int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
17181 cseq_len = strlen(cseq);
17182 old_line = line = *lp;
17183 ansi = len = clen = 0;
17185 for (i=0; i < count; i++)
17187 if (src[i] == '\033')
17190 // if we hit the width, back up
17191 if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
17193 // store i & len in case the word is too long
17194 old_i = i, old_len = len;
17196 // find the end of the last word
17197 while (i && src[i] != ' ' && src[i] != '\n')
17203 // word too long? restore i & len before splitting it
17204 if ((old_i-i+clen) >= width)
17211 if (i && src[i-1] == ' ')
17214 if (src[i] != ' ' && src[i] != '\n')
17221 // now append the newline and continuation sequence
17226 strncpy(dest+len, cseq, cseq_len);
17234 dest[len] = src[i];
17238 if (src[i] == '\n')
17243 if (dest && appData.debugMode)
17245 fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
17246 count, width, line, len, *lp);
17247 show_bytes(debugFP, src, count);
17248 fprintf(debugFP, "\ndest: ");
17249 show_bytes(debugFP, dest, len);
17250 fprintf(debugFP, "\n");
17252 *lp = dest ? line : old_line;
17257 // [HGM] vari: routines for shelving variations
17258 Boolean modeRestore = FALSE;
17261 PushInner (int firstMove, int lastMove)
17263 int i, j, nrMoves = lastMove - firstMove;
17265 // push current tail of game on stack
17266 savedResult[storedGames] = gameInfo.result;
17267 savedDetails[storedGames] = gameInfo.resultDetails;
17268 gameInfo.resultDetails = NULL;
17269 savedFirst[storedGames] = firstMove;
17270 savedLast [storedGames] = lastMove;
17271 savedFramePtr[storedGames] = framePtr;
17272 framePtr -= nrMoves; // reserve space for the boards
17273 for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
17274 CopyBoard(boards[framePtr+i], boards[firstMove+i]);
17275 for(j=0; j<MOVE_LEN; j++)
17276 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
17277 for(j=0; j<2*MOVE_LEN; j++)
17278 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
17279 timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
17280 timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
17281 pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
17282 pvInfoList[firstMove+i-1].depth = 0;
17283 commentList[framePtr+i] = commentList[firstMove+i];
17284 commentList[firstMove+i] = NULL;
17288 forwardMostMove = firstMove; // truncate game so we can start variation
17292 PushTail (int firstMove, int lastMove)
17294 if(appData.icsActive) { // only in local mode
17295 forwardMostMove = currentMove; // mimic old ICS behavior
17298 if(storedGames >= MAX_VARIATIONS-2) return; // leave one for PV-walk
17300 PushInner(firstMove, lastMove);
17301 if(storedGames == 1) GreyRevert(FALSE);
17302 if(gameMode == PlayFromGameFile) gameMode = EditGame, modeRestore = TRUE;
17306 PopInner (Boolean annotate)
17309 char buf[8000], moveBuf[20];
17311 ToNrEvent(savedFirst[storedGames-1]); // sets currentMove
17312 storedGames--; // do this after ToNrEvent, to make sure HistorySet will refresh entire game after PopInner returns
17313 nrMoves = savedLast[storedGames] - currentMove;
17316 if(!WhiteOnMove(currentMove))
17317 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
17318 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
17319 for(i=currentMove; i<forwardMostMove; i++) {
17321 snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
17322 else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
17323 strcat(buf, moveBuf);
17324 if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
17325 if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
17329 for(i=1; i<=nrMoves; i++) { // copy last variation back
17330 CopyBoard(boards[currentMove+i], boards[framePtr+i]);
17331 for(j=0; j<MOVE_LEN; j++)
17332 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
17333 for(j=0; j<2*MOVE_LEN; j++)
17334 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
17335 timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
17336 timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
17337 pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
17338 if(commentList[currentMove+i]) free(commentList[currentMove+i]);
17339 commentList[currentMove+i] = commentList[framePtr+i];
17340 commentList[framePtr+i] = NULL;
17342 if(annotate) AppendComment(currentMove+1, buf, FALSE);
17343 framePtr = savedFramePtr[storedGames];
17344 gameInfo.result = savedResult[storedGames];
17345 if(gameInfo.resultDetails != NULL) {
17346 free(gameInfo.resultDetails);
17348 gameInfo.resultDetails = savedDetails[storedGames];
17349 forwardMostMove = currentMove + nrMoves;
17353 PopTail (Boolean annotate)
17355 if(appData.icsActive) return FALSE; // only in local mode
17356 if(!storedGames) return FALSE; // sanity
17357 CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
17359 PopInner(annotate);
17360 if(currentMove < forwardMostMove) ForwardEvent(); else
17361 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
17363 if(storedGames == 0) { GreyRevert(TRUE); if(modeRestore) modeRestore = FALSE, gameMode = PlayFromGameFile; }
17369 { // remove all shelved variations
17371 for(i=0; i<storedGames; i++) {
17372 if(savedDetails[i])
17373 free(savedDetails[i]);
17374 savedDetails[i] = NULL;
17376 for(i=framePtr; i<MAX_MOVES; i++) {
17377 if(commentList[i]) free(commentList[i]);
17378 commentList[i] = NULL;
17380 framePtr = MAX_MOVES-1;
17385 LoadVariation (int index, char *text)
17386 { // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
17387 char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
17388 int level = 0, move;
17390 if(gameMode != EditGame && gameMode != AnalyzeMode && gameMode != PlayFromGameFile) return;
17391 // first find outermost bracketing variation
17392 while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
17393 if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
17394 if(*p == '{') wait = '}'; else
17395 if(*p == '[') wait = ']'; else
17396 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
17397 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
17399 if(*p == wait) wait = NULLCHAR; // closing ]} found
17402 if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
17403 if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
17404 end[1] = NULLCHAR; // clip off comment beyond variation
17405 ToNrEvent(currentMove-1);
17406 PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
17407 // kludge: use ParsePV() to append variation to game
17408 move = currentMove;
17409 ParsePV(start, TRUE, TRUE);
17410 forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
17411 ClearPremoveHighlights();
17413 ToNrEvent(currentMove+1);