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, 2013, 2014 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);
63 # define EGBB_NAME "egbbdll64.dll"
65 # define EGBB_NAME "egbbdll.dll"
70 # include <sys/file.h>
75 # define EGBB_NAME "egbbso64.so"
77 # define EGBB_NAME "egbbso.so"
79 // kludge to allow Windows code in back-end by converting it to corresponding Linux code
81 # define HMODULE void *
82 # define LoadLibrary(x) dlopen(x, RTLD_LAZY)
83 # define GetProcAddress dlsym
93 #include <sys/types.h>
102 #else /* not STDC_HEADERS */
105 # else /* not HAVE_STRING_H */
106 # include <strings.h>
107 # endif /* not HAVE_STRING_H */
108 #endif /* not STDC_HEADERS */
111 # include <sys/fcntl.h>
112 #else /* not HAVE_SYS_FCNTL_H */
115 # endif /* HAVE_FCNTL_H */
116 #endif /* not HAVE_SYS_FCNTL_H */
118 #if TIME_WITH_SYS_TIME
119 # include <sys/time.h>
123 # include <sys/time.h>
129 #if defined(_amigados) && !defined(__GNUC__)
134 extern int gettimeofday(struct timeval *, struct timezone *);
142 #include "frontend.h"
149 #include "backendz.h"
150 #include "evalgraph.h"
151 #include "engineoutput.h"
155 # define _(s) gettext (s)
156 # define N_(s) gettext_noop (s)
157 # define T_(s) gettext(s)
170 int establish P((void));
171 void read_from_player P((InputSourceRef isr, VOIDSTAR closure,
172 char *buf, int count, int error));
173 void read_from_ics P((InputSourceRef isr, VOIDSTAR closure,
174 char *buf, int count, int error));
175 void SendToICS P((char *s));
176 void SendToICSDelayed P((char *s, long msdelay));
177 void SendMoveToICS P((ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar));
178 void HandleMachineMove P((char *message, ChessProgramState *cps));
179 int AutoPlayOneMove P((void));
180 int LoadGameOneMove P((ChessMove readAhead));
181 int LoadGameFromFile P((char *filename, int n, char *title, int useList));
182 int LoadPositionFromFile P((char *filename, int n, char *title));
183 int SavePositionToFile P((char *filename));
184 void MakeMove P((int fromX, int fromY, int toX, int toY, int promoChar));
185 void ShowMove P((int fromX, int fromY, int toX, int toY));
186 int FinishMove P((ChessMove moveType, int fromX, int fromY, int toX, int toY,
187 /*char*/int promoChar));
188 void BackwardInner P((int target));
189 void ForwardInner P((int target));
190 int Adjudicate P((ChessProgramState *cps));
191 void GameEnds P((ChessMove result, char *resultDetails, int whosays));
192 void EditPositionDone P((Boolean fakeRights));
193 void PrintOpponents P((FILE *fp));
194 void PrintPosition P((FILE *fp, int move));
195 void StartChessProgram P((ChessProgramState *cps));
196 void SendToProgram P((char *message, ChessProgramState *cps));
197 void SendMoveToProgram P((int moveNum, ChessProgramState *cps));
198 void ReceiveFromProgram P((InputSourceRef isr, VOIDSTAR closure,
199 char *buf, int count, int error));
200 void SendTimeControl P((ChessProgramState *cps,
201 int mps, long tc, int inc, int sd, int st));
202 char *TimeControlTagValue P((void));
203 void Attention P((ChessProgramState *cps));
204 void FeedMovesToProgram P((ChessProgramState *cps, int upto));
205 int ResurrectChessProgram P((void));
206 void DisplayComment P((int moveNumber, char *text));
207 void DisplayMove P((int moveNumber));
209 void ParseGameHistory P((char *game));
210 void ParseBoard12 P((char *string));
211 void KeepAlive P((void));
212 void StartClocks P((void));
213 void SwitchClocks P((int nr));
214 void StopClocks P((void));
215 void ResetClocks P((void));
216 char *PGNDate P((void));
217 void SetGameInfo P((void));
218 int RegisterMove P((void));
219 void MakeRegisteredMove P((void));
220 void TruncateGame P((void));
221 int looking_at P((char *, int *, char *));
222 void CopyPlayerNameIntoFileName P((char **, char *));
223 char *SavePart P((char *));
224 int SaveGameOldStyle P((FILE *));
225 int SaveGamePGN P((FILE *));
226 int CheckFlags P((void));
227 long NextTickLength P((long));
228 void CheckTimeControl P((void));
229 void show_bytes P((FILE *, char *, int));
230 int string_to_rating P((char *str));
231 void ParseFeatures P((char* args, ChessProgramState *cps));
232 void InitBackEnd3 P((void));
233 void FeatureDone P((ChessProgramState* cps, int val));
234 void InitChessProgram P((ChessProgramState *cps, int setup));
235 void OutputKibitz(int window, char *text);
236 int PerpetualChase(int first, int last);
237 int EngineOutputIsUp();
238 void InitDrawingSizes(int x, int y);
239 void NextMatchGame P((void));
240 int NextTourneyGame P((int nr, int *swap));
241 int Pairing P((int nr, int nPlayers, int *w, int *b, int *sync));
242 FILE *WriteTourneyFile P((char *results, FILE *f));
243 void DisplayTwoMachinesTitle P(());
244 static void ExcludeClick P((int index));
245 void ToggleSecond P((void));
246 void PauseEngine P((ChessProgramState *cps));
247 static int NonStandardBoardSize P((VariantClass v, int w, int h, int s));
250 extern void ConsoleCreate();
253 ChessProgramState *WhitePlayer();
254 int VerifyDisplayMode P(());
256 char *GetInfoFromComment( int, char * ); // [HGM] PV time: returns stripped comment
257 void InitEngineUCI( const char * iniDir, ChessProgramState * cps ); // [HGM] moved here from winboard.c
258 char *ProbeBook P((int moveNr, char *book)); // [HGM] book: returns a book move
259 char *SendMoveToBookUser P((int nr, ChessProgramState *cps, int initial)); // [HGM] book
260 void ics_update_width P((int new_width));
261 extern char installDir[MSG_SIZ];
262 VariantClass startVariant; /* [HGM] nicks: initial variant */
265 extern int tinyLayout, smallLayout;
266 ChessProgramStats programStats;
267 char lastPV[2][2*MSG_SIZ]; /* [HGM] pv: last PV in thinking output of each engine */
269 static int exiting = 0; /* [HGM] moved to top */
270 static int setboardSpoiledMachineBlack = 0 /*, errorExitFlag = 0*/;
271 int startedFromPositionFile = FALSE; Board filePosition; /* [HGM] loadPos */
272 Board partnerBoard; /* [HGM] bughouse: for peeking at partner game */
273 int partnerHighlight[2];
274 Boolean partnerBoardValid = 0;
275 char partnerStatus[MSG_SIZ];
277 Boolean originalFlip;
278 Boolean twoBoards = 0;
279 char endingGame = 0; /* [HGM] crash: flag to prevent recursion of GameEnds() */
280 int whiteNPS, blackNPS; /* [HGM] nps: for easily making clocks aware of NPS */
281 VariantClass currentlyInitializedVariant; /* [HGM] variantswitch */
282 int lastIndex = 0; /* [HGM] autoinc: last game/position used in match mode */
283 Boolean connectionAlive;/* [HGM] alive: ICS connection status from probing */
284 int opponentKibitzes;
285 int lastSavedGame; /* [HGM] save: ID of game */
286 char chatPartner[MAX_CHAT][MSG_SIZ]; /* [HGM] chat: list of chatting partners */
287 extern int chatCount;
289 char marker[BOARD_RANKS][BOARD_FILES]; /* [HGM] marks for target squares */
290 char legal[BOARD_RANKS][BOARD_FILES]; /* [HGM] legal target squares */
291 char lastMsg[MSG_SIZ];
292 char lastTalker[MSG_SIZ];
293 ChessSquare pieceSweep = EmptySquare;
294 ChessSquare promoSweep = EmptySquare, defaultPromoChoice;
295 int promoDefaultAltered;
296 int keepInfo = 0; /* [HGM] to protect PGN tags in auto-step game analysis */
297 static int initPing = -1;
298 int border; /* [HGM] width of board rim, needed to size seek graph */
300 /* States for ics_getting_history */
302 #define H_REQUESTED 1
303 #define H_GOT_REQ_HEADER 2
304 #define H_GOT_UNREQ_HEADER 3
305 #define H_GETTING_MOVES 4
306 #define H_GOT_UNWANTED_HEADER 5
308 /* whosays values for GameEnds */
317 /* Maximum number of games in a cmail message */
318 #define CMAIL_MAX_GAMES 20
320 /* Different types of move when calling RegisterMove */
322 #define CMAIL_RESIGN 1
324 #define CMAIL_ACCEPT 3
326 /* Different types of result to remember for each game */
327 #define CMAIL_NOT_RESULT 0
328 #define CMAIL_OLD_RESULT 1
329 #define CMAIL_NEW_RESULT 2
331 /* Telnet protocol constants */
342 safeStrCpy (char *dst, const char *src, size_t count)
345 assert( dst != NULL );
346 assert( src != NULL );
349 for(i=0; i<count; i++) if((dst[i] = src[i]) == NULLCHAR) break;
350 if( i == count && dst[count-1] != NULLCHAR)
352 dst[ count-1 ] = '\0'; // make sure incomplete copy still null-terminated
353 if(appData.debugMode)
354 fprintf(debugFP, "safeStrCpy: copying %s into %s didn't work, not enough space %d\n",src,dst, (int)count);
360 /* Some compiler can't cast u64 to double
361 * This function do the job for us:
363 * We use the highest bit for cast, this only
364 * works if the highest bit is not
365 * in use (This should not happen)
367 * We used this for all compiler
370 u64ToDouble (u64 value)
373 u64 tmp = value & u64Const(0x7fffffffffffffff);
374 r = (double)(s64)tmp;
375 if (value & u64Const(0x8000000000000000))
376 r += 9.2233720368547758080e18; /* 2^63 */
380 /* Fake up flags for now, as we aren't keeping track of castling
381 availability yet. [HGM] Change of logic: the flag now only
382 indicates the type of castlings allowed by the rule of the game.
383 The actual rights themselves are maintained in the array
384 castlingRights, as part of the game history, and are not probed
390 int flags = F_ALL_CASTLE_OK;
391 if ((index % 2) == 0) flags |= F_WHITE_ON_MOVE;
392 switch (gameInfo.variant) {
394 flags &= ~F_ALL_CASTLE_OK;
395 case VariantGiveaway: // [HGM] moved this case label one down: seems Giveaway does have castling on ICC!
396 flags |= F_IGNORE_CHECK;
398 flags |= F_MANDATORY_CAPTURE; //[HGM] losers: sets flag so TestLegality rejects non-capts if capts exist
401 flags |= F_IGNORE_CHECK | F_ATOMIC_CAPTURE;
403 case VariantKriegspiel:
404 flags |= F_KRIEGSPIEL_CAPTURE;
406 case VariantCapaRandom:
407 case VariantFischeRandom:
408 flags |= F_FRC_TYPE_CASTLING; /* [HGM] enable this through flag */
409 case VariantNoCastle:
410 case VariantShatranj:
415 flags &= ~F_ALL_CASTLE_OK;
418 case VariantChuChess:
420 flags |= F_NULL_MOVE;
425 if(appData.fischerCastling) flags |= F_FRC_TYPE_CASTLING, flags &= ~F_ALL_CASTLE_OK; // [HGM] fischer
429 FILE *gameFileFP, *debugFP, *serverFP;
430 char *currentDebugFile; // [HGM] debug split: to remember name
433 [AS] Note: sometimes, the sscanf() function is used to parse the input
434 into a fixed-size buffer. Because of this, we must be prepared to
435 receive strings as long as the size of the input buffer, which is currently
436 set to 4K for Windows and 8K for the rest.
437 So, we must either allocate sufficiently large buffers here, or
438 reduce the size of the input buffer in the input reading part.
441 char cmailMove[CMAIL_MAX_GAMES][MOVE_LEN], cmailMsg[MSG_SIZ];
442 char bookOutput[MSG_SIZ*10], thinkOutput[MSG_SIZ*10], lastHint[MSG_SIZ];
443 char thinkOutput1[MSG_SIZ*10];
445 ChessProgramState first, second, pairing;
447 /* premove variables */
450 int premoveFromX = 0;
451 int premoveFromY = 0;
452 int premovePromoChar = 0;
454 Boolean alarmSounded;
455 /* end premove variables */
457 char *ics_prefix = "$";
458 enum ICS_TYPE ics_type = ICS_GENERIC;
460 int currentMove = 0, forwardMostMove = 0, backwardMostMove = 0;
461 int pauseExamForwardMostMove = 0;
462 int nCmailGames = 0, nCmailResults = 0, nCmailMovesRegistered = 0;
463 int cmailMoveRegistered[CMAIL_MAX_GAMES], cmailResult[CMAIL_MAX_GAMES];
464 int cmailMsgLoaded = FALSE, cmailMailedMove = FALSE;
465 int cmailOldMove = -1, firstMove = TRUE, flipView = FALSE;
466 int blackPlaysFirst = FALSE, startedFromSetupPosition = FALSE;
467 int searchTime = 0, pausing = FALSE, pauseExamInvalid = FALSE;
468 int whiteFlag = FALSE, blackFlag = FALSE;
469 int userOfferedDraw = FALSE;
470 int ics_user_moved = 0, ics_gamenum = -1, ics_getting_history = H_FALSE;
471 int matchMode = FALSE, hintRequested = FALSE, bookRequested = FALSE;
472 int cmailMoveType[CMAIL_MAX_GAMES];
473 long ics_clock_paused = 0;
474 ProcRef icsPR = NoProc, cmailPR = NoProc;
475 InputSourceRef telnetISR = NULL, fromUserISR = NULL, cmailISR = NULL;
476 GameMode gameMode = BeginningOfGame;
477 char moveList[MAX_MOVES][MOVE_LEN], parseList[MAX_MOVES][MOVE_LEN * 2];
478 char *commentList[MAX_MOVES], *cmailCommentList[CMAIL_MAX_GAMES];
479 ChessProgramStats_Move pvInfoList[MAX_MOVES]; /* [AS] Info about engine thinking */
480 int hiddenThinkOutputState = 0; /* [AS] */
481 int adjudicateLossThreshold = 0; /* [AS] Automatic adjudication */
482 int adjudicateLossPlies = 6;
483 char white_holding[64], black_holding[64];
484 TimeMark lastNodeCountTime;
485 long lastNodeCount=0;
486 int shiftKey, controlKey; // [HGM] set by mouse handler
488 int have_sent_ICS_logon = 0;
490 int suddenDeath, whiteStartMove, blackStartMove; /* [HGM] for implementation of 'any per time' sessions, as in first part of byoyomi TC */
491 long whiteTimeRemaining, blackTimeRemaining, timeControl, timeIncrement, lastWhite, lastBlack, activePartnerTime;
492 Boolean adjustedClock;
493 long timeControl_2; /* [AS] Allow separate time controls */
494 char *fullTimeControlString = NULL, *nextSession, *whiteTC, *blackTC, activePartner; /* [HGM] secondary TC: merge of MPS, TC and inc */
495 long timeRemaining[2][MAX_MOVES];
496 int matchGame = 0, nextGame = 0, roundNr = 0;
497 Boolean waitingForGame = FALSE, startingEngine = FALSE;
498 TimeMark programStartTime, pauseStart;
499 char ics_handle[MSG_SIZ];
500 int have_set_title = 0;
502 /* animateTraining preserves the state of appData.animate
503 * when Training mode is activated. This allows the
504 * response to be animated when appData.animate == TRUE and
505 * appData.animateDragging == TRUE.
507 Boolean animateTraining;
513 Board boards[MAX_MOVES];
514 /* [HGM] Following 7 needed for accurate legality tests: */
515 signed char castlingRank[BOARD_FILES]; // and corresponding ranks
516 signed char initialRights[BOARD_FILES];
517 int nrCastlingRights; // For TwoKings, or to implement castling-unknown status
518 int initialRulePlies, FENrulePlies;
519 FILE *serverMoves = NULL; // next two for broadcasting (/serverMoves option)
521 Boolean shuffleOpenings;
522 int mute; // mute all sounds
524 // [HGM] vari: next 12 to save and restore variations
525 #define MAX_VARIATIONS 10
526 int framePtr = MAX_MOVES-1; // points to free stack entry
528 int savedFirst[MAX_VARIATIONS];
529 int savedLast[MAX_VARIATIONS];
530 int savedFramePtr[MAX_VARIATIONS];
531 char *savedDetails[MAX_VARIATIONS];
532 ChessMove savedResult[MAX_VARIATIONS];
534 void PushTail P((int firstMove, int lastMove));
535 Boolean PopTail P((Boolean annotate));
536 void PushInner P((int firstMove, int lastMove));
537 void PopInner P((Boolean annotate));
538 void CleanupTail P((void));
540 ChessSquare FIDEArray[2][BOARD_FILES] = {
541 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
542 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
543 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
544 BlackKing, BlackBishop, BlackKnight, BlackRook }
547 ChessSquare twoKingsArray[2][BOARD_FILES] = {
548 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
549 WhiteKing, WhiteKing, WhiteKnight, WhiteRook },
550 { BlackRook, BlackKnight, BlackBishop, BlackQueen,
551 BlackKing, BlackKing, BlackKnight, BlackRook }
554 ChessSquare KnightmateArray[2][BOARD_FILES] = {
555 { WhiteRook, WhiteMan, WhiteBishop, WhiteQueen,
556 WhiteUnicorn, WhiteBishop, WhiteMan, WhiteRook },
557 { BlackRook, BlackMan, BlackBishop, BlackQueen,
558 BlackUnicorn, BlackBishop, BlackMan, BlackRook }
561 ChessSquare SpartanArray[2][BOARD_FILES] = {
562 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
563 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
564 { BlackAlfil, BlackMarshall, BlackKing, BlackDragon,
565 BlackDragon, BlackKing, BlackAngel, BlackAlfil }
568 ChessSquare fairyArray[2][BOARD_FILES] = { /* [HGM] Queen side differs from King side */
569 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen,
570 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
571 { BlackCardinal, BlackAlfil, BlackMarshall, BlackAngel,
572 BlackKing, BlackMarshall, BlackAlfil, BlackCardinal }
575 ChessSquare ShatranjArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
576 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteKing,
577 WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
578 { BlackRook, BlackKnight, BlackAlfil, BlackKing,
579 BlackFerz, BlackAlfil, BlackKnight, BlackRook }
582 ChessSquare makrukArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
583 { WhiteRook, WhiteKnight, WhiteMan, WhiteKing,
584 WhiteFerz, WhiteMan, WhiteKnight, WhiteRook },
585 { BlackRook, BlackKnight, BlackMan, BlackFerz,
586 BlackKing, BlackMan, BlackKnight, BlackRook }
589 ChessSquare aseanArray[2][BOARD_FILES] = { /* [HGM] (movGen knows about Shatranj Q and P) */
590 { WhiteRook, WhiteKnight, WhiteMan, WhiteFerz,
591 WhiteKing, WhiteMan, WhiteKnight, WhiteRook },
592 { BlackRook, BlackKnight, BlackMan, BlackFerz,
593 BlackKing, BlackMan, BlackKnight, BlackRook }
596 ChessSquare lionArray[2][BOARD_FILES] = {
597 { WhiteRook, WhiteLion, WhiteBishop, WhiteQueen,
598 WhiteKing, WhiteBishop, WhiteKnight, WhiteRook },
599 { BlackRook, BlackLion, BlackBishop, BlackQueen,
600 BlackKing, BlackBishop, BlackKnight, BlackRook }
604 #if (BOARD_FILES>=10)
605 ChessSquare ShogiArray[2][BOARD_FILES] = {
606 { WhiteQueen, WhiteKnight, WhiteFerz, WhiteWazir,
607 WhiteKing, WhiteWazir, WhiteFerz, WhiteKnight, WhiteQueen },
608 { BlackQueen, BlackKnight, BlackFerz, BlackWazir,
609 BlackKing, BlackWazir, BlackFerz, BlackKnight, BlackQueen }
612 ChessSquare XiangqiArray[2][BOARD_FILES] = {
613 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteFerz,
614 WhiteWazir, WhiteFerz, WhiteAlfil, WhiteKnight, WhiteRook },
615 { BlackRook, BlackKnight, BlackAlfil, BlackFerz,
616 BlackWazir, BlackFerz, BlackAlfil, BlackKnight, BlackRook }
619 ChessSquare CapablancaArray[2][BOARD_FILES] = {
620 { WhiteRook, WhiteKnight, WhiteAngel, WhiteBishop, WhiteQueen,
621 WhiteKing, WhiteBishop, WhiteMarshall, WhiteKnight, WhiteRook },
622 { BlackRook, BlackKnight, BlackAngel, BlackBishop, BlackQueen,
623 BlackKing, BlackBishop, BlackMarshall, BlackKnight, BlackRook }
626 ChessSquare GreatArray[2][BOARD_FILES] = {
627 { WhiteDragon, WhiteKnight, WhiteAlfil, WhiteGrasshopper, WhiteKing,
628 WhiteSilver, WhiteCardinal, WhiteAlfil, WhiteKnight, WhiteDragon },
629 { BlackDragon, BlackKnight, BlackAlfil, BlackGrasshopper, BlackKing,
630 BlackSilver, BlackCardinal, BlackAlfil, BlackKnight, BlackDragon },
633 ChessSquare JanusArray[2][BOARD_FILES] = {
634 { WhiteRook, WhiteAngel, WhiteKnight, WhiteBishop, WhiteKing,
635 WhiteQueen, WhiteBishop, WhiteKnight, WhiteAngel, WhiteRook },
636 { BlackRook, BlackAngel, BlackKnight, BlackBishop, BlackKing,
637 BlackQueen, BlackBishop, BlackKnight, BlackAngel, BlackRook }
640 ChessSquare GrandArray[2][BOARD_FILES] = {
641 { EmptySquare, WhiteKnight, WhiteBishop, WhiteQueen, WhiteKing,
642 WhiteMarshall, WhiteAngel, WhiteBishop, WhiteKnight, EmptySquare },
643 { EmptySquare, BlackKnight, BlackBishop, BlackQueen, BlackKing,
644 BlackMarshall, BlackAngel, BlackBishop, BlackKnight, EmptySquare }
647 ChessSquare ChuChessArray[2][BOARD_FILES] = {
648 { WhiteMan, WhiteKnight, WhiteBishop, WhiteCardinal, WhiteLion,
649 WhiteQueen, WhiteDragon, WhiteBishop, WhiteKnight, WhiteMan },
650 { BlackMan, BlackKnight, BlackBishop, BlackDragon, BlackQueen,
651 BlackLion, BlackCardinal, BlackBishop, BlackKnight, BlackMan }
655 ChessSquare GothicArray[2][BOARD_FILES] = {
656 { WhiteRook, WhiteKnight, WhiteBishop, WhiteQueen, WhiteMarshall,
657 WhiteKing, WhiteAngel, WhiteBishop, WhiteKnight, WhiteRook },
658 { BlackRook, BlackKnight, BlackBishop, BlackQueen, BlackMarshall,
659 BlackKing, BlackAngel, BlackBishop, BlackKnight, BlackRook }
662 #define GothicArray CapablancaArray
666 ChessSquare FalconArray[2][BOARD_FILES] = {
667 { WhiteRook, WhiteKnight, WhiteBishop, WhiteFalcon, WhiteQueen,
668 WhiteKing, WhiteFalcon, WhiteBishop, WhiteKnight, WhiteRook },
669 { BlackRook, BlackKnight, BlackBishop, BlackFalcon, BlackQueen,
670 BlackKing, BlackFalcon, BlackBishop, BlackKnight, BlackRook }
673 #define FalconArray CapablancaArray
676 #else // !(BOARD_FILES>=10)
677 #define XiangqiPosition FIDEArray
678 #define CapablancaArray FIDEArray
679 #define GothicArray FIDEArray
680 #define GreatArray FIDEArray
681 #endif // !(BOARD_FILES>=10)
683 #if (BOARD_FILES>=12)
684 ChessSquare CourierArray[2][BOARD_FILES] = {
685 { WhiteRook, WhiteKnight, WhiteAlfil, WhiteBishop, WhiteMan, WhiteKing,
686 WhiteFerz, WhiteWazir, WhiteBishop, WhiteAlfil, WhiteKnight, WhiteRook },
687 { BlackRook, BlackKnight, BlackAlfil, BlackBishop, BlackMan, BlackKing,
688 BlackFerz, BlackWazir, BlackBishop, BlackAlfil, BlackKnight, BlackRook }
690 ChessSquare ChuArray[6][BOARD_FILES] = {
691 { WhiteLance, WhiteUnicorn, WhiteMan, WhiteFerz, WhiteWazir, WhiteKing,
692 WhiteAlfil, WhiteWazir, WhiteFerz, WhiteMan, WhiteUnicorn, WhiteLance },
693 { BlackLance, BlackUnicorn, BlackMan, BlackFerz, BlackWazir, BlackAlfil,
694 BlackKing, BlackWazir, BlackFerz, BlackMan, BlackUnicorn, BlackLance },
695 { WhiteCannon, EmptySquare, WhiteBishop, EmptySquare, WhiteNightrider, WhiteMarshall,
696 WhiteAngel, WhiteNightrider, EmptySquare, WhiteBishop, EmptySquare, WhiteCannon },
697 { BlackCannon, EmptySquare, BlackBishop, EmptySquare, BlackNightrider, BlackAngel,
698 BlackMarshall, BlackNightrider, EmptySquare, BlackBishop, EmptySquare, BlackCannon },
699 { WhiteFalcon, WhiteSilver, WhiteRook, WhiteCardinal, WhiteDragon, WhiteLion,
700 WhiteQueen, WhiteDragon, WhiteCardinal, WhiteRook, WhiteSilver, WhiteFalcon },
701 { BlackFalcon, BlackSilver, BlackRook, BlackCardinal, BlackDragon, BlackQueen,
702 BlackLion, BlackDragon, BlackCardinal, BlackRook, BlackSilver, BlackFalcon }
704 #else // !(BOARD_FILES>=12)
705 #define CourierArray CapablancaArray
706 #define ChuArray CapablancaArray
707 #endif // !(BOARD_FILES>=12)
710 Board initialPosition;
713 /* Convert str to a rating. Checks for special cases of "----",
715 "++++", etc. Also strips ()'s */
717 string_to_rating (char *str)
719 while(*str && !isdigit(*str)) ++str;
721 return 0; /* One of the special "no rating" cases */
729 /* Init programStats */
730 programStats.movelist[0] = 0;
731 programStats.depth = 0;
732 programStats.nr_moves = 0;
733 programStats.moves_left = 0;
734 programStats.nodes = 0;
735 programStats.time = -1; // [HGM] PGNtime: make invalid to recognize engine output
736 programStats.score = 0;
737 programStats.got_only_move = 0;
738 programStats.got_fail = 0;
739 programStats.line_is_book = 0;
744 { // [HGM] moved some code here from InitBackend1 that has to be done after both engines have contributed their settings
745 if (appData.firstPlaysBlack) {
746 first.twoMachinesColor = "black\n";
747 second.twoMachinesColor = "white\n";
749 first.twoMachinesColor = "white\n";
750 second.twoMachinesColor = "black\n";
753 first.other = &second;
754 second.other = &first;
757 if(appData.timeOddsMode) {
758 norm = appData.timeOdds[0];
759 if(norm > appData.timeOdds[1]) norm = appData.timeOdds[1];
761 first.timeOdds = appData.timeOdds[0]/norm;
762 second.timeOdds = appData.timeOdds[1]/norm;
765 if(programVersion) free(programVersion);
766 if (appData.noChessProgram) {
767 programVersion = (char*) malloc(5 + strlen(PACKAGE_STRING));
768 sprintf(programVersion, "%s", PACKAGE_STRING);
770 /* [HGM] tidy: use tidy name, in stead of full pathname (which was probably a bug due to / vs \ ) */
771 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
772 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
777 UnloadEngine (ChessProgramState *cps)
779 /* Kill off first chess program */
780 if (cps->isr != NULL)
781 RemoveInputSource(cps->isr);
784 if (cps->pr != NoProc) {
786 DoSleep( appData.delayBeforeQuit );
787 SendToProgram("quit\n", cps);
788 DestroyChildProcess(cps->pr, 4 + cps->useSigterm);
791 if(appData.debugMode) fprintf(debugFP, "Unload %s\n", cps->which);
795 ClearOptions (ChessProgramState *cps)
798 cps->nrOptions = cps->comboCnt = 0;
799 for(i=0; i<MAX_OPTIONS; i++) {
800 cps->option[i].min = cps->option[i].max = cps->option[i].value = 0;
801 cps->option[i].textValue = 0;
805 char *engineNames[] = {
806 /* TRANSLATORS: "first" is the first of possible two chess engines. It is inserted into strings
807 such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
809 /* TRANSLATORS: "second" is the second of possible two chess engines. It is inserted into strings
810 such as "%s engine" / "%s chess program" / "%s machine" - all meaning the same thing */
815 InitEngine (ChessProgramState *cps, int n)
816 { // [HGM] all engine initialiation put in a function that does one engine
820 cps->which = engineNames[n];
821 cps->maybeThinking = FALSE;
825 cps->sendDrawOffers = 1;
827 cps->program = appData.chessProgram[n];
828 cps->host = appData.host[n];
829 cps->dir = appData.directory[n];
830 cps->initString = appData.engInitString[n];
831 cps->computerString = appData.computerString[n];
832 cps->useSigint = TRUE;
833 cps->useSigterm = TRUE;
834 cps->reuse = appData.reuse[n];
835 cps->nps = appData.NPS[n]; // [HGM] nps: copy nodes per second
836 cps->useSetboard = FALSE;
838 cps->usePing = FALSE;
841 cps->usePlayother = FALSE;
842 cps->useColors = TRUE;
843 cps->useUsermove = FALSE;
844 cps->sendICS = FALSE;
845 cps->sendName = appData.icsActive;
846 cps->sdKludge = FALSE;
847 cps->stKludge = FALSE;
848 if(cps->tidy == NULL) cps->tidy = (char*) malloc(MSG_SIZ);
849 TidyProgramName(cps->program, cps->host, cps->tidy);
851 ASSIGN(cps->variants, appData.noChessProgram ? "" : appData.variant);
852 cps->analysisSupport = 2; /* detect */
853 cps->analyzing = FALSE;
854 cps->initDone = FALSE;
856 cps->pseudo = appData.pseudo[n];
858 /* New features added by Tord: */
859 cps->useFEN960 = FALSE;
860 cps->useOOCastle = TRUE;
861 /* End of new features added by Tord. */
862 cps->fenOverride = appData.fenOverride[n];
864 /* [HGM] time odds: set factor for each machine */
865 cps->timeOdds = appData.timeOdds[n];
867 /* [HGM] secondary TC: how to handle sessions that do not fit in 'level'*/
868 cps->accumulateTC = appData.accumulateTC[n];
869 cps->maxNrOfSessions = 1;
874 cps->drawDepth = appData.drawDepth[n];
875 cps->supportsNPS = UNKNOWN;
876 cps->memSize = FALSE;
877 cps->maxCores = FALSE;
878 ASSIGN(cps->egtFormats, "");
881 cps->optionSettings = appData.engOptions[n];
883 cps->scoreIsAbsolute = appData.scoreIsAbsolute[n]; /* [AS] */
884 cps->isUCI = appData.isUCI[n]; /* [AS] */
885 cps->hasOwnBookUCI = appData.hasOwnBookUCI[n]; /* [AS] */
888 if (appData.protocolVersion[n] > PROTOVER
889 || appData.protocolVersion[n] < 1)
894 len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"),
895 appData.protocolVersion[n]);
896 if( (len >= MSG_SIZ) && appData.debugMode )
897 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
899 DisplayFatalError(buf, 0, 2);
903 cps->protocolVersion = appData.protocolVersion[n];
906 InitEngineUCI( installDir, cps ); // [HGM] moved here from winboard.c, to make available in xboard
907 ParseFeatures(appData.featureDefaults, cps);
910 ChessProgramState *savCps;
918 if(WaitForEngine(savCps, LoadEngine)) return;
919 CommonEngineInit(); // recalculate time odds
920 if(gameInfo.variant != StringToVariant(appData.variant)) {
921 // we changed variant when loading the engine; this forces us to reset
922 Reset(TRUE, savCps != &first);
923 oldMode = BeginningOfGame; // to prevent restoring old mode
925 InitChessProgram(savCps, FALSE);
926 if(gameMode == EditGame) SendToProgram("force\n", savCps); // in EditGame mode engine must be in force mode
927 DisplayMessage("", "");
928 if (startedFromSetupPosition) SendBoard(savCps, backwardMostMove);
929 for (i = backwardMostMove; i < currentMove; i++) SendMoveToProgram(i, savCps);
932 if(oldMode == AnalyzeMode) AnalyzeModeEvent();
936 ReplaceEngine (ChessProgramState *cps, int n)
938 oldMode = gameMode; // remember mode, so it can be restored after loading sequence is complete
940 if(oldMode != BeginningOfGame) EditGameEvent();
943 appData.noChessProgram = FALSE;
944 appData.clockMode = TRUE;
947 if(n) return; // only startup first engine immediately; second can wait
948 savCps = cps; // parameter to LoadEngine passed as globals, to allow scheduled calling :-(
952 extern char *engineName, *engineDir, *engineChoice, *engineLine, *nickName, *params;
953 extern Boolean isUCI, hasBook, storeVariant, v1, addToList, useNick;
955 static char resetOptions[] =
956 "-reuse -firstIsUCI false -firstHasOwnBookUCI true -firstTimeOdds 1 "
957 "-firstInitString \"" INIT_STRING "\" -firstComputerString \"" COMPUTER_STRING "\" "
958 "-firstFeatures \"\" -firstLogo \"\" -firstAccumulateTC 1 -fd \".\" "
959 "-firstOptions \"\" -firstNPS -1 -fn \"\" -firstScoreAbs false";
962 FloatToFront(char **list, char *engineLine)
964 char buf[MSG_SIZ], tidy[MSG_SIZ], *p = buf, *q, *r = buf;
966 if(appData.recentEngines <= 0) return;
967 TidyProgramName(engineLine, "localhost", tidy+1);
968 tidy[0] = buf[0] = '\n'; strcat(tidy, "\n");
969 strncpy(buf+1, *list, MSG_SIZ-50);
970 if(p = strstr(buf, tidy)) { // tidy name appears in list
971 q = strchr(++p, '\n'); if(q == NULL) return; // malformed, don't touch
972 while(*p++ = *++q); // squeeze out
974 strcat(tidy, buf+1); // put list behind tidy name
975 p = tidy + 1; while(q = strchr(p, '\n')) i++, r = p, p = q + 1; // count entries in new list
976 if(i > appData.recentEngines) *r = NULLCHAR; // if maximum rached, strip off last
977 ASSIGN(*list, tidy+1);
980 char *insert, *wbOptions; // point in ChessProgramNames were we should insert new engine
983 Load (ChessProgramState *cps, int i)
985 char *p, *q, buf[MSG_SIZ], command[MSG_SIZ], buf2[MSG_SIZ], buf3[MSG_SIZ], jar;
986 if(engineLine && engineLine[0]) { // an engine was selected from the combo box
987 snprintf(buf, MSG_SIZ, "-fcp %s", engineLine);
988 SwapEngines(i); // kludge to parse -f* / -first* like it is -s* / -second*
989 ParseArgsFromString(resetOptions); appData.pvSAN[0] = FALSE;
990 FREE(appData.fenOverride[0]); appData.fenOverride[0] = NULL;
991 appData.firstProtocolVersion = PROTOVER;
992 ParseArgsFromString(buf);
994 ReplaceEngine(cps, i);
995 FloatToFront(&appData.recentEngineList, engineLine);
999 while(q = strchr(p, SLASH)) p = q+1;
1000 if(*p== NULLCHAR) { DisplayError(_("You did not specify the engine executable"), 0); return; }
1001 if(engineDir[0] != NULLCHAR) {
1002 ASSIGN(appData.directory[i], engineDir); p = engineName;
1003 } else if(p != engineName) { // derive directory from engine path, when not given
1005 ASSIGN(appData.directory[i], engineName);
1007 if(SLASH == '/' && p - engineName > 1) *(p -= 2) = '.'; // for XBoard use ./exeName as command after split!
1008 } else { ASSIGN(appData.directory[i], "."); }
1009 jar = (strstr(p, ".jar") == p + strlen(p) - 4);
1011 if(strchr(p, ' ') && !strchr(p, '"')) snprintf(buf2, MSG_SIZ, "\"%s\"", p), p = buf2; // quote if it contains spaces
1012 snprintf(command, MSG_SIZ, "%s %s", p, params);
1015 if(jar) { snprintf(buf3, MSG_SIZ, "java -jar %s", p); p = buf3; }
1016 ASSIGN(appData.chessProgram[i], p);
1017 appData.isUCI[i] = isUCI;
1018 appData.protocolVersion[i] = v1 ? 1 : PROTOVER;
1019 appData.hasOwnBookUCI[i] = hasBook;
1020 if(!nickName[0]) useNick = FALSE;
1021 if(useNick) ASSIGN(appData.pgnName[i], nickName);
1025 q = firstChessProgramNames;
1026 if(nickName[0]) snprintf(buf, MSG_SIZ, "\"%s\" -fcp ", nickName); else buf[0] = NULLCHAR;
1027 quote = strchr(p, '"') ? '\'' : '"'; // use single quotes around engine command if it contains double quotes
1028 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), "%c%s%c -fd \"%s\"%s%s%s%s%s%s%s%s\n",
1029 quote, p, quote, appData.directory[i],
1030 useNick ? " -fn \"" : "",
1031 useNick ? nickName : "",
1032 useNick ? "\"" : "",
1033 v1 ? " -firstProtocolVersion 1" : "",
1034 hasBook ? "" : " -fNoOwnBookUCI",
1035 isUCI ? (isUCI == TRUE ? " -fUCI" : gameInfo.variant == VariantShogi ? " -fUSI" : " -fUCCI") : "",
1036 storeVariant ? " -variant " : "",
1037 storeVariant ? VariantName(gameInfo.variant) : "");
1038 if(wbOptions && wbOptions[0]) snprintf(buf+strlen(buf)-1, MSG_SIZ-strlen(buf), " %s\n", wbOptions);
1039 firstChessProgramNames = malloc(len = strlen(q) + strlen(buf) + 1);
1040 if(insert != q) insert[-1] = NULLCHAR;
1041 snprintf(firstChessProgramNames, len, "%s\n%s%s", q, buf, insert);
1043 FloatToFront(&appData.recentEngineList, buf);
1045 ReplaceEngine(cps, i);
1051 int matched, min, sec;
1053 * Parse timeControl resource
1055 if (!ParseTimeControl(appData.timeControl, appData.timeIncrement,
1056 appData.movesPerSession)) {
1058 snprintf(buf, sizeof(buf), _("bad timeControl option %s"), appData.timeControl);
1059 DisplayFatalError(buf, 0, 2);
1063 * Parse searchTime resource
1065 if (*appData.searchTime != NULLCHAR) {
1066 matched = sscanf(appData.searchTime, "%d:%d", &min, &sec);
1068 searchTime = min * 60;
1069 } else if (matched == 2) {
1070 searchTime = min * 60 + sec;
1073 snprintf(buf, sizeof(buf), _("bad searchTime option %s"), appData.searchTime);
1074 DisplayFatalError(buf, 0, 2);
1083 ShowThinkingEvent(); // [HGM] thinking: make sure post/nopost state is set according to options
1084 startVariant = StringToVariant(appData.variant); // [HGM] nicks: remember original variant
1086 GetTimeMark(&programStartTime);
1087 srandom((programStartTime.ms + 1000*programStartTime.sec)*0x1001001); // [HGM] book: makes sure random is unpredictabe to msec level
1088 appData.seedBase = random() + (random()<<15);
1089 pauseStart = programStartTime; pauseStart.sec -= 100; // [HGM] matchpause: fake a pause that has long since ended
1091 ClearProgramStats();
1092 programStats.ok_to_send = 1;
1093 programStats.seen_stat = 0;
1096 * Initialize game list
1102 * Internet chess server status
1104 if (appData.icsActive) {
1105 appData.matchMode = FALSE;
1106 appData.matchGames = 0;
1108 appData.noChessProgram = !appData.zippyPlay;
1110 appData.zippyPlay = FALSE;
1111 appData.zippyTalk = FALSE;
1112 appData.noChessProgram = TRUE;
1114 if (*appData.icsHelper != NULLCHAR) {
1115 appData.useTelnet = TRUE;
1116 appData.telnetProgram = appData.icsHelper;
1119 appData.zippyTalk = appData.zippyPlay = FALSE;
1122 /* [AS] Initialize pv info list [HGM] and game state */
1126 for( i=0; i<=framePtr; i++ ) {
1127 pvInfoList[i].depth = -1;
1128 boards[i][EP_STATUS] = EP_NONE;
1129 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
1135 /* [AS] Adjudication threshold */
1136 adjudicateLossThreshold = appData.adjudicateLossThreshold;
1138 InitEngine(&first, 0);
1139 InitEngine(&second, 1);
1142 pairing.which = "pairing"; // pairing engine
1143 pairing.pr = NoProc;
1145 pairing.program = appData.pairingEngine;
1146 pairing.host = "localhost";
1149 if (appData.icsActive) {
1150 appData.clockMode = TRUE; /* changes dynamically in ICS mode */
1151 } else if (appData.noChessProgram) { // [HGM] st: searchTime mode now also is clockMode
1152 appData.clockMode = FALSE;
1153 first.sendTime = second.sendTime = 0;
1157 /* Override some settings from environment variables, for backward
1158 compatibility. Unfortunately it's not feasible to have the env
1159 vars just set defaults, at least in xboard. Ugh.
1161 if (appData.icsActive && (appData.zippyPlay || appData.zippyTalk)) {
1166 if (!appData.icsActive) {
1170 /* Check for variants that are supported only in ICS mode,
1171 or not at all. Some that are accepted here nevertheless
1172 have bugs; see comments below.
1174 VariantClass variant = StringToVariant(appData.variant);
1176 case VariantBughouse: /* need four players and two boards */
1177 case VariantKriegspiel: /* need to hide pieces and move details */
1178 /* case VariantFischeRandom: (Fabien: moved below) */
1179 len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant);
1180 if( (len >= MSG_SIZ) && appData.debugMode )
1181 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1183 DisplayFatalError(buf, 0, 2);
1186 case VariantUnknown:
1187 case VariantLoadable:
1197 len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant);
1198 if( (len >= MSG_SIZ) && appData.debugMode )
1199 fprintf(debugFP, "InitBackEnd1: buffer truncated.\n");
1201 DisplayFatalError(buf, 0, 2);
1204 case VariantNormal: /* definitely works! */
1205 if(strcmp(appData.variant, "normal") && !appData.noChessProgram) { // [HGM] hope this is an engine-defined variant
1206 safeStrCpy(engineVariant, appData.variant, MSG_SIZ);
1209 case VariantXiangqi: /* [HGM] repetition rules not implemented */
1210 case VariantFairy: /* [HGM] TestLegality definitely off! */
1211 case VariantGothic: /* [HGM] should work */
1212 case VariantCapablanca: /* [HGM] should work */
1213 case VariantCourier: /* [HGM] initial forced moves not implemented */
1214 case VariantShogi: /* [HGM] could still mate with pawn drop */
1215 case VariantChu: /* [HGM] experimental */
1216 case VariantKnightmate: /* [HGM] should work */
1217 case VariantCylinder: /* [HGM] untested */
1218 case VariantFalcon: /* [HGM] untested */
1219 case VariantCrazyhouse: /* holdings not shown, ([HGM] fixed that!)
1220 offboard interposition not understood */
1221 case VariantWildCastle: /* pieces not automatically shuffled */
1222 case VariantNoCastle: /* pieces not automatically shuffled */
1223 case VariantFischeRandom: /* [HGM] works and shuffles pieces */
1224 case VariantLosers: /* should work except for win condition,
1225 and doesn't know captures are mandatory */
1226 case VariantSuicide: /* should work except for win condition,
1227 and doesn't know captures are mandatory */
1228 case VariantGiveaway: /* should work except for win condition,
1229 and doesn't know captures are mandatory */
1230 case VariantTwoKings: /* should work */
1231 case VariantAtomic: /* should work except for win condition */
1232 case Variant3Check: /* should work except for win condition */
1233 case VariantShatranj: /* should work except for all win conditions */
1234 case VariantMakruk: /* should work except for draw countdown */
1235 case VariantASEAN : /* should work except for draw countdown */
1236 case VariantBerolina: /* might work if TestLegality is off */
1237 case VariantCapaRandom: /* should work */
1238 case VariantJanus: /* should work */
1239 case VariantSuper: /* experimental */
1240 case VariantGreat: /* experimental, requires legality testing to be off */
1241 case VariantSChess: /* S-Chess, should work */
1242 case VariantGrand: /* should work */
1243 case VariantSpartan: /* should work */
1244 case VariantLion: /* should work */
1245 case VariantChuChess: /* should work */
1253 NextIntegerFromString (char ** str, long * value)
1258 while( *s == ' ' || *s == '\t' ) {
1264 if( *s >= '0' && *s <= '9' ) {
1265 while( *s >= '0' && *s <= '9' ) {
1266 *value = *value * 10 + (*s - '0');
1279 NextTimeControlFromString (char ** str, long * value)
1282 int result = NextIntegerFromString( str, &temp );
1285 *value = temp * 60; /* Minutes */
1286 if( **str == ':' ) {
1288 result = NextIntegerFromString( str, &temp );
1289 *value += temp; /* Seconds */
1297 NextSessionFromString (char ** str, int *moves, long * tc, long *inc, int *incType)
1298 { /* [HGM] routine added to read '+moves/time' for secondary time control. */
1299 int result = -1, type = 0; long temp, temp2;
1301 if(**str != ':') return -1; // old params remain in force!
1303 if(**str == '*') type = *(*str)++, temp = 0; // sandclock TC
1304 if( NextIntegerFromString( str, &temp ) ) return -1;
1305 if(type) { *moves = 0; *tc = temp * 500; *inc = temp * 1000; *incType = '*'; return 0; }
1308 /* time only: incremental or sudden-death time control */
1309 if(**str == '+') { /* increment follows; read it */
1311 if(**str == '!') type = *(*str)++; // Bronstein TC
1312 if(result = NextIntegerFromString( str, &temp2)) return -1;
1313 *inc = temp2 * 1000;
1314 if(**str == '.') { // read fraction of increment
1315 char *start = ++(*str);
1316 if(result = NextIntegerFromString( str, &temp2)) return -1;
1318 while(start++ < *str) temp2 /= 10;
1322 *moves = 0; *tc = temp * 1000; *incType = type;
1326 (*str)++; /* classical time control */
1327 result = NextIntegerFromString( str, &temp2); // NOTE: already converted to seconds by ParseTimeControl()
1339 GetTimeQuota (int movenr, int lastUsed, char *tcString)
1340 { /* [HGM] get time to add from the multi-session time-control string */
1341 int incType, moves=1; /* kludge to force reading of first session */
1342 long time, increment;
1345 if(!s || !*s) return 0; // empty TC string means we ran out of the last sudden-death version
1347 if(moves) NextSessionFromString(&s, &moves, &time, &increment, &incType);
1348 nextSession = s; suddenDeath = moves == 0 && increment == 0;
1349 if(movenr == -1) return time; /* last move before new session */
1350 if(incType == '*') increment = 0; else // for sandclock, time is added while not thinking
1351 if(incType == '!' && lastUsed < increment) increment = lastUsed;
1352 if(!moves) return increment; /* current session is incremental */
1353 if(movenr >= 0) movenr -= moves; /* we already finished this session */
1354 } while(movenr >= -1); /* try again for next session */
1356 return 0; // no new time quota on this move
1360 ParseTimeControl (char *tc, float ti, int mps)
1364 char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc;
1367 if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0;
1368 if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1)
1369 sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds
1373 snprintf(buf, MSG_SIZ, ":%d/%s+%g", mps, mytc, ti);
1375 snprintf(buf, MSG_SIZ, ":%s+%g", mytc, ti);
1378 snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc);
1380 snprintf(buf, MSG_SIZ, ":%s", mytc);
1382 fullTimeControlString = StrSave(buf); // this should now be in PGN format
1384 if( NextTimeControlFromString( &tc, &tc1 ) != 0 ) {
1389 /* Parse second time control */
1392 if( NextTimeControlFromString( &tc, &tc2 ) != 0 ) {
1400 timeControl_2 = tc2 * 1000;
1410 timeControl = tc1 * 1000;
1413 timeIncrement = ti * 1000; /* convert to ms */
1414 movesPerSession = 0;
1417 movesPerSession = mps;
1425 if (appData.debugMode) {
1426 # ifdef __GIT_VERSION
1427 fprintf(debugFP, "Version: %s (%s)\n", programVersion, __GIT_VERSION);
1429 fprintf(debugFP, "Version: %s\n", programVersion);
1432 ASSIGN(currentDebugFile, appData.nameOfDebugFile); // [HGM] debug split: remember initial name in use
1434 set_cont_sequence(appData.wrapContSeq);
1435 if (appData.matchGames > 0) {
1436 appData.matchMode = TRUE;
1437 } else if (appData.matchMode) {
1438 appData.matchGames = 1;
1440 if(appData.matchMode && appData.sameColorGames > 0) /* [HGM] alternate: overrule matchGames */
1441 appData.matchGames = appData.sameColorGames;
1442 if(appData.rewindIndex > 1) { /* [HGM] autoinc: rewind implies auto-increment and overrules given index */
1443 if(appData.loadPositionIndex >= 0) appData.loadPositionIndex = -1;
1444 if(appData.loadGameIndex >= 0) appData.loadGameIndex = -1;
1447 if (appData.noChessProgram || first.protocolVersion == 1) {
1450 /* kludge: allow timeout for initial "feature" commands */
1452 DisplayMessage("", _("Starting chess program"));
1453 ScheduleDelayedEvent(InitBackEnd3, FEATURE_TIMEOUT);
1458 CalculateIndex (int index, int gameNr)
1459 { // [HGM] autoinc: absolute way to determine load index from game number (taking auto-inc and rewind into account)
1461 if(index > 0) return index; // fixed nmber
1462 if(index == 0) return 1;
1463 res = (index == -1 ? gameNr : (gameNr-1)/2 + 1); // autoinc
1464 if(appData.rewindIndex > 0) res = (res-1) % appData.rewindIndex + 1; // rewind
1469 LoadGameOrPosition (int gameNr)
1470 { // [HGM] taken out of MatchEvent and NextMatchGame (to combine it)
1471 if (*appData.loadGameFile != NULLCHAR) {
1472 if (!LoadGameFromFile(appData.loadGameFile,
1473 CalculateIndex(appData.loadGameIndex, gameNr),
1474 appData.loadGameFile, FALSE)) {
1475 DisplayFatalError(_("Bad game file"), 0, 1);
1478 } else if (*appData.loadPositionFile != NULLCHAR) {
1479 if (!LoadPositionFromFile(appData.loadPositionFile,
1480 CalculateIndex(appData.loadPositionIndex, gameNr),
1481 appData.loadPositionFile)) {
1482 DisplayFatalError(_("Bad position file"), 0, 1);
1490 ReserveGame (int gameNr, char resChar)
1492 FILE *tf = fopen(appData.tourneyFile, "r+");
1493 char *p, *q, c, buf[MSG_SIZ];
1494 if(tf == NULL) { nextGame = appData.matchGames + 1; return; } // kludge to terminate match
1495 safeStrCpy(buf, lastMsg, MSG_SIZ);
1496 DisplayMessage(_("Pick new game"), "");
1497 flock(fileno(tf), LOCK_EX); // lock the tourney file while we are messing with it
1498 ParseArgsFromFile(tf);
1499 p = q = appData.results;
1500 if(appData.debugMode) {
1501 char *r = appData.participants;
1502 fprintf(debugFP, "results = '%s'\n", p);
1503 while(*r) fprintf(debugFP, *r >= ' ' ? "%c" : "\\%03o", *r), r++;
1504 fprintf(debugFP, "\n");
1506 while(*q && *q != ' ') q++; // get first un-played game (could be beyond end!)
1508 q = malloc(strlen(p) + 2); // could be arbitrary long, but allow to extend by one!
1509 safeStrCpy(q, p, strlen(p) + 2);
1510 if(gameNr >= 0) q[gameNr] = resChar; // replace '*' with result
1511 if(appData.debugMode) fprintf(debugFP, "pick next game from '%s': %d\n", q, nextGame);
1512 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch) { // reserve next game if tourney not yet done
1513 if(q[nextGame] == NULLCHAR) q[nextGame+1] = NULLCHAR; // append one char
1516 fseek(tf, -(strlen(p)+4), SEEK_END);
1518 if(c != '"') // depending on DOS or Unix line endings we can be one off
1519 fseek(tf, -(strlen(p)+2), SEEK_END);
1520 else fseek(tf, -(strlen(p)+3), SEEK_END);
1521 fprintf(tf, "%s\"\n", q); fclose(tf); // update, and flush by closing
1522 DisplayMessage(buf, "");
1523 free(p); appData.results = q;
1524 if(nextGame <= appData.matchGames && resChar != ' ' && !abortMatch &&
1525 (gameNr < 0 || nextGame / appData.defaultMatchGames != gameNr / appData.defaultMatchGames)) {
1526 int round = appData.defaultMatchGames * appData.tourneyType;
1527 if(gameNr < 0 || appData.tourneyType < 1 || // gauntlet engine can always stay loaded as first engine
1528 appData.tourneyType > 1 && nextGame/round != gameNr/round) // in multi-gauntlet change only after round
1529 UnloadEngine(&first); // next game belongs to other pairing;
1530 UnloadEngine(&second); // already unload the engines, so TwoMachinesEvent will load new ones.
1532 if(appData.debugMode) fprintf(debugFP, "Reserved, next=%d, nr=%d\n", nextGame, gameNr);
1536 MatchEvent (int mode)
1537 { // [HGM] moved out of InitBackend3, to make it callable when match starts through menu
1539 if(matchMode) { // already in match mode: switch it off
1541 if(!appData.tourneyFile[0]) appData.matchGames = matchGame; // kludge to let match terminate after next game.
1544 // if(gameMode != BeginningOfGame) {
1545 // DisplayError(_("You can only start a match from the initial position."), 0);
1549 if(mode == 2) appData.matchGames = appData.defaultMatchGames;
1550 /* Set up machine vs. machine match */
1552 NextTourneyGame(-1, &dummy); // sets appData.matchGames if this is tourney, to make sure ReserveGame knows it
1553 if(appData.tourneyFile[0]) {
1555 if(nextGame > appData.matchGames) {
1557 if(strchr(appData.results, '*') == NULL) {
1559 appData.tourneyCycles++;
1560 if(f = WriteTourneyFile(appData.results, NULL)) { // make a tourney file with increased number of cycles
1562 NextTourneyGame(-1, &dummy);
1564 if(nextGame <= appData.matchGames) {
1565 DisplayNote(_("You restarted an already completed tourney.\nOne more cycle will now be added to it.\nGames commence in 10 sec."));
1567 ScheduleDelayedEvent(NextMatchGame, 10000);
1572 snprintf(buf, MSG_SIZ, _("All games in tourney '%s' are already played or playing"), appData.tourneyFile);
1573 DisplayError(buf, 0);
1574 appData.tourneyFile[0] = 0;
1578 if (appData.noChessProgram) { // [HGM] in tourney engines are loaded automatically
1579 DisplayFatalError(_("Can't have a match with no chess programs"),
1584 matchGame = roundNr = 1;
1585 first.matchWins = second.matchWins = 0; // [HGM] match: needed in later matches
1589 char *comboLine = NULL; // [HGM] recent: WinBoard's first-engine combobox line
1592 InitBackEnd3 P((void))
1594 GameMode initialMode;
1598 if(!appData.icsActive && !appData.noChessProgram && !appData.matchMode && // mode involves only first engine
1599 !strcmp(appData.variant, "normal") && // no explicit variant request
1600 appData.NrRanks == -1 && appData.NrFiles == -1 && appData.holdingsSize == -1 && // no size overrides requested
1601 !SupportedVariant(first.variants, VariantNormal, 8, 8, 0, first.protocolVersion, "") && // but 'normal' won't work with engine
1602 !SupportedVariant(first.variants, VariantFischeRandom, 8, 8, 0, first.protocolVersion, "") ) { // nor will Chess960
1603 char c, *q = first.variants, *p = strchr(q, ',');
1604 if(p) *p = NULLCHAR;
1605 if(StringToVariant(q) != VariantUnknown) { // the engine can play a recognized variant, however
1607 if(sscanf(q, "%dx%d+%d_%c", &w, &h, &s, &c) == 4) // get size overrides the engine needs with it (if any)
1608 appData.NrFiles = w, appData.NrRanks = h, appData.holdingsSize = s, q = strchr(q, '_') + 1;
1609 ASSIGN(appData.variant, q); // fake user requested the first variant played by the engine
1610 Reset(TRUE, FALSE); // and re-initialize
1615 InitChessProgram(&first, startedFromSetupPosition);
1617 if(!appData.noChessProgram) { /* [HGM] tidy: redo program version to use name from myname feature */
1618 free(programVersion);
1619 programVersion = (char*) malloc(8 + strlen(PACKAGE_STRING) + strlen(first.tidy));
1620 sprintf(programVersion, "%s + %s", PACKAGE_STRING, first.tidy);
1621 FloatToFront(&appData.recentEngineList, comboLine ? comboLine : appData.firstChessProgram);
1624 if (appData.icsActive) {
1626 /* [DM] Make a console window if needed [HGM] merged ifs */
1632 if (*appData.icsCommPort != NULLCHAR)
1633 len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"),
1634 appData.icsCommPort);
1636 len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"),
1637 appData.icsHost, appData.icsPort);
1639 if( (len >= MSG_SIZ) && appData.debugMode )
1640 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1642 DisplayFatalError(buf, err, 1);
1647 AddInputSource(icsPR, FALSE, read_from_ics, &telnetISR);
1649 AddInputSource(NoProc, FALSE, read_from_player, &fromUserISR);
1650 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
1651 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1652 } else if (appData.noChessProgram) {
1658 if (*appData.cmailGameName != NULLCHAR) {
1660 OpenLoopback(&cmailPR);
1662 AddInputSource(cmailPR, FALSE, CmailSigHandlerCallBack, &cmailISR);
1666 DisplayMessage("", "");
1667 if (StrCaseCmp(appData.initialMode, "") == 0) {
1668 initialMode = BeginningOfGame;
1669 if(!appData.icsActive && appData.noChessProgram) { // [HGM] could be fall-back
1670 gameMode = MachinePlaysBlack; // "Machine Black" might have been implicitly highlighted
1671 ModeHighlight(); // make sure XBoard knows it is highlighted, so it will un-highlight it
1672 gameMode = BeginningOfGame; // in case BeginningOfGame now means "Edit Position"
1675 } else if (StrCaseCmp(appData.initialMode, "TwoMachines") == 0) {
1676 initialMode = TwoMachinesPlay;
1677 } else if (StrCaseCmp(appData.initialMode, "AnalyzeFile") == 0) {
1678 initialMode = AnalyzeFile;
1679 } else if (StrCaseCmp(appData.initialMode, "Analysis") == 0) {
1680 initialMode = AnalyzeMode;
1681 } else if (StrCaseCmp(appData.initialMode, "MachineWhite") == 0) {
1682 initialMode = MachinePlaysWhite;
1683 } else if (StrCaseCmp(appData.initialMode, "MachineBlack") == 0) {
1684 initialMode = MachinePlaysBlack;
1685 } else if (StrCaseCmp(appData.initialMode, "EditGame") == 0) {
1686 initialMode = EditGame;
1687 } else if (StrCaseCmp(appData.initialMode, "EditPosition") == 0) {
1688 initialMode = EditPosition;
1689 } else if (StrCaseCmp(appData.initialMode, "Training") == 0) {
1690 initialMode = Training;
1692 len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode);
1693 if( (len >= MSG_SIZ) && appData.debugMode )
1694 fprintf(debugFP, "InitBackEnd3: buffer truncated.\n");
1696 DisplayFatalError(buf, 0, 2);
1700 if (appData.matchMode) {
1701 if(appData.tourneyFile[0]) { // start tourney from command line
1703 if(f = fopen(appData.tourneyFile, "r")) {
1704 ParseArgsFromFile(f); // make sure tourney parmeters re known
1706 appData.clockMode = TRUE;
1708 } else appData.tourneyFile[0] = NULLCHAR; // for now ignore bad tourney file
1711 } else if (*appData.cmailGameName != NULLCHAR) {
1712 /* Set up cmail mode */
1713 ReloadCmailMsgEvent(TRUE);
1715 /* Set up other modes */
1716 if (initialMode == AnalyzeFile) {
1717 if (*appData.loadGameFile == NULLCHAR) {
1718 DisplayFatalError(_("AnalyzeFile mode requires a game file"), 0, 1);
1722 if (*appData.loadGameFile != NULLCHAR) {
1723 (void) LoadGameFromFile(appData.loadGameFile,
1724 appData.loadGameIndex,
1725 appData.loadGameFile, TRUE);
1726 } else if (*appData.loadPositionFile != NULLCHAR) {
1727 (void) LoadPositionFromFile(appData.loadPositionFile,
1728 appData.loadPositionIndex,
1729 appData.loadPositionFile);
1730 /* [HGM] try to make self-starting even after FEN load */
1731 /* to allow automatic setup of fairy variants with wtm */
1732 if(initialMode == BeginningOfGame && !blackPlaysFirst) {
1733 gameMode = BeginningOfGame;
1734 setboardSpoiledMachineBlack = 1;
1736 /* [HGM] loadPos: make that every new game uses the setup */
1737 /* from file as long as we do not switch variant */
1738 if(!blackPlaysFirst) {
1739 startedFromPositionFile = TRUE;
1740 CopyBoard(filePosition, boards[0]);
1743 if (initialMode == AnalyzeMode) {
1744 if (appData.noChessProgram) {
1745 DisplayFatalError(_("Analysis mode requires a chess engine"), 0, 2);
1748 if (appData.icsActive) {
1749 DisplayFatalError(_("Analysis mode does not work with ICS mode"),0,2);
1753 } else if (initialMode == AnalyzeFile) {
1754 appData.showThinking = TRUE; // [HGM] thinking: moved out of ShowThinkingEvent
1755 ShowThinkingEvent();
1757 AnalysisPeriodicEvent(1);
1758 } else if (initialMode == MachinePlaysWhite) {
1759 if (appData.noChessProgram) {
1760 DisplayFatalError(_("MachineWhite mode requires a chess engine"),
1764 if (appData.icsActive) {
1765 DisplayFatalError(_("MachineWhite mode does not work with ICS mode"),
1769 MachineWhiteEvent();
1770 } else if (initialMode == MachinePlaysBlack) {
1771 if (appData.noChessProgram) {
1772 DisplayFatalError(_("MachineBlack mode requires a chess engine"),
1776 if (appData.icsActive) {
1777 DisplayFatalError(_("MachineBlack mode does not work with ICS mode"),
1781 MachineBlackEvent();
1782 } else if (initialMode == TwoMachinesPlay) {
1783 if (appData.noChessProgram) {
1784 DisplayFatalError(_("TwoMachines mode requires a chess engine"),
1788 if (appData.icsActive) {
1789 DisplayFatalError(_("TwoMachines mode does not work with ICS mode"),
1794 } else if (initialMode == EditGame) {
1796 } else if (initialMode == EditPosition) {
1797 EditPositionEvent();
1798 } else if (initialMode == Training) {
1799 if (*appData.loadGameFile == NULLCHAR) {
1800 DisplayFatalError(_("Training mode requires a game file"), 0, 2);
1809 HistorySet (char movelist[][2*MOVE_LEN], int first, int last, int current)
1811 DisplayBook(current+1);
1813 MoveHistorySet( movelist, first, last, current, pvInfoList );
1815 EvalGraphSet( first, last, current, pvInfoList );
1817 MakeEngineOutputTitle();
1821 * Establish will establish a contact to a remote host.port.
1822 * Sets icsPR to a ProcRef for a process (or pseudo-process)
1823 * used to talk to the host.
1824 * Returns 0 if okay, error code if not.
1831 if (*appData.icsCommPort != NULLCHAR) {
1832 /* Talk to the host through a serial comm port */
1833 return OpenCommPort(appData.icsCommPort, &icsPR);
1835 } else if (*appData.gateway != NULLCHAR) {
1836 if (*appData.remoteShell == NULLCHAR) {
1837 /* Use the rcmd protocol to run telnet program on a gateway host */
1838 snprintf(buf, sizeof(buf), "%s %s %s",
1839 appData.telnetProgram, appData.icsHost, appData.icsPort);
1840 return OpenRcmd(appData.gateway, appData.remoteUser, buf, &icsPR);
1843 /* Use the rsh program to run telnet program on a gateway host */
1844 if (*appData.remoteUser == NULLCHAR) {
1845 snprintf(buf, sizeof(buf), "%s %s %s %s %s", appData.remoteShell,
1846 appData.gateway, appData.telnetProgram,
1847 appData.icsHost, appData.icsPort);
1849 snprintf(buf, sizeof(buf), "%s %s -l %s %s %s %s",
1850 appData.remoteShell, appData.gateway,
1851 appData.remoteUser, appData.telnetProgram,
1852 appData.icsHost, appData.icsPort);
1854 return StartChildProcess(buf, "", &icsPR);
1857 } else if (appData.useTelnet) {
1858 return OpenTelnet(appData.icsHost, appData.icsPort, &icsPR);
1861 /* TCP socket interface differs somewhat between
1862 Unix and NT; handle details in the front end.
1864 return OpenTCP(appData.icsHost, appData.icsPort, &icsPR);
1869 EscapeExpand (char *p, char *q)
1870 { // [HGM] initstring: routine to shape up string arguments
1871 while(*p++ = *q++) if(p[-1] == '\\')
1873 case 'n': p[-1] = '\n'; break;
1874 case 'r': p[-1] = '\r'; break;
1875 case 't': p[-1] = '\t'; break;
1876 case '\\': p[-1] = '\\'; break;
1877 case 0: *p = 0; return;
1878 default: p[-1] = q[-1]; break;
1883 show_bytes (FILE *fp, char *buf, int count)
1886 if (*buf < 040 || *(unsigned char *) buf > 0177) {
1887 fprintf(fp, "\\%03o", *buf & 0xff);
1896 /* Returns an errno value */
1898 OutputMaybeTelnet (ProcRef pr, char *message, int count, int *outError)
1900 char buf[8192], *p, *q, *buflim;
1901 int left, newcount, outcount;
1903 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet ||
1904 *appData.gateway != NULLCHAR) {
1905 if (appData.debugMode) {
1906 fprintf(debugFP, ">ICS: ");
1907 show_bytes(debugFP, message, count);
1908 fprintf(debugFP, "\n");
1910 return OutputToProcess(pr, message, count, outError);
1913 buflim = &buf[sizeof(buf)-1]; /* allow 1 byte for expanding last char */
1920 if (appData.debugMode) {
1921 fprintf(debugFP, ">ICS: ");
1922 show_bytes(debugFP, buf, newcount);
1923 fprintf(debugFP, "\n");
1925 outcount = OutputToProcess(pr, buf, newcount, outError);
1926 if (outcount < newcount) return -1; /* to be sure */
1933 } else if (((unsigned char) *p) == TN_IAC) {
1934 *q++ = (char) TN_IAC;
1941 if (appData.debugMode) {
1942 fprintf(debugFP, ">ICS: ");
1943 show_bytes(debugFP, buf, newcount);
1944 fprintf(debugFP, "\n");
1946 outcount = OutputToProcess(pr, buf, newcount, outError);
1947 if (outcount < newcount) return -1; /* to be sure */
1952 read_from_player (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
1954 int outError, outCount;
1955 static int gotEof = 0;
1958 /* Pass data read from player on to ICS */
1961 outCount = OutputMaybeTelnet(icsPR, message, count, &outError);
1962 if (outCount < count) {
1963 DisplayFatalError(_("Error writing to ICS"), outError, 1);
1965 if(have_sent_ICS_logon == 2) {
1966 if(ini = fopen(appData.icsLogon, "w")) { // save first two lines (presumably username & password) on init script file
1967 fprintf(ini, "%s", message);
1968 have_sent_ICS_logon = 3;
1970 have_sent_ICS_logon = 1;
1971 } else if(have_sent_ICS_logon == 3) {
1972 fprintf(ini, "%s", message);
1974 have_sent_ICS_logon = 1;
1976 } else if (count < 0) {
1977 RemoveInputSource(isr);
1978 DisplayFatalError(_("Error reading from keyboard"), error, 1);
1979 } else if (gotEof++ > 0) {
1980 RemoveInputSource(isr);
1981 DisplayFatalError(_("Got end of file from keyboard"), 0, 0);
1987 { // [HGM] alive: periodically send dummy (date) command to ICS to prevent time-out
1988 if(!connectionAlive) DisplayFatalError("No response from ICS", 0, 1);
1989 connectionAlive = FALSE; // only sticks if no response to 'date' command.
1990 SendToICS("date\n");
1991 if(appData.keepAlive) ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
1994 /* added routine for printf style output to ics */
1996 ics_printf (char *format, ...)
1998 char buffer[MSG_SIZ];
2001 va_start(args, format);
2002 vsnprintf(buffer, sizeof(buffer), format, args);
2003 buffer[sizeof(buffer)-1] = '\0';
2011 int count, outCount, outError;
2013 if (icsPR == NoProc) return;
2016 outCount = OutputMaybeTelnet(icsPR, s, count, &outError);
2017 if (outCount < count) {
2018 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2022 /* This is used for sending logon scripts to the ICS. Sending
2023 without a delay causes problems when using timestamp on ICC
2024 (at least on my machine). */
2026 SendToICSDelayed (char *s, long msdelay)
2028 int count, outCount, outError;
2030 if (icsPR == NoProc) return;
2033 if (appData.debugMode) {
2034 fprintf(debugFP, ">ICS: ");
2035 show_bytes(debugFP, s, count);
2036 fprintf(debugFP, "\n");
2038 outCount = OutputToProcessDelayed(icsPR, s, count, &outError,
2040 if (outCount < count) {
2041 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2046 /* Remove all highlighting escape sequences in s
2047 Also deletes any suffix starting with '('
2050 StripHighlightAndTitle (char *s)
2052 static char retbuf[MSG_SIZ];
2055 while (*s != NULLCHAR) {
2056 while (*s == '\033') {
2057 while (*s != NULLCHAR && !isalpha(*s)) s++;
2058 if (*s != NULLCHAR) s++;
2060 while (*s != NULLCHAR && *s != '\033') {
2061 if (*s == '(' || *s == '[') {
2072 /* Remove all highlighting escape sequences in s */
2074 StripHighlight (char *s)
2076 static char retbuf[MSG_SIZ];
2079 while (*s != NULLCHAR) {
2080 while (*s == '\033') {
2081 while (*s != NULLCHAR && !isalpha(*s)) s++;
2082 if (*s != NULLCHAR) s++;
2084 while (*s != NULLCHAR && *s != '\033') {
2092 char engineVariant[MSG_SIZ];
2093 char *variantNames[] = VARIANT_NAMES;
2095 VariantName (VariantClass v)
2097 if(v == VariantUnknown || *engineVariant) return engineVariant;
2098 return variantNames[v];
2102 /* Identify a variant from the strings the chess servers use or the
2103 PGN Variant tag names we use. */
2105 StringToVariant (char *e)
2109 VariantClass v = VariantNormal;
2110 int i, found = FALSE;
2111 char buf[MSG_SIZ], c;
2116 /* [HGM] skip over optional board-size prefixes */
2117 if( sscanf(e, "%dx%d_%c", &i, &i, &c) == 3 ||
2118 sscanf(e, "%dx%d+%d_%c", &i, &i, &i, &c) == 4 ) {
2119 while( *e++ != '_');
2122 if(StrCaseStr(e, "misc/")) { // [HGM] on FICS, misc/shogi is not shogi
2126 for (i=0; i<sizeof(variantNames)/sizeof(char*); i++) {
2127 if (p = StrCaseStr(e, variantNames[i])) {
2128 if(p && i >= VariantShogi && (p != e || isalpha(p[strlen(variantNames[i])]))) continue;
2129 v = (VariantClass) i;
2136 if ((StrCaseStr(e, "fischer") && StrCaseStr(e, "random"))
2137 || StrCaseStr(e, "wild/fr")
2138 || StrCaseStr(e, "frc") || StrCaseStr(e, "960")) {
2139 v = VariantFischeRandom;
2140 } else if ((i = 4, p = StrCaseStr(e, "wild")) ||
2141 (i = 1, p = StrCaseStr(e, "w"))) {
2143 while (*p && (isspace(*p) || *p == '(' || *p == '/')) p++;
2150 case 0: /* FICS only, actually */
2152 /* Castling legal even if K starts on d-file */
2153 v = VariantWildCastle;
2158 /* Castling illegal even if K & R happen to start in
2159 normal positions. */
2160 v = VariantNoCastle;
2173 /* Castling legal iff K & R start in normal positions */
2179 /* Special wilds for position setup; unclear what to do here */
2180 v = VariantLoadable;
2183 /* Bizarre ICC game */
2184 v = VariantTwoKings;
2187 v = VariantKriegspiel;
2193 v = VariantFischeRandom;
2196 v = VariantCrazyhouse;
2199 v = VariantBughouse;
2205 /* Not quite the same as FICS suicide! */
2206 v = VariantGiveaway;
2212 v = VariantShatranj;
2215 /* Temporary names for future ICC types. The name *will* change in
2216 the next xboard/WinBoard release after ICC defines it. */
2254 v = VariantCapablanca;
2257 v = VariantKnightmate;
2263 v = VariantCylinder;
2269 v = VariantCapaRandom;
2272 v = VariantBerolina;
2284 /* Found "wild" or "w" in the string but no number;
2285 must assume it's normal chess. */
2289 len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum);
2290 if( (len >= MSG_SIZ) && appData.debugMode )
2291 fprintf(debugFP, "StringToVariant: buffer truncated.\n");
2293 DisplayError(buf, 0);
2299 if (appData.debugMode) {
2300 fprintf(debugFP, "recognized '%s' (%d) as variant %s\n",
2301 e, wnum, VariantName(v));
2306 static int leftover_start = 0, leftover_len = 0;
2307 char star_match[STAR_MATCH_N][MSG_SIZ];
2309 /* Test whether pattern is present at &buf[*index]; if so, return TRUE,
2310 advance *index beyond it, and set leftover_start to the new value of
2311 *index; else return FALSE. If pattern contains the character '*', it
2312 matches any sequence of characters not containing '\r', '\n', or the
2313 character following the '*' (if any), and the matched sequence(s) are
2314 copied into star_match.
2317 looking_at ( char *buf, int *index, char *pattern)
2319 char *bufp = &buf[*index], *patternp = pattern;
2321 char *matchp = star_match[0];
2324 if (*patternp == NULLCHAR) {
2325 *index = leftover_start = bufp - buf;
2329 if (*bufp == NULLCHAR) return FALSE;
2330 if (*patternp == '*') {
2331 if (*bufp == *(patternp + 1)) {
2333 matchp = star_match[++star_count];
2337 } else if (*bufp == '\n' || *bufp == '\r') {
2339 if (*patternp == NULLCHAR)
2344 *matchp++ = *bufp++;
2348 if (*patternp != *bufp) return FALSE;
2355 SendToPlayer (char *data, int length)
2357 int error, outCount;
2358 outCount = OutputToProcess(NoProc, data, length, &error);
2359 if (outCount < length) {
2360 DisplayFatalError(_("Error writing to display"), error, 1);
2365 PackHolding (char packed[], char *holding)
2375 switch (runlength) {
2386 sprintf(q, "%d", runlength);
2398 /* Telnet protocol requests from the front end */
2400 TelnetRequest (unsigned char ddww, unsigned char option)
2402 unsigned char msg[3];
2403 int outCount, outError;
2405 if (*appData.icsCommPort != NULLCHAR || appData.useTelnet) return;
2407 if (appData.debugMode) {
2408 char buf1[8], buf2[8], *ddwwStr, *optionStr;
2424 snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww);
2433 snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option);
2436 fprintf(debugFP, ">%s %s ", ddwwStr, optionStr);
2441 outCount = OutputToProcess(icsPR, (char *)msg, 3, &outError);
2443 DisplayFatalError(_("Error writing to ICS"), outError, 1);
2450 if (!appData.icsActive) return;
2451 TelnetRequest(TN_DO, TN_ECHO);
2457 if (!appData.icsActive) return;
2458 TelnetRequest(TN_DONT, TN_ECHO);
2462 CopyHoldings (Board board, char *holdings, ChessSquare lowestPiece)
2464 /* put the holdings sent to us by the server on the board holdings area */
2465 int i, j, holdingsColumn, holdingsStartRow, direction, countsColumn;
2469 if(gameInfo.holdingsWidth < 2) return;
2470 if(gameInfo.variant != VariantBughouse && board[HOLDINGS_SET])
2471 return; // prevent overwriting by pre-board holdings
2473 if( (int)lowestPiece >= BlackPawn ) {
2476 holdingsStartRow = BOARD_HEIGHT-1;
2479 holdingsColumn = BOARD_WIDTH-1;
2480 countsColumn = BOARD_WIDTH-2;
2481 holdingsStartRow = 0;
2485 for(i=0; i<BOARD_HEIGHT; i++) { /* clear holdings */
2486 board[i][holdingsColumn] = EmptySquare;
2487 board[i][countsColumn] = (ChessSquare) 0;
2489 while( (p=*holdings++) != NULLCHAR ) {
2490 piece = CharToPiece( ToUpper(p) );
2491 if(piece == EmptySquare) continue;
2492 /*j = (int) piece - (int) WhitePawn;*/
2493 j = PieceToNumber(piece);
2494 if(j >= gameInfo.holdingsSize) continue; /* ignore pieces that do not fit */
2495 if(j < 0) continue; /* should not happen */
2496 piece = (ChessSquare) ( (int)piece + (int)lowestPiece );
2497 board[holdingsStartRow+j*direction][holdingsColumn] = piece;
2498 board[holdingsStartRow+j*direction][countsColumn]++;
2504 VariantSwitch (Board board, VariantClass newVariant)
2506 int newHoldingsWidth, newWidth = 8, newHeight = 8, i, j;
2507 static Board oldBoard;
2509 startedFromPositionFile = FALSE;
2510 if(gameInfo.variant == newVariant) return;
2512 /* [HGM] This routine is called each time an assignment is made to
2513 * gameInfo.variant during a game, to make sure the board sizes
2514 * are set to match the new variant. If that means adding or deleting
2515 * holdings, we shift the playing board accordingly
2516 * This kludge is needed because in ICS observe mode, we get boards
2517 * of an ongoing game without knowing the variant, and learn about the
2518 * latter only later. This can be because of the move list we requested,
2519 * in which case the game history is refilled from the beginning anyway,
2520 * but also when receiving holdings of a crazyhouse game. In the latter
2521 * case we want to add those holdings to the already received position.
2525 if (appData.debugMode) {
2526 fprintf(debugFP, "Switch board from %s to %s\n",
2527 VariantName(gameInfo.variant), VariantName(newVariant));
2528 setbuf(debugFP, NULL);
2530 shuffleOpenings = 0; /* [HGM] shuffle */
2531 gameInfo.holdingsSize = 5; /* [HGM] prepare holdings */
2535 newWidth = 9; newHeight = 9;
2536 gameInfo.holdingsSize = 7;
2537 case VariantBughouse:
2538 case VariantCrazyhouse:
2539 newHoldingsWidth = 2; break;
2543 newHoldingsWidth = 2;
2544 gameInfo.holdingsSize = 8;
2547 case VariantCapablanca:
2548 case VariantCapaRandom:
2551 newHoldingsWidth = gameInfo.holdingsSize = 0;
2554 if(newWidth != gameInfo.boardWidth ||
2555 newHeight != gameInfo.boardHeight ||
2556 newHoldingsWidth != gameInfo.holdingsWidth ) {
2558 /* shift position to new playing area, if needed */
2559 if(newHoldingsWidth > gameInfo.holdingsWidth) {
2560 for(i=0; i<BOARD_HEIGHT; i++)
2561 for(j=BOARD_RGHT-1; j>=BOARD_LEFT; j--)
2562 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2564 for(i=0; i<newHeight; i++) {
2565 board[i][0] = board[i][newWidth+2*newHoldingsWidth-1] = EmptySquare;
2566 board[i][1] = board[i][newWidth+2*newHoldingsWidth-2] = (ChessSquare) 0;
2568 } else if(newHoldingsWidth < gameInfo.holdingsWidth) {
2569 for(i=0; i<BOARD_HEIGHT; i++)
2570 for(j=BOARD_LEFT; j<BOARD_RGHT; j++)
2571 board[i][j+newHoldingsWidth-gameInfo.holdingsWidth] =
2574 board[HOLDINGS_SET] = 0;
2575 gameInfo.boardWidth = newWidth;
2576 gameInfo.boardHeight = newHeight;
2577 gameInfo.holdingsWidth = newHoldingsWidth;
2578 gameInfo.variant = newVariant;
2579 InitDrawingSizes(-2, 0);
2580 } else gameInfo.variant = newVariant;
2581 CopyBoard(oldBoard, board); // remember correctly formatted board
2582 InitPosition(FALSE); /* this sets up board[0], but also other stuff */
2583 DrawPosition(TRUE, currentMove ? boards[currentMove] : oldBoard);
2586 static int loggedOn = FALSE;
2588 /*-- Game start info cache: --*/
2590 char gs_kind[MSG_SIZ];
2591 static char player1Name[128] = "";
2592 static char player2Name[128] = "";
2593 static char cont_seq[] = "\n\\ ";
2594 static int player1Rating = -1;
2595 static int player2Rating = -1;
2596 /*----------------------------*/
2598 ColorClass curColor = ColorNormal;
2599 int suppressKibitz = 0;
2602 Boolean soughtPending = FALSE;
2603 Boolean seekGraphUp;
2604 #define MAX_SEEK_ADS 200
2606 char *seekAdList[MAX_SEEK_ADS];
2607 int ratingList[MAX_SEEK_ADS], xList[MAX_SEEK_ADS], yList[MAX_SEEK_ADS], seekNrList[MAX_SEEK_ADS], zList[MAX_SEEK_ADS];
2608 float tcList[MAX_SEEK_ADS];
2609 char colorList[MAX_SEEK_ADS];
2610 int nrOfSeekAds = 0;
2611 int minRating = 1010, maxRating = 2800;
2612 int hMargin = 10, vMargin = 20, h, w;
2613 extern int squareSize, lineGap;
2618 int x, y, color = 0, r = ratingList[i]; float tc = tcList[i];
2619 xList[i] = yList[i] = -100; // outside graph, so cannot be clicked
2620 if(r < minRating+100 && r >=0 ) r = minRating+100;
2621 if(r > maxRating) r = maxRating;
2622 if(tc < 1.f) tc = 1.f;
2623 if(tc > 95.f) tc = 95.f;
2624 x = (w-hMargin-squareSize/8-7)* log(tc)/log(95.) + hMargin;
2625 y = ((double)r - minRating)/(maxRating - minRating)
2626 * (h-vMargin-squareSize/8-1) + vMargin;
2627 if(ratingList[i] < 0) y = vMargin + squareSize/4;
2628 if(strstr(seekAdList[i], " u ")) color = 1;
2629 if(!strstr(seekAdList[i], "lightning") && // for now all wilds same color
2630 !strstr(seekAdList[i], "bullet") &&
2631 !strstr(seekAdList[i], "blitz") &&
2632 !strstr(seekAdList[i], "standard") ) color = 2;
2633 if(strstr(seekAdList[i], "(C) ")) color |= SQUARE; // plot computer seeks as squares
2634 DrawSeekDot(xList[i]=x+3*(color&~SQUARE), yList[i]=h-1-y, colorList[i]=color);
2638 PlotSingleSeekAd (int i)
2644 AddAd (char *handle, char *rating, int base, int inc, char rated, char *type, int nr, Boolean plot)
2646 char buf[MSG_SIZ], *ext = "";
2647 VariantClass v = StringToVariant(type);
2648 if(strstr(type, "wild")) {
2649 ext = type + 4; // append wild number
2650 if(v == VariantFischeRandom) type = "chess960"; else
2651 if(v == VariantLoadable) type = "setup"; else
2652 type = VariantName(v);
2654 snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext);
2655 if(nrOfSeekAds < MAX_SEEK_ADS-1) {
2656 if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]);
2657 ratingList[nrOfSeekAds] = -1; // for if seeker has no rating
2658 sscanf(rating, "%d", &ratingList[nrOfSeekAds]);
2659 tcList[nrOfSeekAds] = base + (2./3.)*inc;
2660 seekNrList[nrOfSeekAds] = nr;
2661 zList[nrOfSeekAds] = 0;
2662 seekAdList[nrOfSeekAds++] = StrSave(buf);
2663 if(plot) PlotSingleSeekAd(nrOfSeekAds-1);
2668 EraseSeekDot (int i)
2670 int x = xList[i], y = yList[i], d=squareSize/4, k;
2671 DrawSeekBackground(x-squareSize/8, y-squareSize/8, x+squareSize/8+1, y+squareSize/8+1);
2672 if(x < hMargin+d) DrawSeekAxis(hMargin, y-squareSize/8, hMargin, y+squareSize/8+1);
2673 // now replot every dot that overlapped
2674 for(k=0; k<nrOfSeekAds; k++) if(k != i) {
2675 int xx = xList[k], yy = yList[k];
2676 if(xx <= x+d && xx > x-d && yy <= y+d && yy > y-d)
2677 DrawSeekDot(xx, yy, colorList[k]);
2682 RemoveSeekAd (int nr)
2685 for(i=0; i<nrOfSeekAds; i++) if(seekNrList[i] == nr) {
2687 if(seekAdList[i]) free(seekAdList[i]);
2688 seekAdList[i] = seekAdList[--nrOfSeekAds];
2689 seekNrList[i] = seekNrList[nrOfSeekAds];
2690 ratingList[i] = ratingList[nrOfSeekAds];
2691 colorList[i] = colorList[nrOfSeekAds];
2692 tcList[i] = tcList[nrOfSeekAds];
2693 xList[i] = xList[nrOfSeekAds];
2694 yList[i] = yList[nrOfSeekAds];
2695 zList[i] = zList[nrOfSeekAds];
2696 seekAdList[nrOfSeekAds] = NULL;
2702 MatchSoughtLine (char *line)
2704 char handle[MSG_SIZ], rating[MSG_SIZ], type[MSG_SIZ];
2705 int nr, base, inc, u=0; char dummy;
2707 if(sscanf(line, "%d %s %s %d %d rated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2708 sscanf(line, "%d %s %s %s %d %d rated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7 ||
2710 (sscanf(line, "%d %s %s %d %d unrated %s", &nr, rating, handle, &base, &inc, type) == 6 ||
2711 sscanf(line, "%d %s %s %s %d %d unrated %c", &nr, rating, handle, type, &base, &inc, &dummy) == 7) ) {
2712 // match: compact and save the line
2713 AddAd(handle, rating, base, inc, u ? 'u' : 'r', type, nr, FALSE);
2723 if(!seekGraphUp) return FALSE;
2724 h = BOARD_HEIGHT * (squareSize + lineGap) + lineGap + 2*border;
2725 w = BOARD_WIDTH * (squareSize + lineGap) + lineGap + 2*border;
2727 DrawSeekBackground(0, 0, w, h);
2728 DrawSeekAxis(hMargin, h-1-vMargin, w-5, h-1-vMargin);
2729 DrawSeekAxis(hMargin, h-1-vMargin, hMargin, 5);
2730 for(i=0; i<4000; i+= 100) if(i>=minRating && i<maxRating) {
2731 int yy =((double)i - minRating)/(maxRating - minRating)*(h-vMargin-squareSize/8-1) + vMargin;
2733 DrawSeekAxis(hMargin-5, yy, hMargin+5*(i%500==0), yy); // rating ticks
2736 snprintf(buf, MSG_SIZ, "%d", i);
2737 DrawSeekText(buf, hMargin+squareSize/8+7, yy);
2740 DrawSeekText("unrated", hMargin+squareSize/8+7, h-1-vMargin-squareSize/4);
2741 for(i=1; i<100; i+=(i<10?1:5)) {
2742 int xx = (w-hMargin-squareSize/8-7)* log((double)i)/log(95.) + hMargin;
2743 DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks
2744 if(i<=5 || (i>40 ? i%20 : i%10) == 0) {
2746 snprintf(buf, MSG_SIZ, "%d", i);
2747 DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2);
2750 for(i=0; i<nrOfSeekAds; i++) PlotSeekAd(i);
2755 SeekGraphClick (ClickType click, int x, int y, int moving)
2757 static int lastDown = 0, displayed = 0, lastSecond;
2758 if(y < 0) return FALSE;
2759 if(!(appData.seekGraph && appData.icsActive && loggedOn &&
2760 (gameMode == BeginningOfGame || gameMode == IcsIdle))) {
2761 if(!seekGraphUp) return FALSE;
2762 seekGraphUp = FALSE; // seek graph is up when it shouldn't be: take it down
2763 DrawPosition(TRUE, NULL);
2766 if(!seekGraphUp) { // initiate cration of seek graph by requesting seek-ad list
2767 if(click == Release || moving) return FALSE;
2769 soughtPending = TRUE;
2770 SendToICS(ics_prefix);
2771 SendToICS("sought\n"); // should this be "sought all"?
2772 } else { // issue challenge based on clicked ad
2773 int dist = 10000; int i, closest = 0, second = 0;
2774 for(i=0; i<nrOfSeekAds; i++) {
2775 int d = (x-xList[i])*(x-xList[i]) + (y-yList[i])*(y-yList[i]) + zList[i];
2776 if(d < dist) { dist = d; closest = i; }
2777 second += (d - zList[i] < 120); // count in-range ads
2778 if(click == Press && moving != 1 && zList[i]>0) zList[i] *= 0.8; // age priority
2782 second = (second > 1);
2783 if(displayed != closest || second != lastSecond) {
2784 DisplayMessage(second ? "!" : "", seekAdList[closest]);
2785 lastSecond = second; displayed = closest;
2787 if(click == Press) {
2788 if(moving == 2) zList[closest] = 100; // right-click; push to back on press
2791 } // on press 'hit', only show info
2792 if(moving == 2) return TRUE; // ignore right up-clicks on dot
2793 snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]);
2794 SendToICS(ics_prefix);
2796 return TRUE; // let incoming board of started game pop down the graph
2797 } else if(click == Release) { // release 'miss' is ignored
2798 zList[lastDown] = 100; // make future selection of the rejected ad more difficult
2799 if(moving == 2) { // right up-click
2800 nrOfSeekAds = 0; // refresh graph
2801 soughtPending = TRUE;
2802 SendToICS(ics_prefix);
2803 SendToICS("sought\n"); // should this be "sought all"?
2806 } else if(moving) { if(displayed >= 0) DisplayMessage("", ""); displayed = -1; return TRUE; }
2807 // press miss or release hit 'pop down' seek graph
2808 seekGraphUp = FALSE;
2809 DrawPosition(TRUE, NULL);
2815 read_from_ics (InputSourceRef isr, VOIDSTAR closure, char *data, int count, int error)
2817 #define BUF_SIZE (16*1024) /* overflowed at 8K with "inchannel 1" on FICS? */
2818 #define STARTED_NONE 0
2819 #define STARTED_MOVES 1
2820 #define STARTED_BOARD 2
2821 #define STARTED_OBSERVE 3
2822 #define STARTED_HOLDINGS 4
2823 #define STARTED_CHATTER 5
2824 #define STARTED_COMMENT 6
2825 #define STARTED_MOVES_NOHIDE 7
2827 static int started = STARTED_NONE;
2828 static char parse[20000];
2829 static int parse_pos = 0;
2830 static char buf[BUF_SIZE + 1];
2831 static int firstTime = TRUE, intfSet = FALSE;
2832 static ColorClass prevColor = ColorNormal;
2833 static int savingComment = FALSE;
2834 static int cmatch = 0; // continuation sequence match
2841 int backup; /* [DM] For zippy color lines */
2843 char talker[MSG_SIZ]; // [HGM] chat
2844 int channel, collective=0;
2846 connectionAlive = TRUE; // [HGM] alive: I think, therefore I am...
2848 if (appData.debugMode) {
2850 fprintf(debugFP, "<ICS: ");
2851 show_bytes(debugFP, data, count);
2852 fprintf(debugFP, "\n");
2856 if (appData.debugMode) { int f = forwardMostMove;
2857 fprintf(debugFP, "ics input %d, castling = %d %d %d %d %d %d\n", f,
2858 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
2859 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
2862 /* If last read ended with a partial line that we couldn't parse,
2863 prepend it to the new read and try again. */
2864 if (leftover_len > 0) {
2865 for (i=0; i<leftover_len; i++)
2866 buf[i] = buf[leftover_start + i];
2869 /* copy new characters into the buffer */
2870 bp = buf + leftover_len;
2871 buf_len=leftover_len;
2872 for (i=0; i<count; i++)
2875 if (data[i] == '\r')
2878 // join lines split by ICS?
2879 if (!appData.noJoin)
2882 Joining just consists of finding matches against the
2883 continuation sequence, and discarding that sequence
2884 if found instead of copying it. So, until a match
2885 fails, there's nothing to do since it might be the
2886 complete sequence, and thus, something we don't want
2889 if (data[i] == cont_seq[cmatch])
2892 if (cmatch == strlen(cont_seq))
2894 cmatch = 0; // complete match. just reset the counter
2897 it's possible for the ICS to not include the space
2898 at the end of the last word, making our [correct]
2899 join operation fuse two separate words. the server
2900 does this when the space occurs at the width setting.
2902 if (!buf_len || buf[buf_len-1] != ' ')
2913 match failed, so we have to copy what matched before
2914 falling through and copying this character. In reality,
2915 this will only ever be just the newline character, but
2916 it doesn't hurt to be precise.
2918 strncpy(bp, cont_seq, cmatch);
2930 buf[buf_len] = NULLCHAR;
2931 // next_out = leftover_len; // [HGM] should we set this to 0, and not print it in advance?
2936 while (i < buf_len) {
2937 /* Deal with part of the TELNET option negotiation
2938 protocol. We refuse to do anything beyond the
2939 defaults, except that we allow the WILL ECHO option,
2940 which ICS uses to turn off password echoing when we are
2941 directly connected to it. We reject this option
2942 if localLineEditing mode is on (always on in xboard)
2943 and we are talking to port 23, which might be a real
2944 telnet server that will try to keep WILL ECHO on permanently.
2946 if (buf_len - i >= 3 && (unsigned char) buf[i] == TN_IAC) {
2947 static int remoteEchoOption = FALSE; /* telnet ECHO option */
2948 unsigned char option;
2950 switch ((unsigned char) buf[++i]) {
2952 if (appData.debugMode)
2953 fprintf(debugFP, "\n<WILL ");
2954 switch (option = (unsigned char) buf[++i]) {
2956 if (appData.debugMode)
2957 fprintf(debugFP, "ECHO ");
2958 /* Reply only if this is a change, according
2959 to the protocol rules. */
2960 if (remoteEchoOption) break;
2961 if (appData.localLineEditing &&
2962 atoi(appData.icsPort) == TN_PORT) {
2963 TelnetRequest(TN_DONT, TN_ECHO);
2966 TelnetRequest(TN_DO, TN_ECHO);
2967 remoteEchoOption = TRUE;
2971 if (appData.debugMode)
2972 fprintf(debugFP, "%d ", option);
2973 /* Whatever this is, we don't want it. */
2974 TelnetRequest(TN_DONT, option);
2979 if (appData.debugMode)
2980 fprintf(debugFP, "\n<WONT ");
2981 switch (option = (unsigned char) buf[++i]) {
2983 if (appData.debugMode)
2984 fprintf(debugFP, "ECHO ");
2985 /* Reply only if this is a change, according
2986 to the protocol rules. */
2987 if (!remoteEchoOption) break;
2989 TelnetRequest(TN_DONT, TN_ECHO);
2990 remoteEchoOption = FALSE;
2993 if (appData.debugMode)
2994 fprintf(debugFP, "%d ", (unsigned char) option);
2995 /* Whatever this is, it must already be turned
2996 off, because we never agree to turn on
2997 anything non-default, so according to the
2998 protocol rules, we don't reply. */
3003 if (appData.debugMode)
3004 fprintf(debugFP, "\n<DO ");
3005 switch (option = (unsigned char) buf[++i]) {
3007 /* Whatever this is, we refuse to do it. */
3008 if (appData.debugMode)
3009 fprintf(debugFP, "%d ", option);
3010 TelnetRequest(TN_WONT, option);
3015 if (appData.debugMode)
3016 fprintf(debugFP, "\n<DONT ");
3017 switch (option = (unsigned char) buf[++i]) {
3019 if (appData.debugMode)
3020 fprintf(debugFP, "%d ", option);
3021 /* Whatever this is, we are already not doing
3022 it, because we never agree to do anything
3023 non-default, so according to the protocol
3024 rules, we don't reply. */
3029 if (appData.debugMode)
3030 fprintf(debugFP, "\n<IAC ");
3031 /* Doubled IAC; pass it through */
3035 if (appData.debugMode)
3036 fprintf(debugFP, "\n<%d ", (unsigned char) buf[i]);
3037 /* Drop all other telnet commands on the floor */
3040 if (oldi > next_out)
3041 SendToPlayer(&buf[next_out], oldi - next_out);
3047 /* OK, this at least will *usually* work */
3048 if (!loggedOn && looking_at(buf, &i, "ics%")) {
3052 if (loggedOn && !intfSet) {
3053 if (ics_type == ICS_ICC) {
3054 snprintf(str, MSG_SIZ,
3055 "/set-quietly interface %s\n/set-quietly style 12\n",
3057 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
3058 strcat(str, "/set-2 51 1\n/set seek 1\n");
3059 } else if (ics_type == ICS_CHESSNET) {
3060 snprintf(str, MSG_SIZ, "/style 12\n");
3062 safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0]));
3063 strcat(str, programVersion);
3064 strcat(str, "\n$iset startpos 1\n$iset ms 1\n");
3065 if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph
3066 strcat(str, "$iset seekremove 1\n$set seek 1\n");
3068 strcat(str, "$iset nohighlight 1\n");
3070 strcat(str, "$iset lock 1\n$style 12\n");
3073 NotifyFrontendLogin();
3077 if (started == STARTED_COMMENT) {
3078 /* Accumulate characters in comment */
3079 parse[parse_pos++] = buf[i];
3080 if (buf[i] == '\n') {
3081 parse[parse_pos] = NULLCHAR;
3082 if(chattingPartner>=0) {
3084 snprintf(mess, MSG_SIZ, "%s%s", talker, parse);
3085 OutputChatMessage(chattingPartner, mess);
3086 if(collective == 1) { // broadcasted talk also goes to private chatbox of talker
3088 talker[strlen(talker+1)-1] = NULLCHAR; // strip closing delimiter
3089 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
3090 snprintf(mess, MSG_SIZ, "%s: %s", chatPartner[chattingPartner], parse);
3091 OutputChatMessage(p, mess);
3095 chattingPartner = -1;
3096 if(collective != 3) next_out = i+1; // [HGM] suppress printing in ICS window
3099 if(!suppressKibitz) // [HGM] kibitz
3100 AppendComment(forwardMostMove, StripHighlight(parse), TRUE);
3101 else { // [HGM kibitz: divert memorized engine kibitz to engine-output window
3102 int nrDigit = 0, nrAlph = 0, j;
3103 if(parse_pos > MSG_SIZ - 30) // defuse unreasonably long input
3104 { parse_pos = MSG_SIZ-30; parse[parse_pos - 1] = '\n'; }
3105 parse[parse_pos] = NULLCHAR;
3106 // try to be smart: if it does not look like search info, it should go to
3107 // ICS interaction window after all, not to engine-output window.
3108 for(j=0; j<parse_pos; j++) { // count letters and digits
3109 nrDigit += (parse[j] >= '0' && parse[j] <= '9');
3110 nrAlph += (parse[j] >= 'a' && parse[j] <= 'z');
3111 nrAlph += (parse[j] >= 'A' && parse[j] <= 'Z');
3113 if(nrAlph < 9*nrDigit) { // if more than 10% digit we assume search info
3114 int depth=0; float score;
3115 if(sscanf(parse, "!!! %f/%d", &score, &depth) == 2 && depth>0) {
3116 // [HGM] kibitz: save kibitzed opponent info for PGN and eval graph
3117 pvInfoList[forwardMostMove-1].depth = depth;
3118 pvInfoList[forwardMostMove-1].score = 100*score;
3120 OutputKibitz(suppressKibitz, parse);
3123 if(gameMode == IcsObserving) // restore original ICS messages
3124 /* TRANSLATORS: to 'kibitz' is to send a message to all players and the game observers */
3125 snprintf(tmp, MSG_SIZ, "%s kibitzes: %s", star_match[0], parse);
3127 /* TRANSLATORS: to 'kibitz' is to send a message to all players and the game observers */
3128 snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse);
3129 SendToPlayer(tmp, strlen(tmp));
3131 next_out = i+1; // [HGM] suppress printing in ICS window
3133 started = STARTED_NONE;
3135 /* Don't match patterns against characters in comment */
3140 if (started == STARTED_CHATTER) {
3141 if (buf[i] != '\n') {
3142 /* Don't match patterns against characters in chatter */
3146 started = STARTED_NONE;
3147 if(suppressKibitz) next_out = i+1;
3150 /* Kludge to deal with rcmd protocol */
3151 if (firstTime && looking_at(buf, &i, "\001*")) {
3152 DisplayFatalError(&buf[1], 0, 1);
3158 if (!loggedOn && looking_at(buf, &i, "chessclub.com")) {
3161 if (appData.debugMode)
3162 fprintf(debugFP, "ics_type %d\n", ics_type);
3165 if (!loggedOn && looking_at(buf, &i, "freechess.org")) {
3166 ics_type = ICS_FICS;
3168 if (appData.debugMode)
3169 fprintf(debugFP, "ics_type %d\n", ics_type);
3172 if (!loggedOn && looking_at(buf, &i, "chess.net")) {
3173 ics_type = ICS_CHESSNET;
3175 if (appData.debugMode)
3176 fprintf(debugFP, "ics_type %d\n", ics_type);
3181 (looking_at(buf, &i, "\"*\" is *a registered name") ||
3182 looking_at(buf, &i, "Logging you in as \"*\"") ||
3183 looking_at(buf, &i, "will be \"*\""))) {
3184 safeStrCpy(ics_handle, star_match[0], sizeof(ics_handle)/sizeof(ics_handle[0]));
3188 if (loggedOn && !have_set_title && ics_handle[0] != NULLCHAR) {
3190 snprintf(buf, sizeof(buf), "%s@%s", ics_handle, appData.icsHost);
3191 DisplayIcsInteractionTitle(buf);
3192 have_set_title = TRUE;
3195 /* skip finger notes */
3196 if (started == STARTED_NONE &&
3197 ((buf[i] == ' ' && isdigit(buf[i+1])) ||
3198 (buf[i] == '1' && buf[i+1] == '0')) &&
3199 buf[i+2] == ':' && buf[i+3] == ' ') {
3200 started = STARTED_CHATTER;
3206 // [HGM] seekgraph: recognize sought lines and end-of-sought message
3207 if(appData.seekGraph) {
3208 if(soughtPending && MatchSoughtLine(buf+i)) {
3209 i = strstr(buf+i, "rated") - buf;
3210 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3211 next_out = leftover_start = i;
3212 started = STARTED_CHATTER;
3213 suppressKibitz = TRUE;
3216 if((gameMode == IcsIdle || gameMode == BeginningOfGame)
3217 && looking_at(buf, &i, "* ads displayed")) {
3218 soughtPending = FALSE;
3223 if(appData.autoRefresh) {
3224 if(looking_at(buf, &i, "* (*) seeking * * * * *\"play *\" to respond)\n")) {
3225 int s = (ics_type == ICS_ICC); // ICC format differs
3227 AddAd(star_match[0], star_match[1], atoi(star_match[2+s]), atoi(star_match[3+s]),
3228 star_match[4+s][0], star_match[5-3*s], atoi(star_match[7]), TRUE);
3229 looking_at(buf, &i, "*% "); // eat prompt
3230 if(oldi > 0 && buf[oldi-1] == '\n') oldi--; // suppress preceding LF, if any
3231 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3232 next_out = i; // suppress
3235 if(looking_at(buf, &i, "\nAds removed: *\n") || looking_at(buf, &i, "\031(51 * *\031)")) {
3236 char *p = star_match[0];
3238 if(seekGraphUp) RemoveSeekAd(atoi(p));
3239 while(*p && *p++ != ' '); // next
3241 looking_at(buf, &i, "*% "); // eat prompt
3242 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3249 /* skip formula vars */
3250 if (started == STARTED_NONE &&
3251 buf[i] == 'f' && isdigit(buf[i+1]) && buf[i+2] == ':') {
3252 started = STARTED_CHATTER;
3257 // [HGM] kibitz: try to recognize opponent engine-score kibitzes, to divert them to engine-output window
3258 if (appData.autoKibitz && started == STARTED_NONE &&
3259 !appData.icsEngineAnalyze && // [HGM] [DM] ICS analyze
3260 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack || gameMode == IcsObserving)) {
3261 if((looking_at(buf, &i, "\n* kibitzes: ") || looking_at(buf, &i, "\n* whispers: ") ||
3262 looking_at(buf, &i, "* kibitzes: ") || looking_at(buf, &i, "* whispers: ")) &&
3263 (StrStr(star_match[0], gameInfo.white) == star_match[0] ||
3264 StrStr(star_match[0], gameInfo.black) == star_match[0] )) { // kibitz of self or opponent
3265 suppressKibitz = TRUE;
3266 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3268 if((StrStr(star_match[0], gameInfo.white) == star_match[0]
3269 && (gameMode == IcsPlayingWhite)) ||
3270 (StrStr(star_match[0], gameInfo.black) == star_match[0]
3271 && (gameMode == IcsPlayingBlack)) ) // opponent kibitz
3272 started = STARTED_CHATTER; // own kibitz we simply discard
3274 started = STARTED_COMMENT; // make sure it will be collected in parse[]
3275 parse_pos = 0; parse[0] = NULLCHAR;
3276 savingComment = TRUE;
3277 suppressKibitz = gameMode != IcsObserving ? 2 :
3278 (StrStr(star_match[0], gameInfo.white) == NULL) + 1;
3282 if((looking_at(buf, &i, "\nkibitzed to *\n") || looking_at(buf, &i, "kibitzed to *\n") ||
3283 looking_at(buf, &i, "\n(kibitzed to *\n") || looking_at(buf, &i, "(kibitzed to *\n"))
3284 && atoi(star_match[0])) {
3285 // suppress the acknowledgements of our own autoKibitz
3287 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3288 if(p = strchr(star_match[0], ' ')) p[1] = NULLCHAR; // clip off "players)" on FICS
3289 SendToPlayer(star_match[0], strlen(star_match[0]));
3290 if(looking_at(buf, &i, "*% ")) // eat prompt
3291 suppressKibitz = FALSE;
3295 } // [HGM] kibitz: end of patch
3297 if(looking_at(buf, &i, "* rating adjustment: * --> *\n")) continue;
3299 // [HGM] chat: intercept tells by users for which we have an open chat window
3301 if(started == STARTED_NONE && (looking_at(buf, &i, "* tells you:") || looking_at(buf, &i, "* says:") ||
3302 looking_at(buf, &i, "* whispers:") ||
3303 looking_at(buf, &i, "* kibitzes:") ||
3304 looking_at(buf, &i, "* shouts:") ||
3305 looking_at(buf, &i, "* c-shouts:") ||
3306 looking_at(buf, &i, "--> * ") ||
3307 looking_at(buf, &i, "*(*):") && (sscanf(star_match[1], "%d", &channel),1) ||
3308 looking_at(buf, &i, "*(*)(*):") && (sscanf(star_match[2], "%d", &channel),1) ||
3309 looking_at(buf, &i, "*(*)(*)(*):") && (sscanf(star_match[3], "%d", &channel),1) ||
3310 looking_at(buf, &i, "*(*)(*)(*)(*):") && sscanf(star_match[4], "%d", &channel) == 1 )) {
3312 sscanf(star_match[0], "%[^(]", talker+1); // strip (C) or (U) off ICS handle
3313 chattingPartner = -1; collective = 0;
3315 if(channel >= 0) // channel broadcast; look if there is a chatbox for this channel
3316 for(p=0; p<MAX_CHAT; p++) {
3318 if(chatPartner[p][0] >= '0' && chatPartner[p][0] <= '9' && channel == atoi(chatPartner[p])) {
3319 talker[0] = '['; strcat(talker, "] ");
3320 Colorize((channel == 1 ? ColorChannel1 : ColorChannel), FALSE);
3321 chattingPartner = p; break;
3324 if(buf[i-3] == 'e') // kibitz; look if there is a KIBITZ chatbox
3325 for(p=0; p<MAX_CHAT; p++) {
3327 if(!strcmp("kibitzes", chatPartner[p])) {
3328 talker[0] = '['; strcat(talker, "] ");
3329 chattingPartner = p; break;
3332 if(buf[i-3] == 'r') // whisper; look if there is a WHISPER chatbox
3333 for(p=0; p<MAX_CHAT; p++) {
3335 if(!strcmp("whispers", chatPartner[p])) {
3336 talker[0] = '['; strcat(talker, "] ");
3337 chattingPartner = p; break;
3340 if(buf[i-3] == 't' || buf[oldi+2] == '>') {// shout, c-shout or it; look if there is a 'shouts' chatbox
3341 if(buf[i-8] == '-' && buf[i-3] == 't')
3342 for(p=0; p<MAX_CHAT; p++) { // c-shout; check if dedicatesd c-shout box exists
3344 if(!strcmp("c-shouts", chatPartner[p])) {
3345 talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE);
3346 chattingPartner = p; break;
3349 if(chattingPartner < 0)
3350 for(p=0; p<MAX_CHAT; p++) {
3352 if(!strcmp("shouts", chatPartner[p])) {
3353 if(buf[oldi+2] == '>') { talker[0] = '<'; strcat(talker, "> "); Colorize(ColorShout, FALSE); }
3354 else if(buf[i-8] == '-') { talker[0] = '('; strcat(talker, ") "); Colorize(ColorSShout, FALSE); }
3355 else { talker[0] = '['; strcat(talker, "] "); Colorize(ColorShout, FALSE); }
3356 chattingPartner = p; break;
3360 if(chattingPartner<0) // if not, look if there is a chatbox for this indivdual
3361 for(p=0; p<MAX_CHAT; p++) if(!StrCaseCmp(talker+1, chatPartner[p])) {
3363 Colorize(ColorTell, FALSE);
3364 if(collective) safeStrCpy(talker, "broadcasts: ", MSG_SIZ);
3366 chattingPartner = p; break;
3368 if(chattingPartner<0) i = oldi, safeStrCpy(lastTalker, talker+1, MSG_SIZ); else {
3369 Colorize(curColor, TRUE); // undo the bogus colorations we just made to trigger the souds
3370 started = STARTED_COMMENT;
3371 parse_pos = 0; parse[0] = NULLCHAR;
3372 savingComment = 3 + chattingPartner; // counts as TRUE
3373 if(collective == 3) i = oldi; else {
3374 suppressKibitz = TRUE;
3375 if(oldi > 0 && buf[oldi-1] == '\n') oldi--;
3376 if (oldi > next_out) SendToPlayer(&buf[next_out], oldi - next_out);
3380 } // [HGM] chat: end of patch
3383 if (appData.zippyTalk || appData.zippyPlay) {
3384 /* [DM] Backup address for color zippy lines */
3386 if (loggedOn == TRUE)
3387 if (ZippyControl(buf, &backup) || ZippyConverse(buf, &backup) ||
3388 (appData.zippyPlay && ZippyMatch(buf, &backup)));
3390 } // [DM] 'else { ' deleted
3392 /* Regular tells and says */
3393 (tkind = 1, looking_at(buf, &i, "* tells you: ")) ||
3394 looking_at(buf, &i, "* (your partner) tells you: ") ||
3395 looking_at(buf, &i, "* says: ") ||
3396 /* Don't color "message" or "messages" output */
3397 (tkind = 5, looking_at(buf, &i, "*. * (*:*): ")) ||
3398 looking_at(buf, &i, "*. * at *:*: ") ||
3399 looking_at(buf, &i, "--* (*:*): ") ||
3400 /* Message notifications (same color as tells) */
3401 looking_at(buf, &i, "* has left a message ") ||
3402 looking_at(buf, &i, "* just sent you a message:\n") ||
3403 /* Whispers and kibitzes */
3404 (tkind = 2, looking_at(buf, &i, "* whispers: ")) ||
3405 looking_at(buf, &i, "* kibitzes: ") ||
3407 (tkind = 3, looking_at(buf, &i, "*(*: "))) {
3409 if (tkind == 1 && strchr(star_match[0], ':')) {
3410 /* Avoid "tells you:" spoofs in channels */
3413 if (star_match[0][0] == NULLCHAR ||
3414 strchr(star_match[0], ' ') ||
3415 (tkind == 3 && strchr(star_match[1], ' '))) {
3416 /* Reject bogus matches */
3419 if (appData.colorize) {
3420 if (oldi > next_out) {
3421 SendToPlayer(&buf[next_out], oldi - next_out);
3426 Colorize(ColorTell, FALSE);
3427 curColor = ColorTell;
3430 Colorize(ColorKibitz, FALSE);
3431 curColor = ColorKibitz;
3434 p = strrchr(star_match[1], '(');
3441 Colorize(ColorChannel1, FALSE);
3442 curColor = ColorChannel1;
3444 Colorize(ColorChannel, FALSE);
3445 curColor = ColorChannel;
3449 curColor = ColorNormal;
3453 if (started == STARTED_NONE && appData.autoComment &&
3454 (gameMode == IcsObserving ||
3455 gameMode == IcsPlayingWhite ||
3456 gameMode == IcsPlayingBlack)) {
3457 parse_pos = i - oldi;
3458 memcpy(parse, &buf[oldi], parse_pos);
3459 parse[parse_pos] = NULLCHAR;
3460 started = STARTED_COMMENT;
3461 savingComment = TRUE;
3462 } else if(collective != 3) {
3463 started = STARTED_CHATTER;
3464 savingComment = FALSE;
3471 if (looking_at(buf, &i, "* s-shouts: ") ||
3472 looking_at(buf, &i, "* c-shouts: ")) {
3473 if (appData.colorize) {
3474 if (oldi > next_out) {
3475 SendToPlayer(&buf[next_out], oldi - next_out);
3478 Colorize(ColorSShout, FALSE);
3479 curColor = ColorSShout;
3482 started = STARTED_CHATTER;
3486 if (looking_at(buf, &i, "--->")) {
3491 if (looking_at(buf, &i, "* shouts: ") ||
3492 looking_at(buf, &i, "--> ")) {
3493 if (appData.colorize) {
3494 if (oldi > next_out) {
3495 SendToPlayer(&buf[next_out], oldi - next_out);
3498 Colorize(ColorShout, FALSE);
3499 curColor = ColorShout;
3502 started = STARTED_CHATTER;
3506 if (looking_at( buf, &i, "Challenge:")) {
3507 if (appData.colorize) {
3508 if (oldi > next_out) {
3509 SendToPlayer(&buf[next_out], oldi - next_out);
3512 Colorize(ColorChallenge, FALSE);
3513 curColor = ColorChallenge;
3519 if (looking_at(buf, &i, "* offers you") ||
3520 looking_at(buf, &i, "* offers to be") ||
3521 looking_at(buf, &i, "* would like to") ||
3522 looking_at(buf, &i, "* requests to") ||
3523 looking_at(buf, &i, "Your opponent offers") ||
3524 looking_at(buf, &i, "Your opponent requests")) {
3526 if (appData.colorize) {
3527 if (oldi > next_out) {
3528 SendToPlayer(&buf[next_out], oldi - next_out);
3531 Colorize(ColorRequest, FALSE);
3532 curColor = ColorRequest;
3537 if (looking_at(buf, &i, "* (*) seeking")) {
3538 if (appData.colorize) {
3539 if (oldi > next_out) {
3540 SendToPlayer(&buf[next_out], oldi - next_out);
3543 Colorize(ColorSeek, FALSE);
3544 curColor = ColorSeek;
3549 if(i < backup) { i = backup; continue; } // [HGM] for if ZippyControl matches, but the colorie code doesn't
3551 if (looking_at(buf, &i, "\\ ")) {
3552 if (prevColor != ColorNormal) {
3553 if (oldi > next_out) {
3554 SendToPlayer(&buf[next_out], oldi - next_out);
3557 Colorize(prevColor, TRUE);
3558 curColor = prevColor;
3560 if (savingComment) {
3561 parse_pos = i - oldi;
3562 memcpy(parse, &buf[oldi], parse_pos);
3563 parse[parse_pos] = NULLCHAR;
3564 started = STARTED_COMMENT;
3565 if(savingComment >= 3) // [HGM] chat: continuation of line for chat box
3566 chattingPartner = savingComment - 3; // kludge to remember the box
3568 started = STARTED_CHATTER;
3573 if (looking_at(buf, &i, "Black Strength :") ||
3574 looking_at(buf, &i, "<<< style 10 board >>>") ||
3575 looking_at(buf, &i, "<10>") ||
3576 looking_at(buf, &i, "#@#")) {
3577 /* Wrong board style */
3579 SendToICS(ics_prefix);
3580 SendToICS("set style 12\n");
3581 SendToICS(ics_prefix);
3582 SendToICS("refresh\n");
3586 if (looking_at(buf, &i, "login:")) {
3587 if (!have_sent_ICS_logon) {
3589 have_sent_ICS_logon = 1;
3590 else // no init script was found
3591 have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // flag that we should capture username + password
3592 } else { // we have sent (or created) the InitScript, but apparently the ICS rejected it
3593 have_sent_ICS_logon = (appData.autoCreateLogon ? 2 : 1); // request creation of a new script
3598 if (ics_getting_history != H_GETTING_MOVES /*smpos kludge*/ &&
3599 (looking_at(buf, &i, "\n<12> ") ||
3600 looking_at(buf, &i, "<12> "))) {
3602 if (oldi > next_out) {
3603 SendToPlayer(&buf[next_out], oldi - next_out);
3606 started = STARTED_BOARD;
3611 if ((started == STARTED_NONE && looking_at(buf, &i, "\n<b1> ")) ||
3612 looking_at(buf, &i, "<b1> ")) {
3613 if (oldi > next_out) {
3614 SendToPlayer(&buf[next_out], oldi - next_out);
3617 started = STARTED_HOLDINGS;
3622 if (looking_at(buf, &i, "* *vs. * *--- *")) {
3624 /* Header for a move list -- first line */
3626 switch (ics_getting_history) {
3630 case BeginningOfGame:
3631 /* User typed "moves" or "oldmoves" while we
3632 were idle. Pretend we asked for these
3633 moves and soak them up so user can step
3634 through them and/or save them.
3637 gameMode = IcsObserving;
3640 ics_getting_history = H_GOT_UNREQ_HEADER;
3642 case EditGame: /*?*/
3643 case EditPosition: /*?*/
3644 /* Should above feature work in these modes too? */
3645 /* For now it doesn't */
3646 ics_getting_history = H_GOT_UNWANTED_HEADER;
3649 ics_getting_history = H_GOT_UNWANTED_HEADER;
3654 /* Is this the right one? */
3655 if (gameInfo.white && gameInfo.black &&
3656 strcmp(gameInfo.white, star_match[0]) == 0 &&
3657 strcmp(gameInfo.black, star_match[2]) == 0) {
3659 ics_getting_history = H_GOT_REQ_HEADER;
3662 case H_GOT_REQ_HEADER:
3663 case H_GOT_UNREQ_HEADER:
3664 case H_GOT_UNWANTED_HEADER:
3665 case H_GETTING_MOVES:
3666 /* Should not happen */
3667 DisplayError(_("Error gathering move list: two headers"), 0);
3668 ics_getting_history = H_FALSE;
3672 /* Save player ratings into gameInfo if needed */
3673 if ((ics_getting_history == H_GOT_REQ_HEADER ||
3674 ics_getting_history == H_GOT_UNREQ_HEADER) &&
3675 (gameInfo.whiteRating == -1 ||
3676 gameInfo.blackRating == -1)) {
3678 gameInfo.whiteRating = string_to_rating(star_match[1]);
3679 gameInfo.blackRating = string_to_rating(star_match[3]);
3680 if (appData.debugMode)
3681 fprintf(debugFP, "Ratings from header: W %d, B %d\n",
3682 gameInfo.whiteRating, gameInfo.blackRating);
3687 if (looking_at(buf, &i,
3688 "* * match, initial time: * minute*, increment: * second")) {
3689 /* Header for a move list -- second line */
3690 /* Initial board will follow if this is a wild game */
3691 if (gameInfo.event != NULL) free(gameInfo.event);
3692 snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]);
3693 gameInfo.event = StrSave(str);
3694 /* [HGM] we switched variant. Translate boards if needed. */
3695 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event));
3699 if (looking_at(buf, &i, "Move ")) {
3700 /* Beginning of a move list */
3701 switch (ics_getting_history) {
3703 /* Normally should not happen */
3704 /* Maybe user hit reset while we were parsing */
3707 /* Happens if we are ignoring a move list that is not
3708 * the one we just requested. Common if the user
3709 * tries to observe two games without turning off
3712 case H_GETTING_MOVES:
3713 /* Should not happen */
3714 DisplayError(_("Error gathering move list: nested"), 0);
3715 ics_getting_history = H_FALSE;
3717 case H_GOT_REQ_HEADER:
3718 ics_getting_history = H_GETTING_MOVES;
3719 started = STARTED_MOVES;
3721 if (oldi > next_out) {
3722 SendToPlayer(&buf[next_out], oldi - next_out);
3725 case H_GOT_UNREQ_HEADER:
3726 ics_getting_history = H_GETTING_MOVES;
3727 started = STARTED_MOVES_NOHIDE;
3730 case H_GOT_UNWANTED_HEADER:
3731 ics_getting_history = H_FALSE;
3737 if (looking_at(buf, &i, "% ") ||
3738 ((started == STARTED_MOVES || started == STARTED_MOVES_NOHIDE)
3739 && looking_at(buf, &i, "}*"))) { char *bookHit = NULL; // [HGM] book
3740 if(soughtPending && nrOfSeekAds) { // [HGM] seekgraph: on ICC sought-list has no termination line
3741 soughtPending = FALSE;
3745 if(suppressKibitz) next_out = i;
3746 savingComment = FALSE;
3750 case STARTED_MOVES_NOHIDE:
3751 memcpy(&parse[parse_pos], &buf[oldi], i - oldi);
3752 parse[parse_pos + i - oldi] = NULLCHAR;
3753 ParseGameHistory(parse);
3755 if (appData.zippyPlay && first.initDone) {
3756 FeedMovesToProgram(&first, forwardMostMove);
3757 if (gameMode == IcsPlayingWhite) {
3758 if (WhiteOnMove(forwardMostMove)) {
3759 if (first.sendTime) {
3760 if (first.useColors) {
3761 SendToProgram("black\n", &first);
3763 SendTimeRemaining(&first, TRUE);
3765 if (first.useColors) {
3766 SendToProgram("white\n", &first); // [HGM] book: made sending of "go\n" book dependent
3768 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: probe book for initial pos
3769 first.maybeThinking = TRUE;
3771 if (first.usePlayother) {
3772 if (first.sendTime) {
3773 SendTimeRemaining(&first, TRUE);
3775 SendToProgram("playother\n", &first);
3781 } else if (gameMode == IcsPlayingBlack) {
3782 if (!WhiteOnMove(forwardMostMove)) {
3783 if (first.sendTime) {
3784 if (first.useColors) {
3785 SendToProgram("white\n", &first);
3787 SendTimeRemaining(&first, FALSE);
3789 if (first.useColors) {
3790 SendToProgram("black\n", &first);
3792 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE);
3793 first.maybeThinking = TRUE;
3795 if (first.usePlayother) {
3796 if (first.sendTime) {
3797 SendTimeRemaining(&first, FALSE);
3799 SendToProgram("playother\n", &first);
3808 if (gameMode == IcsObserving && ics_gamenum == -1) {
3809 /* Moves came from oldmoves or moves command
3810 while we weren't doing anything else.
3812 currentMove = forwardMostMove;
3813 ClearHighlights();/*!!could figure this out*/
3814 flipView = appData.flipView;
3815 DrawPosition(TRUE, boards[currentMove]);
3816 DisplayBothClocks();
3817 snprintf(str, MSG_SIZ, "%s %s %s",
3818 gameInfo.white, _("vs."), gameInfo.black);
3822 /* Moves were history of an active game */
3823 if (gameInfo.resultDetails != NULL) {
3824 free(gameInfo.resultDetails);
3825 gameInfo.resultDetails = NULL;
3828 HistorySet(parseList, backwardMostMove,
3829 forwardMostMove, currentMove-1);
3830 DisplayMove(currentMove - 1);
3831 if (started == STARTED_MOVES) next_out = i;
3832 started = STARTED_NONE;
3833 ics_getting_history = H_FALSE;
3836 case STARTED_OBSERVE:
3837 started = STARTED_NONE;
3838 SendToICS(ics_prefix);
3839 SendToICS("refresh\n");
3845 if(bookHit) { // [HGM] book: simulate book reply
3846 static char bookMove[MSG_SIZ]; // a bit generous?
3848 programStats.nodes = programStats.depth = programStats.time =
3849 programStats.score = programStats.got_only_move = 0;
3850 sprintf(programStats.movelist, "%s (xbook)", bookHit);
3852 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
3853 strcat(bookMove, bookHit);
3854 HandleMachineMove(bookMove, &first);
3859 if ((started == STARTED_MOVES || started == STARTED_BOARD ||
3860 started == STARTED_HOLDINGS ||
3861 started == STARTED_MOVES_NOHIDE) && i >= leftover_len) {
3862 /* Accumulate characters in move list or board */
3863 parse[parse_pos++] = buf[i];
3866 /* Start of game messages. Mostly we detect start of game
3867 when the first board image arrives. On some versions
3868 of the ICS, though, we need to do a "refresh" after starting
3869 to observe in order to get the current board right away. */
3870 if (looking_at(buf, &i, "Adding game * to observation list")) {
3871 started = STARTED_OBSERVE;
3875 /* Handle auto-observe */
3876 if (appData.autoObserve &&
3877 (gameMode == IcsIdle || gameMode == BeginningOfGame) &&
3878 looking_at(buf, &i, "Game notification: * (*) vs. * (*)")) {
3880 /* Choose the player that was highlighted, if any. */
3881 if (star_match[0][0] == '\033' ||
3882 star_match[1][0] != '\033') {
3883 player = star_match[0];
3885 player = star_match[2];
3887 snprintf(str, MSG_SIZ, "%sobserve %s\n",
3888 ics_prefix, StripHighlightAndTitle(player));
3891 /* Save ratings from notify string */
3892 safeStrCpy(player1Name, star_match[0], sizeof(player1Name)/sizeof(player1Name[0]));
3893 player1Rating = string_to_rating(star_match[1]);
3894 safeStrCpy(player2Name, star_match[2], sizeof(player2Name)/sizeof(player2Name[0]));
3895 player2Rating = string_to_rating(star_match[3]);
3897 if (appData.debugMode)
3899 "Ratings from 'Game notification:' %s %d, %s %d\n",
3900 player1Name, player1Rating,
3901 player2Name, player2Rating);
3906 /* Deal with automatic examine mode after a game,
3907 and with IcsObserving -> IcsExamining transition */
3908 if (looking_at(buf, &i, "Entering examine mode for game *") ||
3909 looking_at(buf, &i, "has made you an examiner of game *")) {
3911 int gamenum = atoi(star_match[0]);
3912 if ((gameMode == IcsIdle || gameMode == IcsObserving) &&
3913 gamenum == ics_gamenum) {
3914 /* We were already playing or observing this game;
3915 no need to refetch history */
3916 gameMode = IcsExamining;
3918 pauseExamForwardMostMove = forwardMostMove;
3919 } else if (currentMove < forwardMostMove) {
3920 ForwardInner(forwardMostMove);
3923 /* I don't think this case really can happen */
3924 SendToICS(ics_prefix);
3925 SendToICS("refresh\n");
3930 /* Error messages */
3931 // if (ics_user_moved) {
3932 if (1) { // [HGM] old way ignored error after move type in; ics_user_moved is not set then!
3933 if (looking_at(buf, &i, "Illegal move") ||
3934 looking_at(buf, &i, "Not a legal move") ||
3935 looking_at(buf, &i, "Your king is in check") ||
3936 looking_at(buf, &i, "It isn't your turn") ||
3937 looking_at(buf, &i, "It is not your move")) {
3939 if (ics_user_moved && forwardMostMove > backwardMostMove) { // only backup if we already moved
3940 currentMove = forwardMostMove-1;
3941 DisplayMove(currentMove - 1); /* before DMError */
3942 DrawPosition(FALSE, boards[currentMove]);
3943 SwitchClocks(forwardMostMove-1); // [HGM] race
3944 DisplayBothClocks();
3946 DisplayMoveError(_("Illegal move (rejected by ICS)")); // [HGM] but always relay error msg
3952 if (looking_at(buf, &i, "still have time") ||
3953 looking_at(buf, &i, "not out of time") ||
3954 looking_at(buf, &i, "either player is out of time") ||
3955 looking_at(buf, &i, "has timeseal; checking")) {
3956 /* We must have called his flag a little too soon */
3957 whiteFlag = blackFlag = FALSE;
3961 if (looking_at(buf, &i, "added * seconds to") ||
3962 looking_at(buf, &i, "seconds were added to")) {
3963 /* Update the clocks */
3964 SendToICS(ics_prefix);
3965 SendToICS("refresh\n");
3969 if (!ics_clock_paused && looking_at(buf, &i, "clock paused")) {
3970 ics_clock_paused = TRUE;
3975 if (ics_clock_paused && looking_at(buf, &i, "clock resumed")) {
3976 ics_clock_paused = FALSE;
3981 /* Grab player ratings from the Creating: message.
3982 Note we have to check for the special case when
3983 the ICS inserts things like [white] or [black]. */
3984 if (looking_at(buf, &i, "Creating: * (*)* * (*)") ||
3985 looking_at(buf, &i, "Creating: * (*) [*] * (*)")) {
3987 0 player 1 name (not necessarily white)
3989 2 empty, white, or black (IGNORED)
3990 3 player 2 name (not necessarily black)
3993 The names/ratings are sorted out when the game
3994 actually starts (below).
3996 safeStrCpy(player1Name, StripHighlightAndTitle(star_match[0]), sizeof(player1Name)/sizeof(player1Name[0]));
3997 player1Rating = string_to_rating(star_match[1]);
3998 safeStrCpy(player2Name, StripHighlightAndTitle(star_match[3]), sizeof(player2Name)/sizeof(player2Name[0]));
3999 player2Rating = string_to_rating(star_match[4]);
4001 if (appData.debugMode)
4003 "Ratings from 'Creating:' %s %d, %s %d\n",
4004 player1Name, player1Rating,
4005 player2Name, player2Rating);
4010 /* Improved generic start/end-of-game messages */
4011 if ((tkind=0, looking_at(buf, &i, "{Game * (* vs. *) *}*")) ||
4012 (tkind=1, looking_at(buf, &i, "{Game * (*(*) vs. *(*)) *}*"))){
4013 /* If tkind == 0: */
4014 /* star_match[0] is the game number */
4015 /* [1] is the white player's name */
4016 /* [2] is the black player's name */
4017 /* For end-of-game: */
4018 /* [3] is the reason for the game end */
4019 /* [4] is a PGN end game-token, preceded by " " */
4020 /* For start-of-game: */
4021 /* [3] begins with "Creating" or "Continuing" */
4022 /* [4] is " *" or empty (don't care). */
4023 int gamenum = atoi(star_match[0]);
4024 char *whitename, *blackname, *why, *endtoken;
4025 ChessMove endtype = EndOfFile;
4028 whitename = star_match[1];
4029 blackname = star_match[2];
4030 why = star_match[3];
4031 endtoken = star_match[4];
4033 whitename = star_match[1];
4034 blackname = star_match[3];
4035 why = star_match[5];
4036 endtoken = star_match[6];
4039 /* Game start messages */
4040 if (strncmp(why, "Creating ", 9) == 0 ||
4041 strncmp(why, "Continuing ", 11) == 0) {
4042 gs_gamenum = gamenum;
4043 safeStrCpy(gs_kind, strchr(why, ' ') + 1,sizeof(gs_kind)/sizeof(gs_kind[0]));
4044 if(ics_gamenum == -1) // [HGM] only if we are not already involved in a game (because gin=1 sends us such messages)
4045 VariantSwitch(boards[currentMove], StringToVariant(gs_kind)); // [HGM] variantswitch: even before we get first board
4047 if (appData.zippyPlay) {
4048 ZippyGameStart(whitename, blackname);
4051 partnerBoardValid = FALSE; // [HGM] bughouse
4055 /* Game end messages */
4056 if (gameMode == IcsIdle || gameMode == BeginningOfGame ||
4057 ics_gamenum != gamenum) {
4060 while (endtoken[0] == ' ') endtoken++;
4061 switch (endtoken[0]) {
4064 endtype = GameUnfinished;
4067 endtype = BlackWins;
4070 if (endtoken[1] == '/')
4071 endtype = GameIsDrawn;
4073 endtype = WhiteWins;
4076 GameEnds(endtype, why, GE_ICS);
4078 if (appData.zippyPlay && first.initDone) {
4079 ZippyGameEnd(endtype, why);
4080 if (first.pr == NoProc) {
4081 /* Start the next process early so that we'll
4082 be ready for the next challenge */
4083 StartChessProgram(&first);
4085 /* Send "new" early, in case this command takes
4086 a long time to finish, so that we'll be ready
4087 for the next challenge. */
4088 gameInfo.variant = VariantNormal; // [HGM] variantswitch: suppress sending of 'variant'
4092 if(appData.bgObserve && partnerBoardValid) DrawPosition(TRUE, partnerBoard);
4096 if (looking_at(buf, &i, "Removing game * from observation") ||
4097 looking_at(buf, &i, "no longer observing game *") ||
4098 looking_at(buf, &i, "Game * (*) has no examiners")) {
4099 if (gameMode == IcsObserving &&
4100 atoi(star_match[0]) == ics_gamenum)
4102 /* icsEngineAnalyze */
4103 if (appData.icsEngineAnalyze) {
4110 ics_user_moved = FALSE;
4115 if (looking_at(buf, &i, "no longer examining game *")) {
4116 if (gameMode == IcsExamining &&
4117 atoi(star_match[0]) == ics_gamenum)
4121 ics_user_moved = FALSE;
4126 /* Advance leftover_start past any newlines we find,
4127 so only partial lines can get reparsed */
4128 if (looking_at(buf, &i, "\n")) {
4129 prevColor = curColor;
4130 if (curColor != ColorNormal) {
4131 if (oldi > next_out) {
4132 SendToPlayer(&buf[next_out], oldi - next_out);
4135 Colorize(ColorNormal, FALSE);
4136 curColor = ColorNormal;
4138 if (started == STARTED_BOARD) {
4139 started = STARTED_NONE;
4140 parse[parse_pos] = NULLCHAR;
4141 ParseBoard12(parse);
4144 /* Send premove here */
4145 if (appData.premove) {
4147 if (currentMove == 0 &&
4148 gameMode == IcsPlayingWhite &&
4149 appData.premoveWhite) {
4150 snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText);
4151 if (appData.debugMode)
4152 fprintf(debugFP, "Sending premove:\n");
4154 } else if (currentMove == 1 &&
4155 gameMode == IcsPlayingBlack &&
4156 appData.premoveBlack) {
4157 snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText);
4158 if (appData.debugMode)
4159 fprintf(debugFP, "Sending premove:\n");
4161 } else if (gotPremove) {
4163 ClearPremoveHighlights();
4164 if (appData.debugMode)
4165 fprintf(debugFP, "Sending premove:\n");
4166 UserMoveEvent(premoveFromX, premoveFromY,
4167 premoveToX, premoveToY,
4172 /* Usually suppress following prompt */
4173 if (!(forwardMostMove == 0 && gameMode == IcsExamining)) {
4174 while(looking_at(buf, &i, "\n")); // [HGM] skip empty lines
4175 if (looking_at(buf, &i, "*% ")) {
4176 savingComment = FALSE;
4181 } else if (started == STARTED_HOLDINGS) {
4183 char new_piece[MSG_SIZ];
4184 started = STARTED_NONE;
4185 parse[parse_pos] = NULLCHAR;
4186 if (appData.debugMode)
4187 fprintf(debugFP, "Parsing holdings: %s, currentMove = %d\n",
4188 parse, currentMove);
4189 if (sscanf(parse, " game %d", &gamenum) == 1) {
4190 if(gamenum == ics_gamenum) { // [HGM] bughouse: old code if part of foreground game
4191 if (gameInfo.variant == VariantNormal) {
4192 /* [HGM] We seem to switch variant during a game!
4193 * Presumably no holdings were displayed, so we have
4194 * to move the position two files to the right to
4195 * create room for them!
4197 VariantClass newVariant;
4198 switch(gameInfo.boardWidth) { // base guess on board width
4199 case 9: newVariant = VariantShogi; break;
4200 case 10: newVariant = VariantGreat; break;
4201 default: newVariant = VariantCrazyhouse; break;
4203 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4204 /* Get a move list just to see the header, which
4205 will tell us whether this is really bug or zh */
4206 if (ics_getting_history == H_FALSE) {
4207 ics_getting_history = H_REQUESTED;
4208 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4212 new_piece[0] = NULLCHAR;
4213 sscanf(parse, "game %d white [%s black [%s <- %s",
4214 &gamenum, white_holding, black_holding,
4216 white_holding[strlen(white_holding)-1] = NULLCHAR;
4217 black_holding[strlen(black_holding)-1] = NULLCHAR;
4218 /* [HGM] copy holdings to board holdings area */
4219 CopyHoldings(boards[forwardMostMove], white_holding, WhitePawn);
4220 CopyHoldings(boards[forwardMostMove], black_holding, BlackPawn);
4221 boards[forwardMostMove][HOLDINGS_SET] = 1; // flag holdings as set
4223 if (appData.zippyPlay && first.initDone) {
4224 ZippyHoldings(white_holding, black_holding,
4228 if (tinyLayout || smallLayout) {
4229 char wh[16], bh[16];
4230 PackHolding(wh, white_holding);
4231 PackHolding(bh, black_holding);
4232 snprintf(str, MSG_SIZ, "[%s-%s] %s-%s", wh, bh,
4233 gameInfo.white, gameInfo.black);
4235 snprintf(str, MSG_SIZ, "%s [%s] %s %s [%s]",
4236 gameInfo.white, white_holding, _("vs."),
4237 gameInfo.black, black_holding);
4239 if(!partnerUp) // [HGM] bughouse: when peeking at partner game we already know what he captured...
4240 DrawPosition(FALSE, boards[currentMove]);
4242 } else if(appData.bgObserve) { // [HGM] bughouse: holdings of other game => background
4243 sscanf(parse, "game %d white [%s black [%s <- %s",
4244 &gamenum, white_holding, black_holding,
4246 white_holding[strlen(white_holding)-1] = NULLCHAR;
4247 black_holding[strlen(black_holding)-1] = NULLCHAR;
4248 /* [HGM] copy holdings to partner-board holdings area */
4249 CopyHoldings(partnerBoard, white_holding, WhitePawn);
4250 CopyHoldings(partnerBoard, black_holding, BlackPawn);
4251 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual: always draw
4252 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4253 if(twoBoards) { partnerUp = 0; flipView = !flipView; }
4256 /* Suppress following prompt */
4257 if (looking_at(buf, &i, "*% ")) {
4258 if(strchr(star_match[0], 7)) SendToPlayer("\007", 1); // Bell(); // FICS fuses bell for next board with prompt in zh captures
4259 savingComment = FALSE;
4267 i++; /* skip unparsed character and loop back */
4270 if (started != STARTED_MOVES && started != STARTED_BOARD && !suppressKibitz && // [HGM] kibitz
4271 // started != STARTED_HOLDINGS && i > next_out) { // [HGM] should we compare to leftover_start in stead of i?
4272 // SendToPlayer(&buf[next_out], i - next_out);
4273 started != STARTED_HOLDINGS && leftover_start > next_out) {
4274 SendToPlayer(&buf[next_out], leftover_start - next_out);
4278 leftover_len = buf_len - leftover_start;
4279 /* if buffer ends with something we couldn't parse,
4280 reparse it after appending the next read */
4282 } else if (count == 0) {
4283 RemoveInputSource(isr);
4284 DisplayFatalError(_("Connection closed by ICS"), 0, 0);
4286 DisplayFatalError(_("Error reading from ICS"), error, 1);
4291 /* Board style 12 looks like this:
4293 <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
4295 * The "<12> " is stripped before it gets to this routine. The two
4296 * trailing 0's (flip state and clock ticking) are later addition, and
4297 * some chess servers may not have them, or may have only the first.
4298 * Additional trailing fields may be added in the future.
4301 #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"
4303 #define RELATION_OBSERVING_PLAYED 0
4304 #define RELATION_OBSERVING_STATIC -2 /* examined, oldmoves, or smoves */
4305 #define RELATION_PLAYING_MYMOVE 1
4306 #define RELATION_PLAYING_NOTMYMOVE -1
4307 #define RELATION_EXAMINING 2
4308 #define RELATION_ISOLATED_BOARD -3
4309 #define RELATION_STARTING_POSITION -4 /* FICS only */
4312 ParseBoard12 (char *string)
4316 char *bookHit = NULL; // [HGM] book
4318 GameMode newGameMode;
4319 int gamenum, newGame, newMove, relation, basetime, increment, ics_flip = 0;
4320 int j, k, n, moveNum, white_stren, black_stren, white_time, black_time;
4321 int double_push, castle_ws, castle_wl, castle_bs, castle_bl, irrev_count;
4322 char to_play, board_chars[200];
4323 char move_str[MSG_SIZ], str[MSG_SIZ], elapsed_time[MSG_SIZ];
4324 char black[32], white[32];
4326 int prevMove = currentMove;
4329 int fromX, fromY, toX, toY;
4331 int ranks=1, files=0; /* [HGM] ICS80: allow variable board size */
4332 Boolean weird = FALSE, reqFlag = FALSE;
4334 fromX = fromY = toX = toY = -1;
4338 if (appData.debugMode)
4339 fprintf(debugFP, "Parsing board: %s\n", string);
4341 move_str[0] = NULLCHAR;
4342 elapsed_time[0] = NULLCHAR;
4343 { /* [HGM] figure out how many ranks and files the board has, for ICS extension used by Capablanca server */
4345 while(i < 199 && (string[i] != ' ' || string[i+2] != ' ')) {
4346 if(string[i] == ' ') { ranks++; files = 0; }
4348 if(!strchr(" -pnbrqkPNBRQK" , string[i])) weird = TRUE; // test for fairies
4351 for(j = 0; j <i; j++) board_chars[j] = string[j];
4352 board_chars[i] = '\0';
4355 n = sscanf(string, PATTERN, &to_play, &double_push,
4356 &castle_ws, &castle_wl, &castle_bs, &castle_bl, &irrev_count,
4357 &gamenum, white, black, &relation, &basetime, &increment,
4358 &white_stren, &black_stren, &white_time, &black_time,
4359 &moveNum, str, elapsed_time, move_str, &ics_flip,
4363 snprintf(str, MSG_SIZ, _("Failed to parse board string:\n\"%s\""), string);
4364 DisplayError(str, 0);
4368 /* Convert the move number to internal form */
4369 moveNum = (moveNum - 1) * 2;
4370 if (to_play == 'B') moveNum++;
4371 if (moveNum > framePtr) { // [HGM] vari: do not run into saved variations
4372 DisplayFatalError(_("Game too long; increase MAX_MOVES and recompile"),
4378 case RELATION_OBSERVING_PLAYED:
4379 case RELATION_OBSERVING_STATIC:
4380 if (gamenum == -1) {
4381 /* Old ICC buglet */
4382 relation = RELATION_OBSERVING_STATIC;
4384 newGameMode = IcsObserving;
4386 case RELATION_PLAYING_MYMOVE:
4387 case RELATION_PLAYING_NOTMYMOVE:
4389 ((relation == RELATION_PLAYING_MYMOVE) == (to_play == 'W')) ?
4390 IcsPlayingWhite : IcsPlayingBlack;
4391 soughtPending =FALSE; // [HGM] seekgraph: solve race condition
4393 case RELATION_EXAMINING:
4394 newGameMode = IcsExamining;
4396 case RELATION_ISOLATED_BOARD:
4398 /* Just display this board. If user was doing something else,
4399 we will forget about it until the next board comes. */
4400 newGameMode = IcsIdle;
4402 case RELATION_STARTING_POSITION:
4403 newGameMode = gameMode;
4407 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
4408 gameMode == IcsObserving && appData.dualBoard) // also allow use of second board for observing two games
4409 && newGameMode == IcsObserving && gamenum != ics_gamenum && appData.bgObserve) {
4410 // [HGM] bughouse: don't act on alien boards while we play. Just parse the board and save it */
4411 int fac = strchr(elapsed_time, '.') ? 1 : 1000;
4412 static int lastBgGame = -1;
4414 for (k = 0; k < ranks; k++) {
4415 for (j = 0; j < files; j++)
4416 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4417 if(gameInfo.holdingsWidth > 1) {
4418 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4419 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4422 CopyBoard(partnerBoard, board);
4423 if(toSqr = strchr(str, '/')) { // extract highlights from long move
4424 partnerBoard[EP_STATUS-3] = toSqr[1] - AAA; // kludge: hide highlighting info in board
4425 partnerBoard[EP_STATUS-4] = toSqr[2] - ONE;
4426 } else partnerBoard[EP_STATUS-4] = partnerBoard[EP_STATUS-3] = -1;
4427 if(toSqr = strchr(str, '-')) {
4428 partnerBoard[EP_STATUS-1] = toSqr[1] - AAA;
4429 partnerBoard[EP_STATUS-2] = toSqr[2] - ONE;
4430 } else partnerBoard[EP_STATUS-1] = partnerBoard[EP_STATUS-2] = -1;
4431 if(appData.dualBoard && !twoBoards) { twoBoards = 1; InitDrawingSizes(-2,0); }
4432 if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual
4433 if(partnerUp) DrawPosition(FALSE, partnerBoard);
4435 DisplayWhiteClock(white_time*fac, to_play == 'W');
4436 DisplayBlackClock(black_time*fac, to_play != 'W');
4437 activePartner = to_play;
4438 if(gamenum != lastBgGame) {
4440 snprintf(buf, MSG_SIZ, "%s %s %s", white, _("vs."), black);
4443 lastBgGame = gamenum;
4444 activePartnerTime = to_play == 'W' ? white_time*fac : black_time*fac;
4445 partnerUp = 0; flipView = !flipView; } // [HGM] dual
4446 snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time*fac/60000, (white_time*fac%60000)/1000,
4447 (black_time*fac/60000), (black_time*fac%60000)/1000, white_stren, black_stren, to_play);
4448 if(!twoBoards) DisplayMessage(partnerStatus, "");
4449 partnerBoardValid = TRUE;
4453 if(appData.dualBoard && appData.bgObserve) {
4454 if((newGameMode == IcsPlayingWhite || newGameMode == IcsPlayingBlack) && moveNum == 1)
4455 SendToICS(ics_prefix), SendToICS("pobserve\n");
4456 else if(newGameMode == IcsObserving && (gameMode == BeginningOfGame || gameMode == IcsIdle)) {
4458 snprintf(buf, MSG_SIZ, "%spobserve %s\n", ics_prefix, white);
4463 /* Modify behavior for initial board display on move listing
4466 switch (ics_getting_history) {
4470 case H_GOT_REQ_HEADER:
4471 case H_GOT_UNREQ_HEADER:
4472 /* This is the initial position of the current game */
4473 gamenum = ics_gamenum;
4474 moveNum = 0; /* old ICS bug workaround */
4475 if (to_play == 'B') {
4476 startedFromSetupPosition = TRUE;
4477 blackPlaysFirst = TRUE;
4479 if (forwardMostMove == 0) forwardMostMove = 1;
4480 if (backwardMostMove == 0) backwardMostMove = 1;
4481 if (currentMove == 0) currentMove = 1;
4483 newGameMode = gameMode;
4484 relation = RELATION_STARTING_POSITION; /* ICC needs this */
4486 case H_GOT_UNWANTED_HEADER:
4487 /* This is an initial board that we don't want */
4489 case H_GETTING_MOVES:
4490 /* Should not happen */
4491 DisplayError(_("Error gathering move list: extra board"), 0);
4492 ics_getting_history = H_FALSE;
4496 if (gameInfo.boardHeight != ranks || gameInfo.boardWidth != files ||
4497 move_str[1] == '@' && !gameInfo.holdingsWidth ||
4498 weird && (int)gameInfo.variant < (int)VariantShogi) {
4499 /* [HGM] We seem to have switched variant unexpectedly
4500 * Try to guess new variant from board size
4502 VariantClass newVariant = VariantFairy; // if 8x8, but fairies present
4503 if(ranks == 8 && files == 10) newVariant = VariantCapablanca; else
4504 if(ranks == 10 && files == 9) newVariant = VariantXiangqi; else
4505 if(ranks == 8 && files == 12) newVariant = VariantCourier; else
4506 if(ranks == 9 && files == 9) newVariant = VariantShogi; else
4507 if(ranks == 10 && files == 10) newVariant = VariantGrand; else
4508 if(!weird) newVariant = move_str[1] == '@' ? VariantCrazyhouse : VariantNormal;
4509 VariantSwitch(boards[currentMove], newVariant); /* temp guess */
4510 /* Get a move list just to see the header, which
4511 will tell us whether this is really bug or zh */
4512 if (ics_getting_history == H_FALSE) {
4513 ics_getting_history = H_REQUESTED; reqFlag = TRUE;
4514 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4519 /* Take action if this is the first board of a new game, or of a
4520 different game than is currently being displayed. */
4521 if (gamenum != ics_gamenum || newGameMode != gameMode ||
4522 relation == RELATION_ISOLATED_BOARD) {
4524 /* Forget the old game and get the history (if any) of the new one */
4525 if (gameMode != BeginningOfGame) {
4529 if (appData.autoRaiseBoard) BoardToTop();
4531 if (gamenum == -1) {
4532 newGameMode = IcsIdle;
4533 } else if ((moveNum > 0 || newGameMode == IcsObserving) && newGameMode != IcsIdle &&
4534 appData.getMoveList && !reqFlag) {
4535 /* Need to get game history */
4536 ics_getting_history = H_REQUESTED;
4537 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4541 /* Initially flip the board to have black on the bottom if playing
4542 black or if the ICS flip flag is set, but let the user change
4543 it with the Flip View button. */
4544 flipView = appData.autoFlipView ?
4545 (newGameMode == IcsPlayingBlack) || ics_flip :
4548 /* Done with values from previous mode; copy in new ones */
4549 gameMode = newGameMode;
4551 ics_gamenum = gamenum;
4552 if (gamenum == gs_gamenum) {
4553 int klen = strlen(gs_kind);
4554 if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR;
4555 snprintf(str, MSG_SIZ, "ICS %s", gs_kind);
4556 gameInfo.event = StrSave(str);
4558 gameInfo.event = StrSave("ICS game");
4560 gameInfo.site = StrSave(appData.icsHost);
4561 gameInfo.date = PGNDate();
4562 gameInfo.round = StrSave("-");
4563 gameInfo.white = StrSave(white);
4564 gameInfo.black = StrSave(black);
4565 timeControl = basetime * 60 * 1000;
4567 timeIncrement = increment * 1000;
4568 movesPerSession = 0;
4569 gameInfo.timeControl = TimeControlTagValue();
4570 VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event) );
4571 if (appData.debugMode) {
4572 fprintf(debugFP, "ParseBoard says variant = '%s'\n", gameInfo.event);
4573 fprintf(debugFP, "recognized as %s\n", VariantName(gameInfo.variant));
4574 setbuf(debugFP, NULL);
4577 gameInfo.outOfBook = NULL;
4579 /* Do we have the ratings? */
4580 if (strcmp(player1Name, white) == 0 &&
4581 strcmp(player2Name, black) == 0) {
4582 if (appData.debugMode)
4583 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4584 player1Rating, player2Rating);
4585 gameInfo.whiteRating = player1Rating;
4586 gameInfo.blackRating = player2Rating;
4587 } else if (strcmp(player2Name, white) == 0 &&
4588 strcmp(player1Name, black) == 0) {
4589 if (appData.debugMode)
4590 fprintf(debugFP, "Remembered ratings: W %d, B %d\n",
4591 player2Rating, player1Rating);
4592 gameInfo.whiteRating = player2Rating;
4593 gameInfo.blackRating = player1Rating;
4595 player1Name[0] = player2Name[0] = NULLCHAR;
4597 /* Silence shouts if requested */
4598 if (appData.quietPlay &&
4599 (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)) {
4600 SendToICS(ics_prefix);
4601 SendToICS("set shout 0\n");
4605 /* Deal with midgame name changes */
4607 if (!gameInfo.white || strcmp(gameInfo.white, white) != 0) {
4608 if (gameInfo.white) free(gameInfo.white);
4609 gameInfo.white = StrSave(white);
4611 if (!gameInfo.black || strcmp(gameInfo.black, black) != 0) {
4612 if (gameInfo.black) free(gameInfo.black);
4613 gameInfo.black = StrSave(black);
4617 /* Throw away game result if anything actually changes in examine mode */
4618 if (gameMode == IcsExamining && !newGame) {
4619 gameInfo.result = GameUnfinished;
4620 if (gameInfo.resultDetails != NULL) {
4621 free(gameInfo.resultDetails);
4622 gameInfo.resultDetails = NULL;
4626 /* In pausing && IcsExamining mode, we ignore boards coming
4627 in if they are in a different variation than we are. */
4628 if (pauseExamInvalid) return;
4629 if (pausing && gameMode == IcsExamining) {
4630 if (moveNum <= pauseExamForwardMostMove) {
4631 pauseExamInvalid = TRUE;
4632 forwardMostMove = pauseExamForwardMostMove;
4637 if (appData.debugMode) {
4638 fprintf(debugFP, "load %dx%d board\n", files, ranks);
4640 /* Parse the board */
4641 for (k = 0; k < ranks; k++) {
4642 for (j = 0; j < files; j++)
4643 board[k][j+gameInfo.holdingsWidth] = CharToPiece(board_chars[(ranks-1-k)*(files+1) + j]);
4644 if(gameInfo.holdingsWidth > 1) {
4645 board[k][0] = board[k][BOARD_WIDTH-1] = EmptySquare;
4646 board[k][1] = board[k][BOARD_WIDTH-2] = (ChessSquare) 0;;
4649 if(moveNum==0 && gameInfo.variant == VariantSChess) {
4650 board[5][BOARD_RGHT+1] = WhiteAngel;
4651 board[6][BOARD_RGHT+1] = WhiteMarshall;
4652 board[1][0] = BlackMarshall;
4653 board[2][0] = BlackAngel;
4654 board[1][1] = board[2][1] = board[5][BOARD_RGHT] = board[6][BOARD_RGHT] = 1;
4656 CopyBoard(boards[moveNum], board);
4657 boards[moveNum][HOLDINGS_SET] = 0; // [HGM] indicate holdings not set
4659 startedFromSetupPosition =
4660 !CompareBoards(board, initialPosition);
4661 if(startedFromSetupPosition)
4662 initialRulePlies = irrev_count; /* [HGM] 50-move counter offset */
4665 /* [HGM] Set castling rights. Take the outermost Rooks,
4666 to make it also work for FRC opening positions. Note that board12
4667 is really defective for later FRC positions, as it has no way to
4668 indicate which Rook can castle if they are on the same side of King.
4669 For the initial position we grant rights to the outermost Rooks,
4670 and remember thos rights, and we then copy them on positions
4671 later in an FRC game. This means WB might not recognize castlings with
4672 Rooks that have moved back to their original position as illegal,
4673 but in ICS mode that is not its job anyway.
4675 if(moveNum == 0 || gameInfo.variant != VariantFischeRandom)
4676 { int i, j; ChessSquare wKing = WhiteKing, bKing = BlackKing;
4678 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4679 if(board[0][i] == WhiteRook) j = i;
4680 initialRights[0] = boards[moveNum][CASTLING][0] = (castle_ws == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4681 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4682 if(board[0][i] == WhiteRook) j = i;
4683 initialRights[1] = boards[moveNum][CASTLING][1] = (castle_wl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4684 for(i=BOARD_LEFT, j=NoRights; i<BOARD_RGHT; i++)
4685 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4686 initialRights[3] = boards[moveNum][CASTLING][3] = (castle_bs == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4687 for(i=BOARD_RGHT-1, j=NoRights; i>=BOARD_LEFT; i--)
4688 if(board[BOARD_HEIGHT-1][i] == BlackRook) j = i;
4689 initialRights[4] = boards[moveNum][CASTLING][4] = (castle_bl == 0 && gameInfo.variant != VariantFischeRandom ? NoRights : j);
4691 boards[moveNum][CASTLING][2] = boards[moveNum][CASTLING][5] = NoRights;
4692 if(gameInfo.variant == VariantKnightmate) { wKing = WhiteUnicorn; bKing = BlackUnicorn; }
4693 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4694 if(board[0][k] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = k;
4695 for(k=BOARD_LEFT; k<BOARD_RGHT; k++)
4696 if(board[BOARD_HEIGHT-1][k] == bKing)
4697 initialRights[5] = boards[moveNum][CASTLING][5] = k;
4698 if(gameInfo.variant == VariantTwoKings) {
4699 // In TwoKings looking for a King does not work, so always give castling rights to a King on e1/e8
4700 if(board[0][4] == wKing) initialRights[2] = boards[moveNum][CASTLING][2] = 4;
4701 if(board[BOARD_HEIGHT-1][4] == bKing) initialRights[5] = boards[moveNum][CASTLING][5] = 4;
4704 r = boards[moveNum][CASTLING][0] = initialRights[0];
4705 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][0] = NoRights;
4706 r = boards[moveNum][CASTLING][1] = initialRights[1];
4707 if(board[0][r] != WhiteRook) boards[moveNum][CASTLING][1] = NoRights;
4708 r = boards[moveNum][CASTLING][3] = initialRights[3];
4709 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][3] = NoRights;
4710 r = boards[moveNum][CASTLING][4] = initialRights[4];
4711 if(board[BOARD_HEIGHT-1][r] != BlackRook) boards[moveNum][CASTLING][4] = NoRights;
4712 /* wildcastle kludge: always assume King has rights */
4713 r = boards[moveNum][CASTLING][2] = initialRights[2];
4714 r = boards[moveNum][CASTLING][5] = initialRights[5];
4716 /* [HGM] e.p. rights. Assume that ICS sends file number here? */
4717 boards[moveNum][EP_STATUS] = EP_NONE;
4718 if(str[0] == 'P') boards[moveNum][EP_STATUS] = EP_PAWN_MOVE;
4719 if(strchr(move_str, 'x')) boards[moveNum][EP_STATUS] = EP_CAPTURE;
4720 if(double_push != -1) boards[moveNum][EP_STATUS] = double_push + BOARD_LEFT;
4723 if (ics_getting_history == H_GOT_REQ_HEADER ||
4724 ics_getting_history == H_GOT_UNREQ_HEADER) {
4725 /* This was an initial position from a move list, not
4726 the current position */
4730 /* Update currentMove and known move number limits */
4731 newMove = newGame || moveNum > forwardMostMove;
4734 forwardMostMove = backwardMostMove = currentMove = moveNum;
4735 if (gameMode == IcsExamining && moveNum == 0) {
4736 /* Workaround for ICS limitation: we are not told the wild
4737 type when starting to examine a game. But if we ask for
4738 the move list, the move list header will tell us */
4739 ics_getting_history = H_REQUESTED;
4740 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4743 } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove
4744 || (moveNum < forwardMostMove && moveNum >= backwardMostMove)) {
4746 /* [DM] If we found takebacks during icsEngineAnalyze try send to engine */
4747 /* [HGM] applied this also to an engine that is silently watching */
4748 if (appData.zippyPlay && moveNum < forwardMostMove && first.initDone &&
4749 (gameMode == IcsObserving || gameMode == IcsExamining) &&
4750 gameInfo.variant == currentlyInitializedVariant) {
4751 takeback = forwardMostMove - moveNum;
4752 for (i = 0; i < takeback; i++) {
4753 if (appData.debugMode) fprintf(debugFP, "take back move\n");
4754 SendToProgram("undo\n", &first);
4759 forwardMostMove = moveNum;
4760 if (!pausing || currentMove > forwardMostMove)
4761 currentMove = forwardMostMove;
4763 /* New part of history that is not contiguous with old part */
4764 if (pausing && gameMode == IcsExamining) {
4765 pauseExamInvalid = TRUE;
4766 forwardMostMove = pauseExamForwardMostMove;
4769 if (gameMode == IcsExamining && moveNum > 0 && appData.getMoveList) {
4771 if(appData.zippyPlay && forwardMostMove > 0 && first.initDone) {
4772 // [HGM] when we will receive the move list we now request, it will be
4773 // fed to the engine from the first move on. So if the engine is not
4774 // in the initial position now, bring it there.
4775 InitChessProgram(&first, 0);
4778 ics_getting_history = H_REQUESTED;
4779 snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum);
4782 forwardMostMove = backwardMostMove = currentMove = moveNum;
4785 /* Update the clocks */
4786 if (strchr(elapsed_time, '.')) {
4788 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time;
4789 timeRemaining[1][moveNum] = blackTimeRemaining = black_time;
4791 /* Time is in seconds */
4792 timeRemaining[0][moveNum] = whiteTimeRemaining = white_time * 1000;
4793 timeRemaining[1][moveNum] = blackTimeRemaining = black_time * 1000;
4798 if (appData.zippyPlay && newGame &&
4799 gameMode != IcsObserving && gameMode != IcsIdle &&
4800 gameMode != IcsExamining)
4801 ZippyFirstBoard(moveNum, basetime, increment);
4804 /* Put the move on the move list, first converting
4805 to canonical algebraic form. */
4807 if (appData.debugMode) {
4808 int f = forwardMostMove;
4809 fprintf(debugFP, "parseboard %d, castling = %d %d %d %d %d %d\n", f,
4810 boards[f][CASTLING][0],boards[f][CASTLING][1],boards[f][CASTLING][2],
4811 boards[f][CASTLING][3],boards[f][CASTLING][4],boards[f][CASTLING][5]);
4812 fprintf(debugFP, "accepted move %s from ICS, parse it.\n", move_str);
4813 fprintf(debugFP, "moveNum = %d\n", moveNum);
4814 fprintf(debugFP, "board = %d-%d x %d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT);
4815 setbuf(debugFP, NULL);
4817 if (moveNum <= backwardMostMove) {
4818 /* We don't know what the board looked like before
4820 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4821 strcat(parseList[moveNum - 1], " ");
4822 strcat(parseList[moveNum - 1], elapsed_time);
4823 moveList[moveNum - 1][0] = NULLCHAR;
4824 } else if (strcmp(move_str, "none") == 0) {
4825 // [HGM] long SAN: swapped order; test for 'none' before parsing move
4826 /* Again, we don't know what the board looked like;
4827 this is really the start of the game. */
4828 parseList[moveNum - 1][0] = NULLCHAR;
4829 moveList[moveNum - 1][0] = NULLCHAR;
4830 backwardMostMove = moveNum;
4831 startedFromSetupPosition = TRUE;
4832 fromX = fromY = toX = toY = -1;
4834 // [HGM] long SAN: if legality-testing is off, disambiguation might not work or give wrong move.
4835 // So we parse the long-algebraic move string in stead of the SAN move
4836 int valid; char buf[MSG_SIZ], *prom;
4838 if(gameInfo.variant == VariantShogi && !strchr(move_str, '=') && !strchr(move_str, '@'))
4839 strcat(move_str, "="); // if ICS does not say 'promote' on non-drop, we defer.
4840 // str looks something like "Q/a1-a2"; kill the slash
4842 snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2);
4843 else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling
4844 if((prom = strstr(move_str, "=")) && !strstr(buf, "="))
4845 strcat(buf, prom); // long move lacks promo specification!
4846 if(!appData.testLegality && move_str[1] != '@') { // drops never ambiguous (parser chokes on long form!)
4847 if(appData.debugMode)
4848 fprintf(debugFP, "replaced ICS move '%s' by '%s'\n", move_str, buf);
4849 safeStrCpy(move_str, buf, MSG_SIZ);
4851 valid = ParseOneMove(move_str, moveNum - 1, &moveType,
4852 &fromX, &fromY, &toX, &toY, &promoChar)
4853 || ParseOneMove(buf, moveNum - 1, &moveType,
4854 &fromX, &fromY, &toX, &toY, &promoChar);
4855 // end of long SAN patch
4857 (void) CoordsToAlgebraic(boards[moveNum - 1],
4858 PosFlags(moveNum - 1),
4859 fromY, fromX, toY, toX, promoChar,
4860 parseList[moveNum-1]);
4861 switch (MateTest(boards[moveNum], PosFlags(moveNum)) ) {
4867 if(!IS_SHOGI(gameInfo.variant))
4868 strcat(parseList[moveNum - 1], "+");
4871 case MT_STAINMATE: // [HGM] xq: for notation stalemate that wins counts as checkmate
4872 strcat(parseList[moveNum - 1], "#");
4875 strcat(parseList[moveNum - 1], " ");
4876 strcat(parseList[moveNum - 1], elapsed_time);
4877 /* currentMoveString is set as a side-effect of ParseOneMove */
4878 if(gameInfo.variant == VariantShogi && currentMoveString[4]) currentMoveString[4] = '^';
4879 safeStrCpy(moveList[moveNum - 1], currentMoveString, sizeof(moveList[moveNum - 1])/sizeof(moveList[moveNum - 1][0]));
4880 strcat(moveList[moveNum - 1], "\n");
4882 if(gameInfo.holdingsWidth && !appData.disguise && gameInfo.variant != VariantSuper && gameInfo.variant != VariantGreat
4883 && gameInfo.variant != VariantGrand&& gameInfo.variant != VariantSChess) // inherit info that ICS does not give from previous board
4884 for(k=0; k<ranks; k++) for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
4885 ChessSquare old, new = boards[moveNum][k][j];
4886 if(fromY == DROP_RANK && k==toY && j==toX) continue; // dropped pieces always stand for themselves
4887 old = (k==toY && j==toX) ? boards[moveNum-1][fromY][fromX] : boards[moveNum-1][k][j]; // trace back mover
4888 if(old == new) continue;
4889 if(old == PROMOTED new) boards[moveNum][k][j] = old; // prevent promoted pieces to revert to primordial ones
4890 else if(new == WhiteWazir || new == BlackWazir) {
4891 if(old < WhiteCannon || old >= BlackPawn && old < BlackCannon)
4892 boards[moveNum][k][j] = PROMOTED old; // choose correct type of Gold in promotion
4893 else boards[moveNum][k][j] = old; // preserve type of Gold
4894 } else if((old == WhitePawn || old == BlackPawn) && new != EmptySquare) // Pawn promotions (but not e.p.capture!)
4895 boards[moveNum][k][j] = PROMOTED new; // use non-primordial representation of chosen piece
4898 /* Move from ICS was illegal!? Punt. */
4899 if (appData.debugMode) {
4900 fprintf(debugFP, "Illegal move from ICS '%s'\n", move_str);
4901 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
4903 safeStrCpy(parseList[moveNum - 1], move_str, sizeof(parseList[moveNum - 1])/sizeof(parseList[moveNum - 1][0]));
4904 strcat(parseList[moveNum - 1], " ");
4905 strcat(parseList[moveNum - 1], elapsed_time);
4906 moveList[moveNum - 1][0] = NULLCHAR;
4907 fromX = fromY = toX = toY = -1;
4910 if (appData.debugMode) {
4911 fprintf(debugFP, "Move parsed to '%s'\n", parseList[moveNum - 1]);
4912 setbuf(debugFP, NULL);
4916 /* Send move to chess program (BEFORE animating it). */
4917 if (appData.zippyPlay && !newGame && newMove &&
4918 (!appData.getMoveList || backwardMostMove == 0) && first.initDone) {
4920 if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) ||
4921 (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) {
4922 if (moveList[moveNum - 1][0] == NULLCHAR) {
4923 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"),
4925 DisplayError(str, 0);
4927 if (first.sendTime) {
4928 SendTimeRemaining(&first, gameMode == IcsPlayingWhite);
4930 bookHit = SendMoveToBookUser(moveNum - 1, &first, FALSE); // [HGM] book
4931 if (firstMove && !bookHit) {
4933 if (first.useColors) {
4934 SendToProgram(gameMode == IcsPlayingWhite ?
4936 "black\ngo\n", &first);
4938 SendToProgram("go\n", &first);
4940 first.maybeThinking = TRUE;
4943 } else if (gameMode == IcsObserving || gameMode == IcsExamining) {
4944 if (moveList[moveNum - 1][0] == NULLCHAR) {
4945 snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str);
4946 DisplayError(str, 0);
4948 if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand!
4949 SendMoveToProgram(moveNum - 1, &first);
4956 if (moveNum > 0 && !gotPremove && !appData.noGUI) {
4957 /* If move comes from a remote source, animate it. If it
4958 isn't remote, it will have already been animated. */
4959 if (!pausing && !ics_user_moved && prevMove == moveNum - 1) {
4960 AnimateMove(boards[moveNum - 1], fromX, fromY, toX, toY);
4962 if (!pausing && appData.highlightLastMove) {
4963 SetHighlights(fromX, fromY, toX, toY);
4967 /* Start the clocks */
4968 whiteFlag = blackFlag = FALSE;
4969 appData.clockMode = !(basetime == 0 && increment == 0);
4971 ics_clock_paused = TRUE;
4973 } else if (ticking == 1) {
4974 ics_clock_paused = FALSE;
4976 if (gameMode == IcsIdle ||
4977 relation == RELATION_OBSERVING_STATIC ||
4978 relation == RELATION_EXAMINING ||
4980 DisplayBothClocks();
4984 /* Display opponents and material strengths */
4985 if (gameInfo.variant != VariantBughouse &&
4986 gameInfo.variant != VariantCrazyhouse && !appData.noGUI) {
4987 if (tinyLayout || smallLayout) {
4988 if(gameInfo.variant == VariantNormal)
4989 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}",
4990 gameInfo.white, white_stren, gameInfo.black, black_stren,
4991 basetime, increment);
4993 snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}",
4994 gameInfo.white, white_stren, gameInfo.black, black_stren,
4995 basetime, increment, (int) gameInfo.variant);
4997 if(gameInfo.variant == VariantNormal)
4998 snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d}",
4999 gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
5000 basetime, increment);
5002 snprintf(str, MSG_SIZ, "%s (%d) %s %s (%d) {%d %d %s}",
5003 gameInfo.white, white_stren, _("vs."), gameInfo.black, black_stren,
5004 basetime, increment, VariantName(gameInfo.variant));
5007 if (appData.debugMode) {
5008 fprintf(debugFP, "Display title '%s, gameInfo.variant = %d'\n", str, gameInfo.variant);
5013 /* Display the board */
5014 if (!pausing && !appData.noGUI) {
5016 if (appData.premove)
5018 ((gameMode == IcsPlayingWhite) && (WhiteOnMove(currentMove))) ||
5019 ((gameMode == IcsPlayingBlack) && (!WhiteOnMove(currentMove))))
5020 ClearPremoveHighlights();
5022 j = seekGraphUp; seekGraphUp = FALSE; // [HGM] seekgraph: when we draw a board, it overwrites the seek graph
5023 if(partnerUp) { flipView = originalFlip; partnerUp = FALSE; j = TRUE; } // [HGM] bughouse: restore view
5024 DrawPosition(j, boards[currentMove]);
5026 DisplayMove(moveNum - 1);
5027 if (appData.ringBellAfterMoves && /*!ics_user_moved*/ // [HGM] use absolute method to recognize own move
5028 !((gameMode == IcsPlayingWhite) && (!WhiteOnMove(moveNum)) ||
5029 (gameMode == IcsPlayingBlack) && (WhiteOnMove(moveNum)) ) ) {
5030 if(newMove) RingBell(); else PlayIcsUnfinishedSound();
5034 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
5036 if(bookHit) { // [HGM] book: simulate book reply
5037 static char bookMove[MSG_SIZ]; // a bit generous?
5039 programStats.nodes = programStats.depth = programStats.time =
5040 programStats.score = programStats.got_only_move = 0;
5041 sprintf(programStats.movelist, "%s (xbook)", bookHit);
5043 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
5044 strcat(bookMove, bookHit);
5045 HandleMachineMove(bookMove, &first);
5054 if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) {
5055 ics_getting_history = H_REQUESTED;
5056 snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum);
5062 SendToBoth (char *msg)
5063 { // to make it easy to keep two engines in step in dual analysis
5064 SendToProgram(msg, &first);
5065 if(second.analyzing) SendToProgram(msg, &second);
5069 AnalysisPeriodicEvent (int force)
5071 if (((programStats.ok_to_send == 0 || programStats.line_is_book)
5072 && !force) || !appData.periodicUpdates)
5075 /* Send . command to Crafty to collect stats */
5078 /* Don't send another until we get a response (this makes
5079 us stop sending to old Crafty's which don't understand
5080 the "." command (sending illegal cmds resets node count & time,
5081 which looks bad)) */
5082 programStats.ok_to_send = 0;
5086 ics_update_width (int new_width)
5088 ics_printf("set width %d\n", new_width);
5092 SendMoveToProgram (int moveNum, ChessProgramState *cps)
5096 if(moveList[moveNum][1] == '@' && moveList[moveNum][0] == '@') {
5097 if(gameInfo.variant == VariantLion || gameInfo.variant == VariantChuChess || gameInfo.variant == VariantChu) {
5098 sprintf(buf, "%s@@@@\n", cps->useUsermove ? "usermove " : "");
5099 SendToProgram(buf, cps);
5102 // null move in variant where engine does not understand it (for analysis purposes)
5103 SendBoard(cps, moveNum + 1); // send position after move in stead.
5106 if (cps->useUsermove) {
5107 SendToProgram("usermove ", cps);
5111 if ((space = strchr(parseList[moveNum], ' ')) != NULL) {
5112 int len = space - parseList[moveNum];
5113 memcpy(buf, parseList[moveNum], len);
5115 buf[len] = NULLCHAR;
5117 snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]);
5119 SendToProgram(buf, cps);
5121 if(cps->alphaRank) { /* [HGM] shogi: temporarily convert to shogi coordinates before sending */
5122 AlphaRank(moveList[moveNum], 4);
5123 SendToProgram(moveList[moveNum], cps);
5124 AlphaRank(moveList[moveNum], 4); // and back
5126 /* Added by Tord: Send castle moves in "O-O" in FRC games if required by
5127 * the engine. It would be nice to have a better way to identify castle
5129 if(appData.fischerCastling && cps->useOOCastle) {
5130 int fromX = moveList[moveNum][0] - AAA;
5131 int fromY = moveList[moveNum][1] - ONE;
5132 int toX = moveList[moveNum][2] - AAA;
5133 int toY = moveList[moveNum][3] - ONE;
5134 if((boards[moveNum][fromY][fromX] == WhiteKing
5135 && boards[moveNum][toY][toX] == WhiteRook)
5136 || (boards[moveNum][fromY][fromX] == BlackKing
5137 && boards[moveNum][toY][toX] == BlackRook)) {
5138 if(toX > fromX) SendToProgram("O-O\n", cps);
5139 else SendToProgram("O-O-O\n", cps);
5141 else SendToProgram(moveList[moveNum], cps);
5143 if(moveList[moveNum][4] == ';') { // [HGM] lion: move is double-step over intermediate square
5144 snprintf(buf, MSG_SIZ, "%c%d%c%d,%c%d%c%d\n", moveList[moveNum][0], moveList[moveNum][1] - '0', // convert to two moves
5145 moveList[moveNum][5], moveList[moveNum][6] - '0',
5146 moveList[moveNum][5], moveList[moveNum][6] - '0',
5147 moveList[moveNum][2], moveList[moveNum][3] - '0');
5148 SendToProgram(buf, cps);
5150 if(BOARD_HEIGHT > 10) { // [HGM] big: convert ranks to double-digit where needed
5151 if(moveList[moveNum][1] == '@' && (BOARD_HEIGHT < 16 || moveList[moveNum][0] <= 'Z')) { // drop move
5152 if(moveList[moveNum][0]== '@') snprintf(buf, MSG_SIZ, "@@@@\n"); else
5153 snprintf(buf, MSG_SIZ, "%c@%c%d%s", moveList[moveNum][0],
5154 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
5156 snprintf(buf, MSG_SIZ, "%c%d%c%d%s", moveList[moveNum][0], moveList[moveNum][1] - '0',
5157 moveList[moveNum][2], moveList[moveNum][3] - '0', moveList[moveNum]+4);
5158 SendToProgram(buf, cps);
5160 else SendToProgram(moveList[moveNum], cps);
5161 /* End of additions by Tord */
5164 /* [HGM] setting up the opening has brought engine in force mode! */
5165 /* Send 'go' if we are in a mode where machine should play. */
5166 if( (moveNum == 0 && setboardSpoiledMachineBlack && cps == &first) &&
5167 (gameMode == TwoMachinesPlay ||
5169 gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite ||
5171 gameMode == MachinePlaysBlack || gameMode == MachinePlaysWhite) ) {
5172 SendToProgram("go\n", cps);
5173 if (appData.debugMode) {
5174 fprintf(debugFP, "(extra)\n");
5177 setboardSpoiledMachineBlack = 0;
5181 SendMoveToICS (ChessMove moveType, int fromX, int fromY, int toX, int toY, char promoChar)
5183 char user_move[MSG_SIZ];
5186 if(gameInfo.variant == VariantSChess && promoChar) {
5187 snprintf(suffix, 4, "=%c", toX == BOARD_WIDTH<<1 ? ToUpper(promoChar) : ToLower(promoChar));
5188 if(moveType == NormalMove) moveType = WhitePromotion; // kludge to do gating
5189 } else suffix[0] = NULLCHAR;
5193 snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"),
5194 (int)moveType, fromX, fromY, toX, toY);
5195 DisplayError(user_move + strlen("say "), 0);
5197 case WhiteKingSideCastle:
5198 case BlackKingSideCastle:
5199 case WhiteQueenSideCastleWild:
5200 case BlackQueenSideCastleWild:
5202 case WhiteHSideCastleFR:
5203 case BlackHSideCastleFR:
5205 snprintf(user_move, MSG_SIZ, "o-o%s\n", suffix);
5207 case WhiteQueenSideCastle:
5208 case BlackQueenSideCastle:
5209 case WhiteKingSideCastleWild:
5210 case BlackKingSideCastleWild:
5212 case WhiteASideCastleFR:
5213 case BlackASideCastleFR:
5215 snprintf(user_move, MSG_SIZ, "o-o-o%s\n",suffix);
5217 case WhiteNonPromotion:
5218 case BlackNonPromotion:
5219 sprintf(user_move, "%c%c%c%c==\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5221 case WhitePromotion:
5222 case BlackPromotion:
5223 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
5224 gameInfo.variant == VariantMakruk || gameInfo.variant == VariantASEAN)
5225 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5226 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5227 PieceToChar(WhiteFerz));
5228 else if(gameInfo.variant == VariantGreat)
5229 snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n",
5230 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5231 PieceToChar(WhiteMan));
5233 snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n",
5234 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY,
5240 snprintf(user_move, MSG_SIZ, "%c@%c%c\n",
5241 ToUpper(PieceToChar((ChessSquare) fromX)),
5242 AAA + toX, ONE + toY);
5244 case IllegalMove: /* could be a variant we don't quite understand */
5245 if(fromY == DROP_RANK) goto drop; // We need 'IllegalDrop' move type?
5247 case WhiteCapturesEnPassant:
5248 case BlackCapturesEnPassant:
5249 snprintf(user_move, MSG_SIZ,"%c%c%c%c\n",
5250 AAA + fromX, ONE + fromY, AAA + toX, ONE + toY);
5253 SendToICS(user_move);
5254 if(appData.keepAlive) // [HGM] alive: schedule sending of dummy 'date' command
5255 ScheduleDelayedEvent(KeepAlive, appData.keepAlive*60*1000);
5260 { // [HGM] upload: send entire stored game to ICS as long-algebraic moves.
5261 int i, last = forwardMostMove; // make sure ICS reply cannot pre-empt us by clearing fmm
5262 static char *castlingStrings[4] = { "none", "kside", "qside", "both" };
5263 if(gameMode == IcsObserving || gameMode == IcsPlayingBlack || gameMode == IcsPlayingWhite) {
5264 DisplayError(_("You cannot do this while you are playing or observing"), 0);
5267 if(gameMode != IcsExamining) { // is this ever not the case?
5268 char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0;
5270 if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant
5271 snprintf(command,MSG_SIZ, "match %s", ics_handle);
5272 } else { // on FICS we must first go to general examine mode
5273 safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups
5275 if(gameInfo.variant != VariantNormal) {
5276 // try figure out wild number, as xboard names are not always valid on ICS
5277 for(i=1; i<=36; i++) {
5278 snprintf(buf, MSG_SIZ, "wild/%d", i);
5279 if(StringToVariant(buf) == gameInfo.variant) break;
5281 if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i);
5282 else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command);
5283 else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant));
5284 } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine
5285 SendToICS(ics_prefix);
5287 if(startedFromSetupPosition || backwardMostMove != 0) {
5288 fen = PositionToFEN(backwardMostMove, NULL, 1);
5289 if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything
5290 snprintf(buf, MSG_SIZ,"loadfen %s\n", fen);
5292 } else { // FICS: everything has to set by separate bsetup commands
5293 p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board
5294 snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen);
5296 if(!WhiteOnMove(backwardMostMove)) {
5297 SendToICS("bsetup tomove black\n");
5299 i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL);
5300 snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]);
5302 i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL);
5303 snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]);
5305 i = boards[backwardMostMove][EP_STATUS];
5306 if(i >= 0) { // set e.p.
5307 snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA);
5313 if(bsetup || ics_type != ICS_ICC && gameInfo.variant != VariantNormal)
5314 SendToICS("bsetup done\n"); // switch to normal examining.
5316 for(i = backwardMostMove; i<last; i++) {
5318 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s\n", parseList[i]);
5319 if((*buf == 'b' || *buf == 'B') && buf[1] == 'x') { // work-around for stupid FICS bug, which thinks bxc3 can be a Bishop move
5320 int len = strlen(moveList[i]);
5321 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%s", moveList[i]); // use long algebraic
5322 if(!isdigit(buf[len-2])) snprintf(buf+len-2, 20-len, "=%c\n", ToUpper(buf[len-2])); // promotion must have '=' in ICS format
5326 SendToICS(ics_prefix);
5327 SendToICS(ics_type == ICS_ICC ? "tag result Game in progress\n" : "commit\n");
5330 int killX = -1, killY = -1; // [HGM] lion: used for passing e.p. capture square to MakeMove
5334 CoordsToComputerAlgebraic (int rf, int ff, int rt, int ft, char promoChar, char move[7])
5336 if (rf == DROP_RANK) {
5337 if(ff == EmptySquare) sprintf(move, "@@@@\n"); else // [HGM] pass
5338 sprintf(move, "%c@%c%c\n",
5339 ToUpper(PieceToChar((ChessSquare) ff)), AAA + ft, ONE + rt);
5341 if (promoChar == 'x' || promoChar == NULLCHAR) {
5342 sprintf(move, "%c%c%c%c\n",
5343 AAA + ff, ONE + rf, AAA + ft, ONE + rt);
5344 if(killX >= 0 && killY >= 0) sprintf(move+4, ";%c%c\n", AAA + killX, ONE + killY);
5346 sprintf(move, "%c%c%c%c%c\n",
5347 AAA + ff, ONE + rf, AAA + ft, ONE + rt, promoChar);
5353 ProcessICSInitScript (FILE *f)
5357 while (fgets(buf, MSG_SIZ, f)) {
5358 SendToICSDelayed(buf,(long)appData.msLoginDelay);
5365 static int lastX, lastY, lastLeftX, lastLeftY, selectFlag;
5367 static ClickType lastClickType;
5370 Partner (ChessSquare *p)
5371 { // change piece into promotion partner if one shogi-promotes to the other
5372 int stride = gameInfo.variant == VariantChu ? 22 : 11;
5373 ChessSquare partner;
5374 partner = (*p/stride & 1 ? *p - stride : *p + stride);
5375 if(PieceToChar(*p) != '+' && PieceToChar(partner) != '+') return 0;
5383 ChessSquare king = WhiteKing, pawn = WhitePawn, last = promoSweep;
5384 static int toggleFlag;
5385 if(gameInfo.variant == VariantKnightmate) king = WhiteUnicorn;
5386 if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway) king = EmptySquare;
5387 if(promoSweep >= BlackPawn) king = WHITE_TO_BLACK king, pawn = WHITE_TO_BLACK pawn;
5388 if(gameInfo.variant == VariantSpartan && pawn == BlackPawn) pawn = BlackLance, king = EmptySquare;
5389 if(fromY != BOARD_HEIGHT-2 && fromY != 1 && gameInfo.variant != VariantChuChess) pawn = EmptySquare;
5390 if(!step) toggleFlag = Partner(&last); // piece has shogi-promotion
5392 if(step && !(toggleFlag && Partner(&promoSweep))) promoSweep -= step;
5393 if(promoSweep == EmptySquare) promoSweep = BlackPawn; // wrap
5394 else if((int)promoSweep == -1) promoSweep = WhiteKing;
5395 else if(promoSweep == BlackPawn && step < 0) promoSweep = WhitePawn;
5396 else if(promoSweep == WhiteKing && step > 0) promoSweep = BlackKing;
5397 if(!step) step = -1;
5398 } while(PieceToChar(promoSweep) == '.' || PieceToChar(promoSweep) == '~' || promoSweep == pawn ||
5399 !toggleFlag && PieceToChar(promoSweep) == '+' || // skip promoted versions of other
5400 appData.testLegality && (promoSweep == king || gameInfo.variant != VariantChuChess &&
5401 (promoSweep == WhiteLion || promoSweep == BlackLion)));
5403 int victim = boards[currentMove][toY][toX];
5404 boards[currentMove][toY][toX] = promoSweep;
5405 DrawPosition(FALSE, boards[currentMove]);
5406 boards[currentMove][toY][toX] = victim;
5408 ChangeDragPiece(promoSweep);
5412 PromoScroll (int x, int y)
5416 if(promoSweep == EmptySquare || !appData.sweepSelect) return FALSE;
5417 if(abs(x - lastX) < 25 && abs(y - lastY) < 25) return FALSE;
5418 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5419 if(!step) return FALSE;
5420 lastX = x; lastY = y;
5421 if((promoSweep < BlackPawn) == flipView) step = -step;
5422 if(step > 0) selectFlag = 1;
5423 if(!selectFlag) Sweep(step);
5428 NextPiece (int step)
5430 ChessSquare piece = boards[currentMove][toY][toX];
5433 if(pieceSweep == EmptySquare) pieceSweep = WhitePawn; // wrap
5434 if((int)pieceSweep == -1) pieceSweep = BlackKing;
5435 if(!step) step = -1;
5436 } while(PieceToChar(pieceSweep) == '.');
5437 boards[currentMove][toY][toX] = pieceSweep;
5438 DrawPosition(FALSE, boards[currentMove]);
5439 boards[currentMove][toY][toX] = piece;
5441 /* [HGM] Shogi move preprocessor: swap digits for letters, vice versa */
5443 AlphaRank (char *move, int n)
5445 // char *p = move, c; int x, y;
5447 if (appData.debugMode) {
5448 fprintf(debugFP, "alphaRank(%s,%d)\n", move, n);
5452 move[2]>='0' && move[2]<='9' &&
5453 move[3]>='a' && move[3]<='x' ) {
5455 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5456 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5458 if(move[0]>='0' && move[0]<='9' &&
5459 move[1]>='a' && move[1]<='x' &&
5460 move[2]>='0' && move[2]<='9' &&
5461 move[3]>='a' && move[3]<='x' ) {
5462 /* input move, Shogi -> normal */
5463 move[0] = BOARD_RGHT -1 - (move[0]-'1') + AAA;
5464 move[1] = BOARD_HEIGHT-1 - (move[1]-'a') + ONE;
5465 move[2] = BOARD_RGHT -1 - (move[2]-'1') + AAA;
5466 move[3] = BOARD_HEIGHT-1 - (move[3]-'a') + ONE;
5469 move[3]>='0' && move[3]<='9' &&
5470 move[2]>='a' && move[2]<='x' ) {
5472 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5473 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5476 move[0]>='a' && move[0]<='x' &&
5477 move[3]>='0' && move[3]<='9' &&
5478 move[2]>='a' && move[2]<='x' ) {
5479 /* output move, normal -> Shogi */
5480 move[0] = BOARD_RGHT - 1 - (move[0]-AAA) + '1';
5481 move[1] = BOARD_HEIGHT-1 - (move[1]-ONE) + 'a';
5482 move[2] = BOARD_RGHT - 1 - (move[2]-AAA) + '1';
5483 move[3] = BOARD_HEIGHT-1 - (move[3]-ONE) + 'a';
5484 if(move[4] == PieceToChar(BlackQueen)) move[4] = '+';
5486 if (appData.debugMode) {
5487 fprintf(debugFP, " out = '%s'\n", move);
5491 char yy_textstr[8000];
5493 /* Parser for moves from gnuchess, ICS, or user typein box */
5495 ParseOneMove (char *move, int moveNum, ChessMove *moveType, int *fromX, int *fromY, int *toX, int *toY, char *promoChar)
5497 *moveType = yylexstr(moveNum, move, yy_textstr, sizeof yy_textstr);
5499 switch (*moveType) {
5500 case WhitePromotion:
5501 case BlackPromotion:
5502 case WhiteNonPromotion:
5503 case BlackNonPromotion:
5506 case WhiteCapturesEnPassant:
5507 case BlackCapturesEnPassant:
5508 case WhiteKingSideCastle:
5509 case WhiteQueenSideCastle:
5510 case BlackKingSideCastle:
5511 case BlackQueenSideCastle:
5512 case WhiteKingSideCastleWild:
5513 case WhiteQueenSideCastleWild:
5514 case BlackKingSideCastleWild:
5515 case BlackQueenSideCastleWild:
5516 /* Code added by Tord: */
5517 case WhiteHSideCastleFR:
5518 case WhiteASideCastleFR:
5519 case BlackHSideCastleFR:
5520 case BlackASideCastleFR:
5521 /* End of code added by Tord */
5522 case IllegalMove: /* bug or odd chess variant */
5523 *fromX = currentMoveString[0] - AAA;
5524 *fromY = currentMoveString[1] - ONE;
5525 *toX = currentMoveString[2] - AAA;
5526 *toY = currentMoveString[3] - ONE;
5527 *promoChar = currentMoveString[4];
5528 if (*fromX < BOARD_LEFT || *fromX >= BOARD_RGHT || *fromY < 0 || *fromY >= BOARD_HEIGHT ||
5529 *toX < BOARD_LEFT || *toX >= BOARD_RGHT || *toY < 0 || *toY >= BOARD_HEIGHT) {
5530 if (appData.debugMode) {
5531 fprintf(debugFP, "Off-board move (%d,%d)-(%d,%d)%c, type = %d\n", *fromX, *fromY, *toX, *toY, *promoChar, *moveType);
5533 *fromX = *fromY = *toX = *toY = 0;
5536 if (appData.testLegality) {
5537 return (*moveType != IllegalMove);
5539 return !(*fromX == *toX && *fromY == *toY && killX < 0) && boards[moveNum][*fromY][*fromX] != EmptySquare &&
5540 // [HGM] lion: if this is a double move we are less critical
5541 WhiteOnMove(moveNum) == (boards[moveNum][*fromY][*fromX] < BlackPawn);
5546 *fromX = *moveType == WhiteDrop ?
5547 (int) CharToPiece(ToUpper(currentMoveString[0])) :
5548 (int) CharToPiece(ToLower(currentMoveString[0]));
5550 *toX = currentMoveString[2] - AAA;
5551 *toY = currentMoveString[3] - ONE;
5552 *promoChar = NULLCHAR;
5556 case ImpossibleMove:
5566 if (appData.debugMode) {
5567 fprintf(debugFP, "Impossible move %s, type = %d\n", currentMoveString, *moveType);
5570 *fromX = *fromY = *toX = *toY = 0;
5571 *promoChar = NULLCHAR;
5576 Boolean pushed = FALSE;
5577 char *lastParseAttempt;
5580 ParsePV (char *pv, Boolean storeComments, Boolean atEnd)
5581 { // Parse a string of PV moves, and append to current game, behind forwardMostMove
5582 int fromX, fromY, toX, toY; char promoChar;
5587 lastParseAttempt = pv; if(!*pv) return; // turns out we crash when we parse an empty PV
5588 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) && currentMove < forwardMostMove) {
5589 PushInner(currentMove, forwardMostMove); // [HGM] engine might not be thinking on forwardMost position!
5592 endPV = forwardMostMove;
5594 while(*pv == ' ' || *pv == '\n' || *pv == '\t') pv++; // must still read away whitespace
5595 if(nr == 0 && !storeComments && *pv == '(') pv++; // first (ponder) move can be in parentheses
5596 lastParseAttempt = pv;
5597 valid = ParseOneMove(pv, endPV, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
5598 if(!valid && nr == 0 &&
5599 ParseOneMove(pv, endPV-1, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)){
5600 nr++; moveType = Comment; // First move has been played; kludge to make sure we continue
5601 // Hande case where played move is different from leading PV move
5602 CopyBoard(boards[endPV+1], boards[endPV-1]); // tentatively unplay last game move
5603 CopyBoard(boards[endPV+2], boards[endPV-1]); // and play first move of PV
5604 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV+2]);
5605 if(!CompareBoards(boards[endPV], boards[endPV+2])) {
5606 endPV += 2; // if position different, keep this
5607 moveList[endPV-1][0] = fromX + AAA;
5608 moveList[endPV-1][1] = fromY + ONE;
5609 moveList[endPV-1][2] = toX + AAA;
5610 moveList[endPV-1][3] = toY + ONE;
5611 parseList[endPV-1][0] = NULLCHAR;
5612 safeStrCpy(moveList[endPV-2], "_0_0", sizeof(moveList[endPV-2])/sizeof(moveList[endPV-2][0])); // suppress premove highlight on takeback move
5615 pv = strstr(pv, yy_textstr) + strlen(yy_textstr); // skip what we parsed
5616 if(nr == 0 && !storeComments && *pv == ')') pv++; // closing parenthesis of ponder move;
5617 if(moveType == Comment && storeComments) AppendComment(endPV, yy_textstr, FALSE);
5618 if(moveType == Comment || moveType == NAG || moveType == ElapsedTime) {
5619 valid++; // allow comments in PV
5623 if(endPV+1 > framePtr) break; // no space, truncate
5626 CopyBoard(boards[endPV], boards[endPV-1]);
5627 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[endPV]);
5628 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, moveList[endPV - 1]);
5629 strncat(moveList[endPV-1], "\n", MOVE_LEN);
5630 CoordsToAlgebraic(boards[endPV - 1],
5631 PosFlags(endPV - 1),
5632 fromY, fromX, toY, toX, promoChar,
5633 parseList[endPV - 1]);
5635 if(atEnd == 2) return; // used hidden, for PV conversion
5636 currentMove = (atEnd || endPV == forwardMostMove) ? endPV : forwardMostMove + 1;
5637 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5638 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5639 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5640 DrawPosition(TRUE, boards[currentMove]);
5644 MultiPV (ChessProgramState *cps)
5645 { // check if engine supports MultiPV, and if so, return the number of the option that sets it
5647 for(i=0; i<cps->nrOptions; i++)
5648 if(!strcmp(cps->option[i].name, "MultiPV") && cps->option[i].type == Spin)
5653 Boolean extendGame; // signals to UnLoadPV() if walked part of PV has to be appended to game
5656 LoadMultiPV (int x, int y, char *buf, int index, int *start, int *end, int pane)
5658 int startPV, multi, lineStart, origIndex = index;
5659 char *p, buf2[MSG_SIZ];
5660 ChessProgramState *cps = (pane ? &second : &first);
5662 if(index < 0 || index >= strlen(buf)) return FALSE; // sanity
5663 lastX = x; lastY = y;
5664 while(index > 0 && buf[index-1] != '\n') index--; // beginning of line
5665 lineStart = startPV = index;
5666 while(buf[index] != '\n') if(buf[index++] == '\t') startPV = index;
5667 if(index == startPV && (p = StrCaseStr(buf+index, "PV="))) startPV = p - buf + 3;
5669 do{ while(buf[index] && buf[index] != '\n') index++;
5670 } while(buf[index] == '\n' && buf[index+1] == '\\' && buf[index+2] == ' ' && index++); // join kibitzed PV continuation line
5672 if(lineStart == 0 && gameMode == AnalyzeMode && (multi = MultiPV(cps)) >= 0) {
5673 int n = cps->option[multi].value;
5674 if(origIndex > 17 && origIndex < 24) { if(n>1) n--; } else if(origIndex > index - 6) n++;
5675 snprintf(buf2, MSG_SIZ, "option MultiPV=%d\n", n);
5676 if(cps->option[multi].value != n) SendToProgram(buf2, cps);
5677 cps->option[multi].value = n;
5680 } else if(strstr(buf+lineStart, "exclude:") == buf+lineStart) { // exclude moves clicked
5681 ExcludeClick(origIndex - lineStart);
5683 } else if(!strncmp(buf+lineStart, "dep\t", 4)) { // column headers clicked
5684 Collapse(origIndex - lineStart);
5687 ParsePV(buf+startPV, FALSE, gameMode != AnalyzeMode);
5688 *start = startPV; *end = index-1;
5689 extendGame = (gameMode == AnalyzeMode && appData.autoExtend && origIndex - startPV < 5);
5696 static char buf[10*MSG_SIZ];
5697 int i, k=0, savedEnd=endPV, saveFMM = forwardMostMove;
5699 if(forwardMostMove < endPV) PushInner(forwardMostMove, endPV); // shelve PV of PV-walk
5700 ParsePV(pv, FALSE, 2); // this appends PV to game, suppressing any display of it
5701 for(i = forwardMostMove; i<endPV; i++){
5702 if(i&1) snprintf(buf+k, 10*MSG_SIZ-k, "%s ", parseList[i]);
5703 else snprintf(buf+k, 10*MSG_SIZ-k, "%d. %s ", i/2 + 1, parseList[i]);
5706 snprintf(buf+k, 10*MSG_SIZ-k, "%s", lastParseAttempt); // if we ran into stuff that could not be parsed, print it verbatim
5707 if(pushed) { PopInner(0); pushed = FALSE; } // restore game continuation shelved by ParsePV
5708 if(forwardMostMove < savedEnd) { PopInner(0); forwardMostMove = saveFMM; } // PopInner would set fmm to endPV!
5714 LoadPV (int x, int y)
5715 { // called on right mouse click to load PV
5716 int which = gameMode == TwoMachinesPlay && (WhiteOnMove(forwardMostMove) == (second.twoMachinesColor[0] == 'w'));
5717 lastX = x; lastY = y;
5718 ParsePV(lastPV[which], FALSE, TRUE); // load the PV of the thinking engine in the boards array.
5726 int oldFMM = forwardMostMove; // N.B.: this was currentMove before PV was loaded!
5727 if(endPV < 0) return;
5728 if(appData.autoCopyPV) CopyFENToClipboard();
5730 if(extendGame && currentMove > forwardMostMove) {
5731 Boolean saveAnimate = appData.animate;
5733 if(shiftKey && storedGames < MAX_VARIATIONS-2) { // wants to start variation, and there is space
5734 if(storedGames == 1) GreyRevert(FALSE); // we already pushed the tail, so just make it official
5735 } else storedGames--; // abandon shelved tail of original game
5738 forwardMostMove = currentMove;
5739 currentMove = oldFMM;
5740 appData.animate = FALSE;
5741 ToNrEvent(forwardMostMove);
5742 appData.animate = saveAnimate;
5744 currentMove = forwardMostMove;
5745 if(pushed) { PopInner(0); pushed = FALSE; } // restore shelved game continuation
5746 ClearPremoveHighlights();
5747 DrawPosition(TRUE, boards[currentMove]);
5751 MovePV (int x, int y, int h)
5752 { // step through PV based on mouse coordinates (called on mouse move)
5753 int margin = h>>3, step = 0, threshold = (pieceSweep == EmptySquare ? 10 : 15);
5755 // we must somehow check if right button is still down (might be released off board!)
5756 if(endPV < 0 && pieceSweep == EmptySquare) return; // needed in XBoard because lastX/Y is shared :-(
5757 if(abs(x - lastX) < threshold && abs(y - lastY) < threshold) return;
5758 if( y > lastY + 2 ) step = -1; else if(y < lastY - 2) step = 1;
5760 lastX = x; lastY = y;
5762 if(pieceSweep != EmptySquare) { NextPiece(step); return; }
5763 if(endPV < 0) return;
5764 if(y < margin) step = 1; else
5765 if(y > h - margin) step = -1;
5766 if(currentMove + step > endPV || currentMove + step < forwardMostMove) step = 0;
5767 currentMove += step;
5768 if(currentMove == forwardMostMove) ClearPremoveHighlights(); else
5769 SetPremoveHighlights(moveList[currentMove-1][0]-AAA, moveList[currentMove-1][1]-ONE,
5770 moveList[currentMove-1][2]-AAA, moveList[currentMove-1][3]-ONE);
5771 DrawPosition(FALSE, boards[currentMove]);
5775 // [HGM] shuffle: a general way to suffle opening setups, applicable to arbitrary variants.
5776 // All positions will have equal probability, but the current method will not provide a unique
5777 // numbering scheme for arrays that contain 3 or more pieces of the same kind.
5783 int piecesLeft[(int)BlackPawn];
5784 int seed, nrOfShuffles;
5787 GetPositionNumber ()
5788 { // sets global variable seed
5791 seed = appData.defaultFrcPosition;
5792 if(seed < 0) { // randomize based on time for negative FRC position numbers
5793 for(i=0; i<50; i++) seed += random();
5794 seed = random() ^ random() >> 8 ^ random() << 8;
5795 if(seed<0) seed = -seed;
5800 put (Board board, int pieceType, int rank, int n, int shade)
5801 // put the piece on the (n-1)-th empty squares of the given shade
5805 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
5806 if( (((i-BOARD_LEFT)&1)+1) & shade && board[rank][i] == EmptySquare && n-- == 0) {
5807 board[rank][i] = (ChessSquare) pieceType;
5808 squaresLeft[((i-BOARD_LEFT)&1) + 1]--;
5810 piecesLeft[pieceType]--;
5819 AddOnePiece (Board board, int pieceType, int rank, int shade)
5820 // calculate where the next piece goes, (any empty square), and put it there
5824 i = seed % squaresLeft[shade];
5825 nrOfShuffles *= squaresLeft[shade];
5826 seed /= squaresLeft[shade];
5827 put(board, pieceType, rank, i, shade);
5831 AddTwoPieces (Board board, int pieceType, int rank)
5832 // calculate where the next 2 identical pieces go, (any empty square), and put it there
5834 int i, n=squaresLeft[ANY], j=n-1, k;
5836 k = n*(n-1)/2; // nr of possibilities, not counting permutations
5837 i = seed % k; // pick one
5840 while(i >= j) i -= j--;
5841 j = n - 1 - j; i += j;
5842 put(board, pieceType, rank, j, ANY);
5843 put(board, pieceType, rank, i, ANY);
5847 SetUpShuffle (Board board, int number)
5851 GetPositionNumber(); nrOfShuffles = 1;
5853 squaresLeft[DARK] = (BOARD_RGHT - BOARD_LEFT + 1)/2;
5854 squaresLeft[ANY] = BOARD_RGHT - BOARD_LEFT;
5855 squaresLeft[LITE] = squaresLeft[ANY] - squaresLeft[DARK];
5857 for(p = 0; p<=(int)WhiteKing; p++) piecesLeft[p] = 0;
5859 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // count pieces and clear board
5860 p = (int) board[0][i];
5861 if(p < (int) BlackPawn) piecesLeft[p] ++;
5862 board[0][i] = EmptySquare;
5865 if(PosFlags(0) & F_ALL_CASTLE_OK) {
5866 // shuffles restricted to allow normal castling put KRR first
5867 if(piecesLeft[(int)WhiteKing]) // King goes rightish of middle
5868 put(board, WhiteKing, 0, (gameInfo.boardWidth+1)/2, ANY);
5869 else if(piecesLeft[(int)WhiteUnicorn]) // in Knightmate Unicorn castles
5870 put(board, WhiteUnicorn, 0, (gameInfo.boardWidth+1)/2, ANY);
5871 if(piecesLeft[(int)WhiteRook]) // First supply a Rook for K-side castling
5872 put(board, WhiteRook, 0, gameInfo.boardWidth-2, ANY);
5873 if(piecesLeft[(int)WhiteRook]) // Then supply a Rook for Q-side castling
5874 put(board, WhiteRook, 0, 0, ANY);
5875 // in variants with super-numerary Kings and Rooks, we leave these for the shuffle
5878 if(((BOARD_RGHT-BOARD_LEFT) & 1) == 0)
5879 // only for even boards make effort to put pairs of colorbound pieces on opposite colors
5880 for(p = (int) WhiteKing; p > (int) WhitePawn; p--) {
5881 if(p != (int) WhiteBishop && p != (int) WhiteFerz && p != (int) WhiteAlfil) continue;
5882 while(piecesLeft[p] >= 2) {
5883 AddOnePiece(board, p, 0, LITE);
5884 AddOnePiece(board, p, 0, DARK);
5886 // Odd color-bound pieces are shuffled with the rest (to not run out of paired squares)
5889 for(p = (int) WhiteKing - 2; p > (int) WhitePawn; p--) {
5890 // Remaining pieces (non-colorbound, or odd color bound) can be put anywhere
5891 // but we leave King and Rooks for last, to possibly obey FRC restriction
5892 if(p == (int)WhiteRook) continue;
5893 while(piecesLeft[p] >= 2) AddTwoPieces(board, p, 0); // add in pairs, for not counting permutations
5894 if(piecesLeft[p]) AddOnePiece(board, p, 0, ANY); // add the odd piece
5897 // now everything is placed, except perhaps King (Unicorn) and Rooks
5899 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
5900 // Last King gets castling rights
5901 while(piecesLeft[(int)WhiteUnicorn]) {
5902 i = put(board, WhiteUnicorn, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5903 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5906 while(piecesLeft[(int)WhiteKing]) {
5907 i = put(board, WhiteKing, 0, piecesLeft[(int)WhiteRook]/2, ANY);
5908 initialRights[2] = initialRights[5] = board[CASTLING][2] = board[CASTLING][5] = i;
5913 while(piecesLeft[(int)WhiteKing]) AddOnePiece(board, WhiteKing, 0, ANY);
5914 while(piecesLeft[(int)WhiteUnicorn]) AddOnePiece(board, WhiteUnicorn, 0, ANY);
5917 // Only Rooks can be left; simply place them all
5918 while(piecesLeft[(int)WhiteRook]) {
5919 i = put(board, WhiteRook, 0, 0, ANY);
5920 if(PosFlags(0) & F_FRC_TYPE_CASTLING) { // first and last Rook get FRC castling rights
5923 initialRights[1] = initialRights[4] = board[CASTLING][1] = board[CASTLING][4] = i;
5925 initialRights[0] = initialRights[3] = board[CASTLING][0] = board[CASTLING][3] = i;
5928 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // copy black from white
5929 board[BOARD_HEIGHT-1][i] = (int) board[0][i] < BlackPawn ? WHITE_TO_BLACK board[0][i] : EmptySquare;
5932 if(number >= 0) appData.defaultFrcPosition %= nrOfShuffles; // normalize
5936 SetCharTable (char *table, const char * map)
5937 /* [HGM] moved here from winboard.c because of its general usefulness */
5938 /* Basically a safe strcpy that uses the last character as King */
5940 int result = FALSE; int NrPieces;
5942 if( map != NULL && (NrPieces=strlen(map)) <= (int) EmptySquare
5943 && NrPieces >= 12 && !(NrPieces&1)) {
5944 int i; /* [HGM] Accept even length from 12 to 34 */
5946 for( i=0; i<(int) EmptySquare; i++ ) table[i] = '.';
5947 for( i=0; i<NrPieces/2-1; i++ ) {
5949 table[i + (int)BlackPawn - (int) WhitePawn] = map[i+NrPieces/2];
5951 table[(int) WhiteKing] = map[NrPieces/2-1];
5952 table[(int) BlackKing] = map[NrPieces-1];
5961 Prelude (Board board)
5962 { // [HGM] superchess: random selection of exo-pieces
5963 int i, j, k; ChessSquare p;
5964 static ChessSquare exoPieces[4] = { WhiteAngel, WhiteMarshall, WhiteSilver, WhiteLance };
5966 GetPositionNumber(); // use FRC position number
5968 if(appData.pieceToCharTable != NULL) { // select pieces to participate from given char table
5969 SetCharTable(pieceToChar, appData.pieceToCharTable);
5970 for(i=(int)WhiteQueen+1, j=0; i<(int)WhiteKing && j<4; i++)
5971 if(PieceToChar((ChessSquare)i) != '.') exoPieces[j++] = (ChessSquare) i;
5974 j = seed%4; seed /= 4;
5975 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5976 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5977 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5978 j = seed%3 + (seed%3 >= j); seed /= 3;
5979 p = board[0][BOARD_LEFT+j]; board[0][BOARD_LEFT+j] = EmptySquare; k = PieceToNumber(p);
5980 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5981 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5982 j = seed%3; seed /= 3;
5983 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5984 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5985 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5986 j = seed%2 + (seed%2 >= j); seed /= 2;
5987 p = board[0][BOARD_LEFT+j+5]; board[0][BOARD_LEFT+j+5] = EmptySquare; k = PieceToNumber(p);
5988 board[k][BOARD_WIDTH-1] = p; board[k][BOARD_WIDTH-2]++;
5989 board[BOARD_HEIGHT-1-k][0] = WHITE_TO_BLACK p; board[BOARD_HEIGHT-1-k][1]++;
5990 j = seed%4; seed /= 4; put(board, exoPieces[3], 0, j, ANY);
5991 j = seed%3; seed /= 3; put(board, exoPieces[2], 0, j, ANY);
5992 j = seed%2; seed /= 2; put(board, exoPieces[1], 0, j, ANY);
5993 put(board, exoPieces[0], 0, 0, ANY);
5994 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) board[BOARD_HEIGHT-1][i] = WHITE_TO_BLACK board[0][i];
5998 InitPosition (int redraw)
6000 ChessSquare (* pieces)[BOARD_FILES];
6001 int i, j, pawnRow=1, pieceRows=1, overrule,
6002 oldx = gameInfo.boardWidth,
6003 oldy = gameInfo.boardHeight,
6004 oldh = gameInfo.holdingsWidth;
6007 if(appData.icsActive) shuffleOpenings = appData.fischerCastling = FALSE; // [HGM] shuffle: in ICS mode, only shuffle on ICS request
6009 /* [AS] Initialize pv info list [HGM] and game status */
6011 for( i=0; i<=framePtr; i++ ) { // [HGM] vari: spare saved variations
6012 pvInfoList[i].depth = 0;
6013 boards[i][EP_STATUS] = EP_NONE;
6014 for( j=0; j<BOARD_FILES-2; j++ ) boards[i][CASTLING][j] = NoRights;
6017 initialRulePlies = 0; /* 50-move counter start */
6019 castlingRank[0] = castlingRank[1] = castlingRank[2] = 0;
6020 castlingRank[3] = castlingRank[4] = castlingRank[5] = BOARD_HEIGHT-1;
6024 /* [HGM] logic here is completely changed. In stead of full positions */
6025 /* the initialized data only consist of the two backranks. The switch */
6026 /* selects which one we will use, which is than copied to the Board */
6027 /* initialPosition, which for the rest is initialized by Pawns and */
6028 /* empty squares. This initial position is then copied to boards[0], */
6029 /* possibly after shuffling, so that it remains available. */
6031 gameInfo.holdingsWidth = 0; /* default board sizes */
6032 gameInfo.boardWidth = 8;
6033 gameInfo.boardHeight = 8;
6034 gameInfo.holdingsSize = 0;
6035 nrCastlingRights = -1; /* [HGM] Kludge to indicate default should be used */
6036 for(i=0; i<BOARD_FILES-6; i++)
6037 initialPosition[CASTLING][i] = initialRights[i] = NoRights; /* but no rights yet */
6038 initialPosition[EP_STATUS] = EP_NONE;
6039 initialPosition[TOUCHED_W] = initialPosition[TOUCHED_B] = 0;
6040 SetCharTable(pieceToChar, "PNBRQ...........Kpnbrq...........k");
6041 if(startVariant == gameInfo.variant) // [HGM] nicks: enable nicknames in original variant
6042 SetCharTable(pieceNickName, appData.pieceNickNames);
6043 else SetCharTable(pieceNickName, "............");
6046 switch (gameInfo.variant) {
6047 case VariantFischeRandom:
6048 shuffleOpenings = TRUE;
6049 appData.fischerCastling = TRUE;
6052 case VariantShatranj:
6053 pieces = ShatranjArray;
6054 nrCastlingRights = 0;
6055 SetCharTable(pieceToChar, "PN.R.QB...Kpn.r.qb...k");
6058 pieces = makrukArray;
6059 nrCastlingRights = 0;
6060 SetCharTable(pieceToChar, "PN.R.M....SKpn.r.m....sk");
6063 pieces = aseanArray;
6064 nrCastlingRights = 0;
6065 SetCharTable(pieceToChar, "PN.R.Q....BKpn.r.q....bk");
6067 case VariantTwoKings:
6068 pieces = twoKingsArray;
6071 pieces = GrandArray;
6072 nrCastlingRights = 0;
6073 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
6074 gameInfo.boardWidth = 10;
6075 gameInfo.boardHeight = 10;
6076 gameInfo.holdingsSize = 7;
6078 case VariantCapaRandom:
6079 shuffleOpenings = TRUE;
6080 appData.fischerCastling = TRUE;
6081 case VariantCapablanca:
6082 pieces = CapablancaArray;
6083 gameInfo.boardWidth = 10;
6084 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
6087 pieces = GothicArray;
6088 gameInfo.boardWidth = 10;
6089 SetCharTable(pieceToChar, "PNBRQ..ACKpnbrq..ack");
6092 SetCharTable(pieceToChar, "PNBRQ..HEKpnbrq..hek");
6093 gameInfo.holdingsSize = 7;
6094 for(i=0; i<BOARD_FILES; i++) initialPosition[VIRGIN][i] = VIRGIN_W | VIRGIN_B;
6097 pieces = JanusArray;
6098 gameInfo.boardWidth = 10;
6099 SetCharTable(pieceToChar, "PNBRQ..JKpnbrq..jk");
6100 nrCastlingRights = 6;
6101 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
6102 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
6103 initialPosition[CASTLING][2] = initialRights[2] =(BOARD_WIDTH-1)>>1;
6104 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
6105 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
6106 initialPosition[CASTLING][5] = initialRights[5] =(BOARD_WIDTH-1)>>1;
6109 pieces = FalconArray;
6110 gameInfo.boardWidth = 10;
6111 SetCharTable(pieceToChar, "PNBRQ............FKpnbrq............fk");
6113 case VariantXiangqi:
6114 pieces = XiangqiArray;
6115 gameInfo.boardWidth = 9;
6116 gameInfo.boardHeight = 10;
6117 nrCastlingRights = 0;
6118 SetCharTable(pieceToChar, "PH.R.AE..K.C.ph.r.ae..k.c.");
6121 pieces = ShogiArray;
6122 gameInfo.boardWidth = 9;
6123 gameInfo.boardHeight = 9;
6124 gameInfo.holdingsSize = 7;
6125 nrCastlingRights = 0;
6126 SetCharTable(pieceToChar, "PNBRLS...G.++++++Kpnbrls...g.++++++k");
6129 pieces = ChuArray; pieceRows = 3;
6130 gameInfo.boardWidth = 12;
6131 gameInfo.boardHeight = 12;
6132 nrCastlingRights = 0;
6133 SetCharTable(pieceToChar, "P.BRQSEXOGCATHD.VMLIFN+.++.++++++++++.+++++K"
6134 "p.brqsexogcathd.vmlifn+.++.++++++++++.+++++k");
6136 case VariantCourier:
6137 pieces = CourierArray;
6138 gameInfo.boardWidth = 12;
6139 nrCastlingRights = 0;
6140 SetCharTable(pieceToChar, "PNBR.FE..WMKpnbr.fe..wmk");
6142 case VariantKnightmate:
6143 pieces = KnightmateArray;
6144 SetCharTable(pieceToChar, "P.BRQ.....M.........K.p.brq.....m.........k.");
6146 case VariantSpartan:
6147 pieces = SpartanArray;
6148 SetCharTable(pieceToChar, "PNBRQ................K......lwg.....c...h..k");
6152 SetCharTable(pieceToChar, "PNBRQ................LKpnbrq................lk");
6154 case VariantChuChess:
6155 pieces = ChuChessArray;
6156 gameInfo.boardWidth = 10;
6157 gameInfo.boardHeight = 10;
6158 SetCharTable(pieceToChar, "PNBRQ.....M.+++......LKpnbrq.....m.+++......lk");
6161 pieces = fairyArray;
6162 SetCharTable(pieceToChar, "PNBRQFEACWMOHIJGDVLSUKpnbrqfeacwmohijgdvlsuk");
6165 pieces = GreatArray;
6166 gameInfo.boardWidth = 10;
6167 SetCharTable(pieceToChar, "PN....E...S..HWGMKpn....e...s..hwgmk");
6168 gameInfo.holdingsSize = 8;
6172 SetCharTable(pieceToChar, "PNBRQ..SE.......V.AKpnbrq..se.......v.ak");
6173 gameInfo.holdingsSize = 8;
6174 startedFromSetupPosition = TRUE;
6176 case VariantCrazyhouse:
6177 case VariantBughouse:
6179 SetCharTable(pieceToChar, "PNBRQ.......~~~~Kpnbrq.......~~~~k");
6180 gameInfo.holdingsSize = 5;
6182 case VariantWildCastle:
6184 /* !!?shuffle with kings guaranteed to be on d or e file */
6185 shuffleOpenings = 1;
6187 case VariantNoCastle:
6189 nrCastlingRights = 0;
6190 /* !!?unconstrained back-rank shuffle */
6191 shuffleOpenings = 1;
6196 if(appData.NrFiles >= 0) {
6197 if(gameInfo.boardWidth != appData.NrFiles) overrule++;
6198 gameInfo.boardWidth = appData.NrFiles;
6200 if(appData.NrRanks >= 0) {
6201 gameInfo.boardHeight = appData.NrRanks;
6203 if(appData.holdingsSize >= 0) {
6204 i = appData.holdingsSize;
6205 if(i > gameInfo.boardHeight) i = gameInfo.boardHeight;
6206 gameInfo.holdingsSize = i;
6208 if(gameInfo.holdingsSize) gameInfo.holdingsWidth = 2;
6209 if(BOARD_HEIGHT > BOARD_RANKS || BOARD_WIDTH > BOARD_FILES)
6210 DisplayFatalError(_("Recompile to support this BOARD_RANKS or BOARD_FILES!"), 0, 2);
6212 pawnRow = gameInfo.boardHeight - 7; /* seems to work in all common variants */
6213 if(pawnRow < 1) pawnRow = 1;
6214 if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantASEAN ||
6215 gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) pawnRow = 2;
6216 if(gameInfo.variant == VariantChu) pawnRow = 3;
6218 /* User pieceToChar list overrules defaults */
6219 if(appData.pieceToCharTable != NULL)
6220 SetCharTable(pieceToChar, appData.pieceToCharTable);
6222 for( j=0; j<BOARD_WIDTH; j++ ) { ChessSquare s = EmptySquare;
6224 if(j==BOARD_LEFT-1 || j==BOARD_RGHT)
6225 s = (ChessSquare) 0; /* account holding counts in guard band */
6226 for( i=0; i<BOARD_HEIGHT; i++ )
6227 initialPosition[i][j] = s;
6229 if(j < BOARD_LEFT || j >= BOARD_RGHT || overrule) continue;
6230 initialPosition[gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess][j] = pieces[0][j-gameInfo.holdingsWidth];
6231 initialPosition[pawnRow][j] = WhitePawn;
6232 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = gameInfo.variant == VariantSpartan ? BlackLance : BlackPawn;
6233 if(gameInfo.variant == VariantXiangqi) {
6235 initialPosition[pawnRow][j] =
6236 initialPosition[BOARD_HEIGHT-pawnRow-1][j] = EmptySquare;
6237 if(j==BOARD_LEFT+1 || j>=BOARD_RGHT-2) {
6238 initialPosition[2][j] = WhiteCannon;
6239 initialPosition[BOARD_HEIGHT-3][j] = BlackCannon;
6243 if(gameInfo.variant == VariantChu) {
6244 if(j == (BOARD_WIDTH-2)/3 || j == BOARD_WIDTH - (BOARD_WIDTH+1)/3)
6245 initialPosition[pawnRow+1][j] = WhiteCobra,
6246 initialPosition[BOARD_HEIGHT-pawnRow-2][j] = BlackCobra;
6247 for(i=1; i<pieceRows; i++) {
6248 initialPosition[i][j] = pieces[2*i][j-gameInfo.holdingsWidth];
6249 initialPosition[BOARD_HEIGHT-1-i][j] = pieces[2*i+1][j-gameInfo.holdingsWidth];
6252 if(gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) {
6253 if(j==BOARD_LEFT || j>=BOARD_RGHT-1) {
6254 initialPosition[0][j] = WhiteRook;
6255 initialPosition[BOARD_HEIGHT-1][j] = BlackRook;
6258 initialPosition[BOARD_HEIGHT-1-(gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess)][j] = pieces[1][j-gameInfo.holdingsWidth];
6260 if(gameInfo.variant == VariantChuChess) initialPosition[0][BOARD_WIDTH/2] = WhiteKing, initialPosition[BOARD_HEIGHT-1][BOARD_WIDTH/2-1] = BlackKing;
6261 if( (gameInfo.variant == VariantShogi) && !overrule ) {
6264 initialPosition[1][j] = WhiteBishop;
6265 initialPosition[BOARD_HEIGHT-2][j] = BlackRook;
6267 initialPosition[1][j] = WhiteRook;
6268 initialPosition[BOARD_HEIGHT-2][j] = BlackBishop;
6271 if( nrCastlingRights == -1) {
6272 /* [HGM] Build normal castling rights (must be done after board sizing!) */
6273 /* This sets default castling rights from none to normal corners */
6274 /* Variants with other castling rights must set them themselves above */
6275 nrCastlingRights = 6;
6277 initialPosition[CASTLING][0] = initialRights[0] = BOARD_RGHT-1;
6278 initialPosition[CASTLING][1] = initialRights[1] = BOARD_LEFT;
6279 initialPosition[CASTLING][2] = initialRights[2] = BOARD_WIDTH>>1;
6280 initialPosition[CASTLING][3] = initialRights[3] = BOARD_RGHT-1;
6281 initialPosition[CASTLING][4] = initialRights[4] = BOARD_LEFT;
6282 initialPosition[CASTLING][5] = initialRights[5] = BOARD_WIDTH>>1;
6285 if(gameInfo.variant == VariantSuper) Prelude(initialPosition);
6286 if(gameInfo.variant == VariantGreat) { // promotion commoners
6287 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-1] = WhiteMan;
6288 initialPosition[PieceToNumber(WhiteMan)][BOARD_WIDTH-2] = 9;
6289 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][0] = BlackMan;
6290 initialPosition[BOARD_HEIGHT-1-PieceToNumber(WhiteMan)][1] = 9;
6292 if( gameInfo.variant == VariantSChess ) {
6293 initialPosition[1][0] = BlackMarshall;
6294 initialPosition[2][0] = BlackAngel;
6295 initialPosition[6][BOARD_WIDTH-1] = WhiteMarshall;
6296 initialPosition[5][BOARD_WIDTH-1] = WhiteAngel;
6297 initialPosition[1][1] = initialPosition[2][1] =
6298 initialPosition[6][BOARD_WIDTH-2] = initialPosition[5][BOARD_WIDTH-2] = 1;
6300 if (appData.debugMode) {
6301 fprintf(debugFP, "shuffleOpenings = %d\n", shuffleOpenings);
6303 if(shuffleOpenings) {
6304 SetUpShuffle(initialPosition, appData.defaultFrcPosition);
6305 startedFromSetupPosition = TRUE;
6307 if(startedFromPositionFile) {
6308 /* [HGM] loadPos: use PositionFile for every new game */
6309 CopyBoard(initialPosition, filePosition);
6310 for(i=0; i<nrCastlingRights; i++)
6311 initialRights[i] = filePosition[CASTLING][i];
6312 startedFromSetupPosition = TRUE;
6315 CopyBoard(boards[0], initialPosition);
6317 if(oldx != gameInfo.boardWidth ||
6318 oldy != gameInfo.boardHeight ||
6319 oldv != gameInfo.variant ||
6320 oldh != gameInfo.holdingsWidth
6322 InitDrawingSizes(-2 ,0);
6324 oldv = gameInfo.variant;
6326 DrawPosition(TRUE, boards[currentMove]);
6330 SendBoard (ChessProgramState *cps, int moveNum)
6332 char message[MSG_SIZ];
6334 if (cps->useSetboard) {
6335 char* fen = PositionToFEN(moveNum, cps->fenOverride, 1);
6336 snprintf(message, MSG_SIZ,"setboard %s\n", fen);
6337 SendToProgram(message, cps);
6342 int i, j, left=0, right=BOARD_WIDTH;
6343 /* Kludge to set black to move, avoiding the troublesome and now
6344 * deprecated "black" command.
6346 if (!WhiteOnMove(moveNum)) // [HGM] but better a deprecated command than an illegal move...
6347 SendToProgram(boards[0][1][BOARD_LEFT] == WhitePawn ? "a2a3\n" : "black\n", cps);
6349 if(!cps->extendedEdit) left = BOARD_LEFT, right = BOARD_RGHT; // only board proper
6351 SendToProgram("edit\n", cps);
6352 SendToProgram("#\n", cps);
6353 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6354 bp = &boards[moveNum][i][left];
6355 for (j = left; j < right; j++, bp++) {
6356 if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6357 if ((int) *bp < (int) BlackPawn) {
6358 if(j == BOARD_RGHT+1)
6359 snprintf(message, MSG_SIZ, "%c@%d\n", PieceToChar(*bp), bp[-1]);
6360 else snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp), AAA + j, ONE + i);
6361 if(message[0] == '+' || message[0] == '~') {
6362 snprintf(message, MSG_SIZ,"%c%c%c+\n",
6363 PieceToChar((ChessSquare)(DEMOTED *bp)),
6366 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6367 message[1] = BOARD_RGHT - 1 - j + '1';
6368 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6370 SendToProgram(message, cps);
6375 SendToProgram("c\n", cps);
6376 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
6377 bp = &boards[moveNum][i][left];
6378 for (j = left; j < right; j++, bp++) {
6379 if(j == BOARD_LEFT-1 || j == BOARD_RGHT) continue;
6380 if (((int) *bp != (int) EmptySquare)
6381 && ((int) *bp >= (int) BlackPawn)) {
6382 if(j == BOARD_LEFT-2)
6383 snprintf(message, MSG_SIZ, "%c@%d\n", ToUpper(PieceToChar(*bp)), bp[1]);
6384 else snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)),
6386 if(message[0] == '+' || message[0] == '~') {
6387 snprintf(message, MSG_SIZ,"%c%c%c+\n",
6388 PieceToChar((ChessSquare)(DEMOTED *bp)),
6391 if(cps->alphaRank) { /* [HGM] shogi: translate coords */
6392 message[1] = BOARD_RGHT - 1 - j + '1';
6393 message[2] = BOARD_HEIGHT - 1 - i + 'a';
6395 SendToProgram(message, cps);
6400 SendToProgram(".\n", cps);
6402 setboardSpoiledMachineBlack = 0; /* [HGM] assume WB 4.2.7 already solves this after sending setboard */
6405 char exclusionHeader[MSG_SIZ];
6406 int exCnt, excludePtr;
6407 typedef struct { int ff, fr, tf, tr, pc, mark; } Exclusion;
6408 static Exclusion excluTab[200];
6409 static char excludeMap[(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8]; // [HGM] exclude: bitmap for excluced moves
6415 for(j=0; j<(BOARD_RANKS*BOARD_FILES*BOARD_RANKS*BOARD_FILES+7)/8; j++) excludeMap[j] = s;
6416 exclusionHeader[19] = s ? '-' : '+'; // update tail state
6422 safeStrCpy(exclusionHeader, "exclude: none best +tail \n", MSG_SIZ);
6423 excludePtr = 24; exCnt = 0;
6428 UpdateExcludeHeader (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6429 { // search given move in table of header moves, to know where it is listed (and add if not there), and update state
6430 char buf[2*MOVE_LEN], *p;
6431 Exclusion *e = excluTab;
6433 for(i=0; i<exCnt; i++)
6434 if(e[i].ff == fromX && e[i].fr == fromY &&
6435 e[i].tf == toX && e[i].tr == toY && e[i].pc == promoChar) break;
6436 if(i == exCnt) { // was not in exclude list; add it
6437 CoordsToAlgebraic(boards[currentMove], PosFlags(currentMove), fromY, fromX, toY, toX, promoChar, buf);
6438 if(strlen(exclusionHeader + excludePtr) < strlen(buf)) { // no space to write move
6439 if(state != exclusionHeader[19]) exclusionHeader[19] = '*'; // tail is now in mixed state
6442 e[i].ff = fromX; e[i].fr = fromY; e[i].tf = toX; e[i].tr = toY; e[i].pc = promoChar;
6443 excludePtr++; e[i].mark = excludePtr++;
6444 for(p=buf; *p; p++) exclusionHeader[excludePtr++] = *p; // copy move
6447 exclusionHeader[e[i].mark] = state;
6451 ExcludeOneMove (int fromY, int fromX, int toY, int toX, char promoChar, char state)
6452 { // include or exclude the given move, as specified by state ('+' or '-'), or toggle
6456 if((signed char)promoChar == -1) { // kludge to indicate best move
6457 if(!ParseOneMove(lastPV[0], currentMove, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) // get current best move from last PV
6458 return 1; // if unparsable, abort
6460 // update exclusion map (resolving toggle by consulting existing state)
6461 k=(BOARD_FILES*fromY+fromX)*BOARD_RANKS*BOARD_FILES + (BOARD_FILES*toY+toX);
6463 if(state == '*') state = (excludeMap[k] & 1<<j ? '+' : '-'); // toggle
6464 if(state == '-' && !promoChar) // only non-promotions get marked as excluded, to allow exclusion of under-promotions
6465 excludeMap[k] |= 1<<j;
6466 else excludeMap[k] &= ~(1<<j);
6468 UpdateExcludeHeader(fromY, fromX, toY, toX, promoChar, state);
6470 snprintf(buf, MSG_SIZ, "%sclude ", state == '+' ? "in" : "ex");
6471 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar, buf+8);
6473 return (state == '+');
6477 ExcludeClick (int index)
6480 Exclusion *e = excluTab;
6481 if(index < 25) { // none, best or tail clicked
6482 if(index < 13) { // none: include all
6483 WriteMap(0); // clear map
6484 for(i=0; i<exCnt; i++) exclusionHeader[excluTab[i].mark] = '+'; // and moves
6485 SendToBoth("include all\n"); // and inform engine
6486 } else if(index > 18) { // tail
6487 if(exclusionHeader[19] == '-') { // tail was excluded
6488 SendToBoth("include all\n");
6489 WriteMap(0); // clear map completely
6490 // now re-exclude selected moves
6491 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '-')
6492 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '-');
6493 } else { // tail was included or in mixed state
6494 SendToBoth("exclude all\n");
6495 WriteMap(0xFF); // fill map completely
6496 // now re-include selected moves
6497 j = 0; // count them
6498 for(i=0; i<exCnt; i++) if(exclusionHeader[e[i].mark] == '+')
6499 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, '+'), j++;
6500 if(!j) ExcludeOneMove(0, 0, 0, 0, -1, '+'); // if no moves were selected, keep best
6503 ExcludeOneMove(0, 0, 0, 0, -1, '-'); // exclude it
6506 for(i=0; i<exCnt; i++) if(i == exCnt-1 || excluTab[i+1].mark > index) {
6507 char *p=exclusionHeader + excluTab[i].mark; // do trust header more than map (promotions!)
6508 ExcludeOneMove(e[i].fr, e[i].ff, e[i].tr, e[i].tf, e[i].pc, *p == '+' ? '-' : '+');
6515 DefaultPromoChoice (int white)
6518 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6519 gameInfo.variant == VariantMakruk || gameInfo.variant == VariantASEAN)
6520 result = WhiteFerz; // no choice
6521 else if(gameInfo.variant == VariantSuicide || gameInfo.variant == VariantGiveaway)
6522 result= WhiteKing; // in Suicide Q is the last thing we want
6523 else if(gameInfo.variant == VariantSpartan)
6524 result = white ? WhiteQueen : WhiteAngel;
6525 else result = WhiteQueen;
6526 if(!white) result = WHITE_TO_BLACK result;
6530 static int autoQueen; // [HGM] oneclick
6533 HasPromotionChoice (int fromX, int fromY, int toX, int toY, char *promoChoice, int sweepSelect)
6535 /* [HGM] rewritten IsPromotion to only flag promotions that offer a choice */
6536 /* [HGM] add Shogi promotions */
6537 int promotionZoneSize=1, highestPromotingPiece = (int)WhitePawn;
6538 ChessSquare piece, partner;
6542 if(fromX < BOARD_LEFT || fromX >= BOARD_RGHT) return FALSE; // drop
6543 if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return FALSE; // move into holdings
6545 if(gameMode == EditPosition || gameInfo.variant == VariantXiangqi || // no promotions
6546 !(fromX >=0 && fromY >= 0 && toX >= 0 && toY >= 0) ) // invalid move
6549 piece = boards[currentMove][fromY][fromX];
6550 if(gameInfo.variant == VariantChu) {
6551 int p = piece >= BlackPawn ? BLACK_TO_WHITE piece : piece;
6552 promotionZoneSize = BOARD_HEIGHT/3;
6553 highestPromotingPiece = (p >= WhiteLion || PieceToChar(piece + 22) == '.') ? WhitePawn : WhiteLion;
6554 } else if(gameInfo.variant == VariantShogi) {
6555 promotionZoneSize = BOARD_HEIGHT/3;
6556 highestPromotingPiece = (int)WhiteAlfil;
6557 } else if(gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess) {
6558 promotionZoneSize = 3;
6561 // Treat Lance as Pawn when it is not representing Amazon or Lance
6562 if(gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu) {
6563 if(piece == WhiteLance) piece = WhitePawn; else
6564 if(piece == BlackLance) piece = BlackPawn;
6567 // next weed out all moves that do not touch the promotion zone at all
6568 if((int)piece >= BlackPawn) {
6569 if(toY >= promotionZoneSize && fromY >= promotionZoneSize)
6571 if(fromY < promotionZoneSize && gameInfo.variant == VariantChuChess) return FALSE;
6572 highestPromotingPiece = WHITE_TO_BLACK highestPromotingPiece;
6574 if( toY < BOARD_HEIGHT - promotionZoneSize &&
6575 fromY < BOARD_HEIGHT - promotionZoneSize) return FALSE;
6576 if(fromY >= BOARD_HEIGHT - promotionZoneSize && gameInfo.variant == VariantChuChess)
6580 if( (int)piece > highestPromotingPiece ) return FALSE; // non-promoting piece
6582 // weed out mandatory Shogi promotions
6583 if(gameInfo.variant == VariantShogi) {
6584 if(piece >= BlackPawn) {
6585 if(toY == 0 && piece == BlackPawn ||
6586 toY == 0 && piece == BlackQueen ||
6587 toY <= 1 && piece == BlackKnight) {
6592 if(toY == BOARD_HEIGHT-1 && piece == WhitePawn ||
6593 toY == BOARD_HEIGHT-1 && piece == WhiteQueen ||
6594 toY >= BOARD_HEIGHT-2 && piece == WhiteKnight) {
6601 // weed out obviously illegal Pawn moves
6602 if(appData.testLegality && (piece == WhitePawn || piece == BlackPawn) ) {
6603 if(toX > fromX+1 || toX < fromX-1) return FALSE; // wide
6604 if(piece == WhitePawn && toY != fromY+1) return FALSE; // deep
6605 if(piece == BlackPawn && toY != fromY-1) return FALSE; // deep
6606 if(fromX != toX && gameInfo.variant == VariantShogi) return FALSE;
6607 // note we are not allowed to test for valid (non-)capture, due to premove
6610 // we either have a choice what to promote to, or (in Shogi) whether to promote
6611 if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
6612 gameInfo.variant == VariantMakruk || gameInfo.variant == VariantASEAN) {
6613 ChessSquare p=BlackFerz; // no choice
6614 while(p < EmptySquare) { //but make sure we use piece that exists
6615 *promoChoice = PieceToChar(p++);
6616 if(*promoChoice != '.') break;
6620 // no sense asking what we must promote to if it is going to explode...
6621 if(gameInfo.variant == VariantAtomic && boards[currentMove][toY][toX] != EmptySquare) {
6622 *promoChoice = PieceToChar(BlackQueen); // Queen as good as any
6625 // give caller the default choice even if we will not make it
6626 *promoChoice = ToLower(PieceToChar(defaultPromoChoice));
6627 partner = piece; // pieces can promote if the pieceToCharTable says so
6628 if(IS_SHOGI(gameInfo.variant)) *promoChoice = (defaultPromoChoice == piece && sweepSelect ? '=' : '+'); // obsolete?
6629 else if(Partner(&partner)) *promoChoice = (defaultPromoChoice == piece && sweepSelect ? NULLCHAR : '+');
6630 if( sweepSelect && gameInfo.variant != VariantGreat
6631 && gameInfo.variant != VariantGrand
6632 && gameInfo.variant != VariantSuper) return FALSE;
6633 if(autoQueen) return FALSE; // predetermined
6635 // suppress promotion popup on illegal moves that are not premoves
6636 premove = gameMode == IcsPlayingWhite && !WhiteOnMove(currentMove) ||
6637 gameMode == IcsPlayingBlack && WhiteOnMove(currentMove);
6638 if(appData.testLegality && !premove) {
6639 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
6640 fromY, fromX, toY, toX, IS_SHOGI(gameInfo.variant) || gameInfo.variant == VariantChuChess ? '+' : NULLCHAR);
6641 if(moveType == IllegalMove) *promoChoice = NULLCHAR; // could be the fact we promoted was illegal
6642 if(moveType != WhitePromotion && moveType != BlackPromotion)
6650 InPalace (int row, int column)
6651 { /* [HGM] for Xiangqi */
6652 if( (row < 3 || row > BOARD_HEIGHT-4) &&
6653 column < (BOARD_WIDTH + 4)/2 &&
6654 column > (BOARD_WIDTH - 5)/2 ) return TRUE;
6659 PieceForSquare (int x, int y)
6661 if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT)
6664 return boards[currentMove][y][x];
6668 OKToStartUserMove (int x, int y)
6670 ChessSquare from_piece;
6673 if (matchMode) return FALSE;
6674 if (gameMode == EditPosition) return TRUE;
6676 if (x >= 0 && y >= 0)
6677 from_piece = boards[currentMove][y][x];
6679 from_piece = EmptySquare;
6681 if (from_piece == EmptySquare) return FALSE;
6683 white_piece = (int)from_piece >= (int)WhitePawn &&
6684 (int)from_piece < (int)BlackPawn; /* [HGM] can be > King! */
6688 case TwoMachinesPlay:
6696 case MachinePlaysWhite:
6697 case IcsPlayingBlack:
6698 if (appData.zippyPlay) return FALSE;
6700 DisplayMoveError(_("You are playing Black"));
6705 case MachinePlaysBlack:
6706 case IcsPlayingWhite:
6707 if (appData.zippyPlay) return FALSE;
6709 DisplayMoveError(_("You are playing White"));
6714 case PlayFromGameFile:
6715 if(!shiftKey || !appData.variations) return FALSE; // [HGM] allow starting variation in this mode
6717 if (!white_piece && WhiteOnMove(currentMove)) {
6718 DisplayMoveError(_("It is White's turn"));
6721 if (white_piece && !WhiteOnMove(currentMove)) {
6722 DisplayMoveError(_("It is Black's turn"));
6725 if (cmailMsgLoaded && (currentMove < cmailOldMove)) {
6726 /* Editing correspondence game history */
6727 /* Could disallow this or prompt for confirmation */
6732 case BeginningOfGame:
6733 if (appData.icsActive) return FALSE;
6734 if (!appData.noChessProgram) {
6736 DisplayMoveError(_("You are playing White"));
6743 if (!white_piece && WhiteOnMove(currentMove)) {
6744 DisplayMoveError(_("It is White's turn"));
6747 if (white_piece && !WhiteOnMove(currentMove)) {
6748 DisplayMoveError(_("It is Black's turn"));
6757 if (currentMove != forwardMostMove && gameMode != AnalyzeMode
6758 && gameMode != EditGame // [HGM] vari: treat as AnalyzeMode
6759 && gameMode != PlayFromGameFile // [HGM] as EditGame, with protected main line
6760 && gameMode != AnalyzeFile && gameMode != Training) {
6761 DisplayMoveError(_("Displayed position is not current"));
6768 OnlyMove (int *x, int *y, Boolean captures)
6770 DisambiguateClosure cl;
6771 if (appData.zippyPlay || !appData.testLegality) return FALSE;
6773 case MachinePlaysBlack:
6774 case IcsPlayingWhite:
6775 case BeginningOfGame:
6776 if(!WhiteOnMove(currentMove)) return FALSE;
6778 case MachinePlaysWhite:
6779 case IcsPlayingBlack:
6780 if(WhiteOnMove(currentMove)) return FALSE;
6787 cl.pieceIn = EmptySquare;
6792 cl.promoCharIn = NULLCHAR;
6793 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6794 if( cl.kind == NormalMove ||
6795 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6796 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6797 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6804 if(cl.kind != ImpossibleMove) return FALSE;
6805 cl.pieceIn = EmptySquare;
6810 cl.promoCharIn = NULLCHAR;
6811 Disambiguate(boards[currentMove], PosFlags(currentMove), &cl);
6812 if( cl.kind == NormalMove ||
6813 cl.kind == AmbiguousMove && captures && cl.captures == 1 ||
6814 cl.kind == WhitePromotion || cl.kind == BlackPromotion ||
6815 cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) {
6820 autoQueen = TRUE; // act as if autoQueen on when we click to-square
6826 FILE *lastLoadGameFP = NULL, *lastLoadPositionFP = NULL;
6827 int lastLoadGameNumber = 0, lastLoadPositionNumber = 0;
6828 int lastLoadGameUseList = FALSE;
6829 char lastLoadGameTitle[MSG_SIZ], lastLoadPositionTitle[MSG_SIZ];
6830 ChessMove lastLoadGameStart = EndOfFile;
6832 Boolean addToBookFlag;
6835 UserMoveEvent(int fromX, int fromY, int toX, int toY, int promoChar)
6839 int ff=fromX, rf=fromY, ft=toX, rt=toY;
6841 /* Check if the user is playing in turn. This is complicated because we
6842 let the user "pick up" a piece before it is his turn. So the piece he
6843 tried to pick up may have been captured by the time he puts it down!
6844 Therefore we use the color the user is supposed to be playing in this
6845 test, not the color of the piece that is currently on the starting
6846 square---except in EditGame mode, where the user is playing both
6847 sides; fortunately there the capture race can't happen. (It can
6848 now happen in IcsExamining mode, but that's just too bad. The user
6849 will get a somewhat confusing message in that case.)
6854 case TwoMachinesPlay:
6858 /* We switched into a game mode where moves are not accepted,
6859 perhaps while the mouse button was down. */
6862 case MachinePlaysWhite:
6863 /* User is moving for Black */
6864 if (WhiteOnMove(currentMove)) {
6865 DisplayMoveError(_("It is White's turn"));
6870 case MachinePlaysBlack:
6871 /* User is moving for White */
6872 if (!WhiteOnMove(currentMove)) {
6873 DisplayMoveError(_("It is Black's turn"));
6878 case PlayFromGameFile:
6879 if(!shiftKey ||!appData.variations) return; // [HGM] only variations
6882 case BeginningOfGame:
6885 if(fromY == DROP_RANK) break; // [HGM] drop moves (entered through move type-in) are automatically assigned to side-to-move
6886 if ((int) boards[currentMove][fromY][fromX] >= (int) BlackPawn &&
6887 (int) boards[currentMove][fromY][fromX] < (int) EmptySquare) {
6888 /* User is moving for Black */
6889 if (WhiteOnMove(currentMove)) {
6890 DisplayMoveError(_("It is White's turn"));
6894 /* User is moving for White */
6895 if (!WhiteOnMove(currentMove)) {
6896 DisplayMoveError(_("It is Black's turn"));
6902 case IcsPlayingBlack:
6903 /* User is moving for Black */
6904 if (WhiteOnMove(currentMove)) {
6905 if (!appData.premove) {
6906 DisplayMoveError(_("It is White's turn"));
6907 } else if (toX >= 0 && toY >= 0) {
6910 premoveFromX = fromX;
6911 premoveFromY = fromY;
6912 premovePromoChar = promoChar;
6914 if (appData.debugMode)
6915 fprintf(debugFP, "Got premove: fromX %d,"
6916 "fromY %d, toX %d, toY %d\n",
6917 fromX, fromY, toX, toY);
6923 case IcsPlayingWhite:
6924 /* User is moving for White */
6925 if (!WhiteOnMove(currentMove)) {
6926 if (!appData.premove) {
6927 DisplayMoveError(_("It is Black's turn"));
6928 } else if (toX >= 0 && toY >= 0) {
6931 premoveFromX = fromX;
6932 premoveFromY = fromY;
6933 premovePromoChar = promoChar;
6935 if (appData.debugMode)
6936 fprintf(debugFP, "Got premove: fromX %d,"
6937 "fromY %d, toX %d, toY %d\n",
6938 fromX, fromY, toX, toY);
6948 /* EditPosition, empty square, or different color piece;
6949 click-click move is possible */
6950 if (toX == -2 || toY == -2) {
6951 boards[0][fromY][fromX] = (boards[0][fromY][fromX] == EmptySquare ? DarkSquare : EmptySquare);
6952 DrawPosition(FALSE, boards[currentMove]);
6954 } else if (toX >= 0 && toY >= 0) {
6955 if(!appData.pieceMenu && toX == fromX && toY == fromY && boards[0][rf][ff] != EmptySquare) {
6956 ChessSquare q, p = boards[0][rf][ff];
6957 if(p >= BlackPawn) p = BLACK_TO_WHITE p;
6958 if(CHUPROMOTED p < BlackPawn) p = q = CHUPROMOTED boards[0][rf][ff];
6959 else p = CHUDEMOTED (q = boards[0][rf][ff]);
6960 if(PieceToChar(q) == '+') gatingPiece = p;
6962 boards[0][toY][toX] = boards[0][fromY][fromX];
6963 if(fromX == BOARD_LEFT-2) { // handle 'moves' out of holdings
6964 if(boards[0][fromY][0] != EmptySquare) {
6965 if(boards[0][fromY][1]) boards[0][fromY][1]--;
6966 if(boards[0][fromY][1] == 0) boards[0][fromY][0] = EmptySquare;
6969 if(fromX == BOARD_RGHT+1) {
6970 if(boards[0][fromY][BOARD_WIDTH-1] != EmptySquare) {
6971 if(boards[0][fromY][BOARD_WIDTH-2]) boards[0][fromY][BOARD_WIDTH-2]--;
6972 if(boards[0][fromY][BOARD_WIDTH-2] == 0) boards[0][fromY][BOARD_WIDTH-1] = EmptySquare;
6975 boards[0][fromY][fromX] = gatingPiece;
6976 DrawPosition(FALSE, boards[currentMove]);
6982 if((toX < 0 || toY < 0) && (fromY != DROP_RANK || fromX != EmptySquare)) return;
6983 pup = boards[currentMove][toY][toX];
6985 /* [HGM] If move started in holdings, it means a drop. Convert to standard form */
6986 if( (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) && fromY != DROP_RANK ) {
6987 if( pup != EmptySquare ) return;
6988 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
6989 if(appData.debugMode) fprintf(debugFP, "Drop move %d, curr=%d, x=%d,y=%d, p=%d\n",
6990 moveType, currentMove, fromX, fromY, boards[currentMove][fromY][fromX]);
6991 // holdings might not be sent yet in ICS play; we have to figure out which piece belongs here
6992 if(fromX == 0) fromY = BOARD_HEIGHT-1 - fromY; // black holdings upside-down
6993 fromX = fromX ? WhitePawn : BlackPawn; // first piece type in selected holdings
6994 while(PieceToChar(fromX) == '.' || PieceToChar(fromX) == '+' || PieceToNumber(fromX) != fromY && fromX != (int) EmptySquare) fromX++;
6998 /* [HGM] always test for legality, to get promotion info */
6999 moveType = LegalityTest(boards[currentMove], PosFlags(currentMove),
7000 fromY, fromX, toY, toX, promoChar);
7002 if(fromY == DROP_RANK && fromX == EmptySquare && (gameMode == AnalyzeMode || gameMode == EditGame || PosFlags(0) & F_NULL_MOVE)) moveType = NormalMove;
7004 /* [HGM] but possibly ignore an IllegalMove result */
7005 if (appData.testLegality) {
7006 if (moveType == IllegalMove || moveType == ImpossibleMove) {
7007 DisplayMoveError(_("Illegal move"));
7012 if(doubleClick && gameMode == AnalyzeMode) { // [HGM] exclude: move entered with double-click on from square is for exclusion, not playing
7013 if(ExcludeOneMove(fromY, fromX, toY, toX, promoChar, '*')) // toggle
7014 ClearPremoveHighlights(); // was included
7015 else ClearHighlights(), SetPremoveHighlights(ff, rf, ft, rt); // exclusion indicated by premove highlights
7019 if(addToBookFlag) { // adding moves to book
7020 char buf[MSG_SIZ], move[MSG_SIZ];
7021 CoordsToAlgebraic(boards[currentMove], PosFlags(currentMove), fromY, fromX, toY, toX, promoChar, move);
7022 snprintf(buf, MSG_SIZ, " 0.0%% 1 %s\n", move);
7024 addToBookFlag = FALSE;
7029 FinishMove(moveType, fromX, fromY, toX, toY, promoChar);
7032 /* Common tail of UserMoveEvent and DropMenuEvent */
7034 FinishMove (ChessMove moveType, int fromX, int fromY, int toX, int toY, int promoChar)
7038 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) && promoChar != NULLCHAR) {
7039 // [HGM] superchess: suppress promotions to non-available piece (but P always allowed)
7040 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
7041 if(WhiteOnMove(currentMove)) {
7042 if(!boards[currentMove][k][BOARD_WIDTH-2]) return 0;
7044 if(!boards[currentMove][BOARD_HEIGHT-1-k][1]) return 0;
7048 /* [HGM] <popupFix> kludge to avoid having to know the exact promotion
7049 move type in caller when we know the move is a legal promotion */
7050 if(moveType == NormalMove && promoChar)
7051 moveType = WhiteOnMove(currentMove) ? WhitePromotion : BlackPromotion;
7053 /* [HGM] <popupFix> The following if has been moved here from
7054 UserMoveEvent(). Because it seemed to belong here (why not allow
7055 piece drops in training games?), and because it can only be
7056 performed after it is known to what we promote. */
7057 if (gameMode == Training) {
7058 /* compare the move played on the board to the next move in the
7059 * game. If they match, display the move and the opponent's response.
7060 * If they don't match, display an error message.
7064 CopyBoard(testBoard, boards[currentMove]);
7065 ApplyMove(fromX, fromY, toX, toY, promoChar, testBoard);
7067 if (CompareBoards(testBoard, boards[currentMove+1])) {
7068 ForwardInner(currentMove+1);
7070 /* Autoplay the opponent's response.
7071 * if appData.animate was TRUE when Training mode was entered,
7072 * the response will be animated.
7074 saveAnimate = appData.animate;
7075 appData.animate = animateTraining;
7076 ForwardInner(currentMove+1);
7077 appData.animate = saveAnimate;
7079 /* check for the end of the game */
7080 if (currentMove >= forwardMostMove) {
7081 gameMode = PlayFromGameFile;
7083 SetTrainingModeOff();
7084 DisplayInformation(_("End of game"));
7087 DisplayError(_("Incorrect move"), 0);
7092 /* Ok, now we know that the move is good, so we can kill
7093 the previous line in Analysis Mode */
7094 if ((gameMode == AnalyzeMode || gameMode == EditGame || gameMode == PlayFromGameFile && appData.variations && shiftKey)
7095 && currentMove < forwardMostMove) {
7096 if(appData.variations && shiftKey) PushTail(currentMove, forwardMostMove); // [HGM] vari: save tail of game
7097 else forwardMostMove = currentMove;
7102 /* If we need the chess program but it's dead, restart it */
7103 ResurrectChessProgram();
7105 /* A user move restarts a paused game*/
7109 thinkOutput[0] = NULLCHAR;
7111 MakeMove(fromX, fromY, toX, toY, promoChar); /*updates forwardMostMove*/
7113 if(Adjudicate(NULL)) { // [HGM] adjudicate: take care of automatic game end
7114 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7118 if (gameMode == BeginningOfGame) {
7119 if (appData.noChessProgram) {
7120 gameMode = EditGame;
7124 gameMode = MachinePlaysBlack;
7127 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
7129 if (first.sendName) {
7130 snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white);
7131 SendToProgram(buf, &first);
7138 /* Relay move to ICS or chess engine */
7139 if (appData.icsActive) {
7140 if (gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
7141 gameMode == IcsExamining) {
7142 if(userOfferedDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
7143 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
7145 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7147 // also send plain move, in case ICS does not understand atomic claims
7148 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
7152 if (first.sendTime && (gameMode == BeginningOfGame ||
7153 gameMode == MachinePlaysWhite ||
7154 gameMode == MachinePlaysBlack)) {
7155 SendTimeRemaining(&first, gameMode != MachinePlaysBlack);
7157 if (gameMode != EditGame && gameMode != PlayFromGameFile && gameMode != AnalyzeMode) {
7158 // [HGM] book: if program might be playing, let it use book
7159 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, FALSE);
7160 first.maybeThinking = TRUE;
7161 } else if(fromY == DROP_RANK && fromX == EmptySquare) {
7162 if(!first.useSetboard) SendToProgram("undo\n", &first); // kludge to change stm in engines that do not support setboard
7163 SendBoard(&first, currentMove+1);
7164 if(second.analyzing) {
7165 if(!second.useSetboard) SendToProgram("undo\n", &second);
7166 SendBoard(&second, currentMove+1);
7169 SendMoveToProgram(forwardMostMove-1, &first);
7170 if(second.analyzing) SendMoveToProgram(forwardMostMove-1, &second);
7172 if (currentMove == cmailOldMove + 1) {
7173 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
7177 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
7181 if(appData.testLegality)
7182 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
7188 if (WhiteOnMove(currentMove)) {
7189 GameEnds(BlackWins, "Black mates", GE_PLAYER);
7191 GameEnds(WhiteWins, "White mates", GE_PLAYER);
7195 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
7200 case MachinePlaysBlack:
7201 case MachinePlaysWhite:
7202 /* disable certain menu options while machine is thinking */
7203 SetMachineThinkingEnables();
7210 userOfferedDraw = FALSE; // [HGM] drawclaim: after move made, and tested for claimable draw
7211 promoDefaultAltered = FALSE; // [HGM] fall back on default choice
7213 if(bookHit) { // [HGM] book: simulate book reply
7214 static char bookMove[MSG_SIZ]; // a bit generous?
7216 programStats.nodes = programStats.depth = programStats.time =
7217 programStats.score = programStats.got_only_move = 0;
7218 sprintf(programStats.movelist, "%s (xbook)", bookHit);
7220 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
7221 strcat(bookMove, bookHit);
7222 HandleMachineMove(bookMove, &first);
7228 MarkByFEN(char *fen)
7231 if(!appData.markers || !appData.highlightDragging) return;
7232 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) legal[r][f] = 0;
7233 r=BOARD_HEIGHT-1; f=BOARD_LEFT;
7237 if(*fen == 'M') legal[r][f] = 2; else // request promotion choice
7238 if(*fen >= 'A' && *fen <= 'Z') legal[r][f] = 1; else
7239 if(*fen >= 'a' && *fen <= 'z') *fen += 'A' - 'a';
7240 if(*fen == '/' && f > BOARD_LEFT) f = BOARD_LEFT, r--; else
7241 if(*fen == 'T') marker[r][f++] = 0; else
7242 if(*fen == 'Y') marker[r][f++] = 1; else
7243 if(*fen == 'G') marker[r][f++] = 3; else
7244 if(*fen == 'B') marker[r][f++] = 4; else
7245 if(*fen == 'C') marker[r][f++] = 5; else
7246 if(*fen == 'M') marker[r][f++] = 6; else
7247 if(*fen == 'W') marker[r][f++] = 7; else
7248 if(*fen == 'D') marker[r][f++] = 8; else
7249 if(*fen == 'R') marker[r][f++] = 2; else {
7250 while(*fen <= '9' && *fen >= '0') s = 10*s + *fen++ - '0';
7253 while(f >= BOARD_RGHT) f -= BOARD_RGHT - BOARD_LEFT, r--;
7257 DrawPosition(TRUE, NULL);
7260 static char baseMarker[BOARD_RANKS][BOARD_FILES], baseLegal[BOARD_RANKS][BOARD_FILES];
7263 Mark (Board board, int flags, ChessMove kind, int rf, int ff, int rt, int ft, VOIDSTAR closure)
7265 typedef char Markers[BOARD_RANKS][BOARD_FILES];
7266 Markers *m = (Markers *) closure;
7267 if(rf == fromY && ff == fromX && (killX < 0 ? !(rt == rf && ft == ff) && legNr & 1 : rt == killY && ft == killX || legNr & 2))
7268 (*m)[rt][ft] = 1 + (board[rt][ft] != EmptySquare
7269 || kind == WhiteCapturesEnPassant
7270 || kind == BlackCapturesEnPassant) + 3*(kind == FirstLeg && killX < 0), legal[rt][ft] = 1;
7271 else if(flags & F_MANDATORY_CAPTURE && board[rt][ft] != EmptySquare) (*m)[rt][ft] = 3, legal[rt][ft] = 1;
7274 static int hoverSavedValid;
7277 MarkTargetSquares (int clear)
7280 if(clear) { // no reason to ever suppress clearing
7281 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) sum += marker[y][x], marker[y][x] = 0;
7282 hoverSavedValid = 0;
7283 if(!sum) return; // nothing was cleared,no redraw needed
7286 if(!appData.markers || !appData.highlightDragging || appData.icsActive && gameInfo.variant < VariantShogi ||
7287 !appData.testLegality && !pieceDefs || gameMode == EditPosition) return;
7288 GenLegal(boards[currentMove], PosFlags(currentMove), Mark, (void*) marker, EmptySquare);
7289 if(PosFlags(0) & F_MANDATORY_CAPTURE) {
7290 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x]>1) capt++;
7292 for(x=0; x<BOARD_WIDTH; x++) for(y=0; y<BOARD_HEIGHT; y++) if(marker[y][x] == 1) marker[y][x] = 0;
7295 DrawPosition(FALSE, NULL);
7299 Explode (Board board, int fromX, int fromY, int toX, int toY)
7301 if(gameInfo.variant == VariantAtomic &&
7302 (board[toY][toX] != EmptySquare || // capture?
7303 toX != fromX && (board[fromY][fromX] == WhitePawn || // e.p. ?
7304 board[fromY][fromX] == BlackPawn )
7306 AnimateAtomicCapture(board, fromX, fromY, toX, toY);
7312 ChessSquare gatingPiece = EmptySquare; // exported to front-end, for dragging
7315 CanPromote (ChessSquare piece, int y)
7317 int zone = (gameInfo.variant == VariantChuChess ? 3 : 1);
7318 if(gameMode == EditPosition) return FALSE; // no promotions when editing position
7319 // some variants have fixed promotion piece, no promotion at all, or another selection mechanism
7320 if(IS_SHOGI(gameInfo.variant) || gameInfo.variant == VariantXiangqi ||
7321 gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat ||
7322 gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier ||
7323 gameInfo.variant == VariantMakruk || gameInfo.variant == VariantASEAN) return FALSE;
7324 return (piece == BlackPawn && y <= zone ||
7325 piece == WhitePawn && y >= BOARD_HEIGHT-1-zone ||
7326 piece == BlackLance && y <= zone ||
7327 piece == WhiteLance && y >= BOARD_HEIGHT-1-zone );
7331 HoverEvent (int xPix, int yPix, int x, int y)
7333 static int oldX = -1, oldY = -1, oldFromX = -1, oldFromY = -1;
7335 if(!first.highlight) return;
7336 if(fromX != oldFromX || fromY != oldFromY) oldX = oldY = -1; // kludge to fake entry on from-click
7337 if(x == oldX && y == oldY) return; // only do something if we enter new square
7338 oldFromX = fromX; oldFromY = fromY;
7339 if(oldX == -1 && oldY == -1 && x == fromX && y == fromY) { // record markings after from-change
7340 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
7341 baseMarker[r][f] = marker[r][f], baseLegal[r][f] = legal[r][f];
7342 hoverSavedValid = 1;
7343 } else if(oldX != x || oldY != y) {
7344 // [HGM] lift: entered new to-square; redraw arrow, and inform engine
7345 if(hoverSavedValid) // don't restore markers that are supposed to be cleared
7346 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
7347 marker[r][f] = baseMarker[r][f], legal[r][f] = baseLegal[r][f];
7348 if((marker[y][x] == 2 || marker[y][x] == 6) && legal[y][x]) {
7350 snprintf(buf, MSG_SIZ, "hover %c%d\n", x + AAA, y + ONE - '0');
7351 SendToProgram(buf, &first);
7354 // SetHighlights(fromX, fromY, x, y);
7358 void ReportClick(char *action, int x, int y)
7360 char buf[MSG_SIZ]; // Inform engine of what user does
7362 if(action[0] == 'l') // mark any target square of a lifted piece as legal to-square, clear markers
7363 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++)
7364 legal[r][f] = !pieceDefs || !appData.markers, marker[r][f] = 0;
7365 if(!first.highlight || gameMode == EditPosition) return;
7366 snprintf(buf, MSG_SIZ, "%s %c%d%s\n", action, x+AAA, y+ONE-'0', controlKey && action[0]=='p' ? "," : "");
7367 SendToProgram(buf, &first);
7370 Boolean right; // instructs front-end to use button-1 events as if they were button 3
7373 LeftClick (ClickType clickType, int xPix, int yPix)
7376 Boolean saveAnimate;
7377 static int second = 0, promotionChoice = 0, clearFlag = 0, sweepSelecting = 0;
7378 char promoChoice = NULLCHAR;
7380 static TimeMark lastClickTime, prevClickTime;
7382 x = EventToSquare(xPix, BOARD_WIDTH);
7383 y = EventToSquare(yPix, BOARD_HEIGHT);
7384 if (!flipView && y >= 0) {
7385 y = BOARD_HEIGHT - 1 - y;
7387 if (flipView && x >= 0) {
7388 x = BOARD_WIDTH - 1 - x;
7391 if(appData.monoMouse && gameMode == EditPosition && fromX < 0 && clickType == Press && boards[currentMove][y][x] == EmptySquare) {
7393 RightClick(clickType, xPix, yPix, &dummy, &dummy);
7398 if(SeekGraphClick(clickType, xPix, yPix, 0)) return;
7400 prevClickTime = lastClickTime; GetTimeMark(&lastClickTime);
7402 if (clickType == Press) ErrorPopDown();
7403 lastClickType = clickType, lastLeftX = xPix, lastLeftY = yPix; // [HGM] alien: remember state
7405 if(promoSweep != EmptySquare) { // up-click during sweep-select of promo-piece
7406 defaultPromoChoice = promoSweep;
7407 promoSweep = EmptySquare; // terminate sweep
7408 promoDefaultAltered = TRUE;
7409 if(!selectFlag && !sweepSelecting && (x != toX || y != toY)) x = fromX, y = fromY; // and fake up-click on same square if we were still selecting
7412 if(promotionChoice) { // we are waiting for a click to indicate promotion piece
7413 if(clickType == Release) return; // ignore upclick of click-click destination
7414 promotionChoice = FALSE; // only one chance: if click not OK it is interpreted as cancel
7415 if(appData.debugMode) fprintf(debugFP, "promotion click, x=%d, y=%d\n", x, y);
7416 if(gameInfo.holdingsWidth &&
7417 (WhiteOnMove(currentMove)
7418 ? x == BOARD_WIDTH-1 && y < gameInfo.holdingsSize && y >= 0
7419 : x == 0 && y >= BOARD_HEIGHT - gameInfo.holdingsSize && y < BOARD_HEIGHT) ) {
7420 // click in right holdings, for determining promotion piece
7421 ChessSquare p = boards[currentMove][y][x];
7422 if(appData.debugMode) fprintf(debugFP, "square contains %d\n", (int)p);
7423 if(p == WhitePawn || p == BlackPawn) p = EmptySquare; // [HGM] Pawns could be valid as deferral
7424 if(p != EmptySquare || gameInfo.variant == VariantGrand && toY != 0 && toY != BOARD_HEIGHT-1) { // [HGM] grand: empty square means defer
7425 FinishMove(NormalMove, fromX, fromY, toX, toY, p==EmptySquare ? NULLCHAR : ToLower(PieceToChar(p)));
7430 DrawPosition(FALSE, boards[currentMove]);
7434 /* [HGM] holdings: next 5 lines: ignore all clicks between board and holdings */
7435 if(clickType == Press
7436 && ( x == BOARD_LEFT-1 || x == BOARD_RGHT
7437 || x == BOARD_LEFT-2 && y < BOARD_HEIGHT-gameInfo.holdingsSize
7438 || x == BOARD_RGHT+1 && y >= gameInfo.holdingsSize) )
7441 if(gotPremove && x == premoveFromX && y == premoveFromY && clickType == Release) {
7442 // could be static click on premove from-square: abort premove
7444 ClearPremoveHighlights();
7447 if(clickType == Press && fromX == x && fromY == y && promoDefaultAltered && SubtractTimeMarks(&lastClickTime, &prevClickTime) >= 200)
7448 fromX = fromY = -1; // second click on piece after altering default promo piece treated as first click
7450 if(!promoDefaultAltered) { // determine default promotion piece, based on the side the user is moving for
7451 int side = (gameMode == IcsPlayingWhite || gameMode == MachinePlaysBlack ||
7452 gameMode != MachinePlaysWhite && gameMode != IcsPlayingBlack && WhiteOnMove(currentMove));
7453 defaultPromoChoice = DefaultPromoChoice(side);
7456 autoQueen = appData.alwaysPromoteToQueen;
7460 gatingPiece = EmptySquare;
7461 if (clickType != Press) {
7462 if(dragging) { // [HGM] from-square must have been reset due to game end since last press
7463 DragPieceEnd(xPix, yPix); dragging = 0;
7464 DrawPosition(FALSE, NULL);
7468 doubleClick = FALSE;
7469 if(gameMode == AnalyzeMode && (pausing || controlKey) && first.excludeMoves) { // use pause state to exclude moves
7470 doubleClick = TRUE; gatingPiece = boards[currentMove][y][x];
7472 fromX = x; fromY = y; toX = toY = killX = killY = -1;
7473 if(!appData.oneClick || !OnlyMove(&x, &y, FALSE) ||
7474 // even if only move, we treat as normal when this would trigger a promotion popup, to allow sweep selection
7475 appData.sweepSelect && CanPromote(boards[currentMove][fromY][fromX], fromY) && originalY != y) {
7477 if (OKToStartUserMove(fromX, fromY)) {
7479 ReportClick("lift", x, y);
7480 MarkTargetSquares(0);
7481 if(gameMode == EditPosition && controlKey) gatingPiece = boards[currentMove][fromY][fromX];
7482 DragPieceBegin(xPix, yPix, FALSE); dragging = 1;
7483 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][fromY][fromX], fromY)) {
7484 promoSweep = defaultPromoChoice;
7485 selectFlag = 0; lastX = xPix; lastY = yPix;
7486 Sweep(0); // Pawn that is going to promote: preview promotion piece
7487 DisplayMessage("", _("Pull pawn backwards to under-promote"));
7489 if (appData.highlightDragging) {
7490 SetHighlights(fromX, fromY, -1, -1);
7494 } else fromX = fromY = -1;
7498 printf("to click %d,%d\n",x,y);
7500 if (clickType == Press && gameMode != EditPosition) {
7505 // ignore off-board to clicks
7506 if(y < 0 || x < 0) return;
7508 /* Check if clicking again on the same color piece */
7509 fromP = boards[currentMove][fromY][fromX];
7510 toP = boards[currentMove][y][x];
7511 frc = appData.fischerCastling || gameInfo.variant == VariantSChess;
7512 if( (killX < 0 || x != fromX || y != fromY) && // [HGM] lion: do not interpret igui as deselect!
7513 legal[y][x] == 0 && // if engine told we can move to here, do it even if own piece
7514 ((WhitePawn <= fromP && fromP <= WhiteKing &&
7515 WhitePawn <= toP && toP <= WhiteKing &&
7516 !(fromP == WhiteKing && toP == WhiteRook && frc) &&
7517 !(fromP == WhiteRook && toP == WhiteKing && frc)) ||
7518 (BlackPawn <= fromP && fromP <= BlackKing &&
7519 BlackPawn <= toP && toP <= BlackKing &&
7520 !(fromP == BlackRook && toP == BlackKing && frc) && // allow also RxK as FRC castling
7521 !(fromP == BlackKing && toP == BlackRook && frc)))) {
7522 /* Clicked again on same color piece -- changed his mind */
7523 second = (x == fromX && y == fromY);
7525 if(second && gameMode == AnalyzeMode && SubtractTimeMarks(&lastClickTime, &prevClickTime) < 200) {
7526 second = FALSE; // first double-click rather than scond click
7527 doubleClick = first.excludeMoves; // used by UserMoveEvent to recognize exclude moves
7529 promoDefaultAltered = FALSE;
7530 MarkTargetSquares(1);
7531 if(!(second && appData.oneClick && OnlyMove(&x, &y, TRUE))) {
7532 if (appData.highlightDragging) {
7533 SetHighlights(x, y, -1, -1);
7537 if (OKToStartUserMove(x, y)) {
7538 if(gameInfo.variant == VariantSChess && // S-Chess: back-rank piece selected after holdings means gating
7539 (fromX == BOARD_LEFT-2 || fromX == BOARD_RGHT+1) &&
7540 y == (toP < BlackPawn ? 0 : BOARD_HEIGHT-1))
7541 gatingPiece = boards[currentMove][fromY][fromX];
7542 else gatingPiece = doubleClick ? fromP : EmptySquare;
7544 fromY = y; dragging = 1;
7545 ReportClick("lift", x, y);
7546 MarkTargetSquares(0);
7547 DragPieceBegin(xPix, yPix, FALSE);
7548 if(appData.sweepSelect && CanPromote(piece = boards[currentMove][y][x], y)) {
7549 promoSweep = defaultPromoChoice;
7550 selectFlag = 0; lastX = xPix; lastY = yPix;
7551 Sweep(0); // Pawn that is going to promote: preview promotion piece
7555 if(x == fromX && y == fromY) return; // if OnlyMove altered (x,y) we go on
7558 // ignore clicks on holdings
7559 if(x < BOARD_LEFT || x >= BOARD_RGHT) return;
7561 printf("A type=%d\n",clickType);
7563 if(x == fromX && y == fromY && gameMode == EditPosition && SubtractTimeMarks(&lastClickTime, &prevClickTime) < 200) {
7564 gatingPiece = boards[currentMove][fromY][fromX]; // prepare to copy rather than move
7568 if (clickType == Release && x == fromX && y == fromY && killX < 0) {
7569 DragPieceEnd(xPix, yPix); dragging = 0;
7571 // a deferred attempt to click-click move an empty square on top of a piece
7572 boards[currentMove][y][x] = EmptySquare;
7574 DrawPosition(FALSE, boards[currentMove]);
7575 fromX = fromY = -1; clearFlag = 0;
7578 if (appData.animateDragging) {
7579 /* Undo animation damage if any */
7580 DrawPosition(FALSE, NULL);
7582 if (second || sweepSelecting) {
7583 /* Second up/down in same square; just abort move */
7584 if(sweepSelecting) DrawPosition(FALSE, boards[currentMove]);
7585 second = sweepSelecting = 0;
7587 gatingPiece = EmptySquare;
7588 MarkTargetSquares(1);
7591 ClearPremoveHighlights();
7593 /* First upclick in same square; start click-click mode */
7594 SetHighlights(x, y, -1, -1);
7601 if(gameMode != EditPosition && !appData.testLegality && !legal[y][x] &&
7602 fromX >= BOARD_LEFT && fromX < BOARD_RGHT && (x != killX || y != killY) && !sweepSelecting) {
7603 if(dragging) DragPieceEnd(xPix, yPix), dragging = 0;
7604 DisplayMessage(_("only marked squares are legal"),"");
7605 DrawPosition(TRUE, NULL);
7606 return; // ignore to-click
7608 printf("(%d,%d)-(%d,%d) %d %d\n",fromX,fromY,toX,toY,x,y);
7609 /* we now have a different from- and (possibly off-board) to-square */
7610 /* Completed move */
7611 if(!sweepSelecting) {
7616 piece = boards[currentMove][fromY][fromX];
7618 saveAnimate = appData.animate;
7619 if (clickType == Press) {
7620 if(gameInfo.variant == VariantChuChess && piece != WhitePawn && piece != BlackPawn) defaultPromoChoice = piece;
7621 if(gameMode == EditPosition && boards[currentMove][fromY][fromX] == EmptySquare) {
7622 // must be Edit Position mode with empty-square selected
7623 fromX = x; fromY = y; DragPieceBegin(xPix, yPix, FALSE); dragging = 1; // consider this a new attempt to drag
7624 if(x >= BOARD_LEFT && x < BOARD_RGHT) clearFlag = 1; // and defer click-click move of empty-square to up-click
7627 if(dragging == 2) { // [HGM] lion: just turn buttonless drag into normal drag, and let release to the job
7630 if(x == killX && y == killY) { // second click on this square, which was selected as first-leg target
7631 killX = killY = -1; // this informs us no second leg is coming, so treat as to-click without intermediate
7633 if(marker[y][x] == 5) return; // [HGM] lion: to-click on cyan square; defer action to release
7634 if(legal[y][x] == 2 || HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, FALSE)) {
7635 if(appData.sweepSelect) {
7636 promoSweep = defaultPromoChoice;
7637 if(gameInfo.variant != VariantChuChess && PieceToChar(CHUPROMOTED piece) == '+') promoSweep = CHUPROMOTED piece;
7638 selectFlag = 0; lastX = xPix; lastY = yPix;
7639 Sweep(0); // Pawn that is going to promote: preview promotion piece
7641 DisplayMessage("", _("Pull pawn backwards to under-promote"));
7642 MarkTargetSquares(1);
7644 return; // promo popup appears on up-click
7646 /* Finish clickclick move */
7647 if (appData.animate || appData.highlightLastMove) {
7648 SetHighlights(fromX, fromY, toX, toY);
7652 } else if(sweepSelecting) { // this must be the up-click corresponding to the down-click that started the sweep
7653 sweepSelecting = 0; appData.animate = FALSE; // do not animate, a selected piece already on to-square
7654 if (appData.animate || appData.highlightLastMove) {
7655 SetHighlights(fromX, fromY, toX, toY);
7661 // [HGM] this must be done after the move is made, as with arrow it could lead to a board redraw with piece still on from square
7662 /* Finish drag move */
7663 if (appData.highlightLastMove) {
7664 SetHighlights(fromX, fromY, toX, toY);
7669 if(gameInfo.variant == VariantChuChess && piece != WhitePawn && piece != BlackPawn) defaultPromoChoice = piece;
7670 if(marker[y][x] == 5) { // [HGM] lion: this was the release of a to-click or drag on a cyan square
7671 dragging *= 2; // flag button-less dragging if we are dragging
7672 MarkTargetSquares(1);
7673 if(x == killX && y == killY) killX = killY = -1; else {
7674 killX = x; killY = y; //remeber this square as intermediate
7675 ReportClick("put", x, y); // and inform engine
7676 ReportClick("lift", x, y);
7677 MarkTargetSquares(0);
7681 DragPieceEnd(xPix, yPix); dragging = 0;
7682 /* Don't animate move and drag both */
7683 appData.animate = FALSE;
7686 // moves into holding are invalid for now (except in EditPosition, adapting to-square)
7687 if(x >= 0 && x < BOARD_LEFT || x >= BOARD_RGHT) {
7688 ChessSquare piece = boards[currentMove][fromY][fromX];
7689 if(gameMode == EditPosition && piece != EmptySquare &&
7690 fromX >= BOARD_LEFT && fromX < BOARD_RGHT) {
7693 if(x == BOARD_LEFT-2 && piece >= BlackPawn) {
7694 n = PieceToNumber(piece - (int)BlackPawn);
7695 if(n >= gameInfo.holdingsSize) { n = 0; piece = BlackPawn; }
7696 boards[currentMove][BOARD_HEIGHT-1 - n][0] = piece;
7697 boards[currentMove][BOARD_HEIGHT-1 - n][1]++;
7699 if(x == BOARD_RGHT+1 && piece < BlackPawn) {
7700 n = PieceToNumber(piece);
7701 if(n >= gameInfo.holdingsSize) { n = 0; piece = WhitePawn; }
7702 boards[currentMove][n][BOARD_WIDTH-1] = piece;
7703 boards[currentMove][n][BOARD_WIDTH-2]++;
7705 boards[currentMove][fromY][fromX] = EmptySquare;
7709 MarkTargetSquares(1);
7710 DrawPosition(TRUE, boards[currentMove]);
7714 // off-board moves should not be highlighted
7715 if(x < 0 || y < 0) ClearHighlights();
7716 else ReportClick("put", x, y);
7718 if(gatingPiece != EmptySquare && gameInfo.variant == VariantSChess) promoChoice = ToLower(PieceToChar(gatingPiece));
7720 if (HasPromotionChoice(fromX, fromY, toX, toY, &promoChoice, appData.sweepSelect)) {
7721 SetHighlights(fromX, fromY, toX, toY);
7722 MarkTargetSquares(1);
7723 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
7724 // [HGM] super: promotion to captured piece selected from holdings
7725 ChessSquare p = boards[currentMove][fromY][fromX], q = boards[currentMove][toY][toX];
7726 promotionChoice = TRUE;
7727 // kludge follows to temporarily execute move on display, without promoting yet
7728 boards[currentMove][fromY][fromX] = EmptySquare; // move Pawn to 8th rank
7729 boards[currentMove][toY][toX] = p;
7730 DrawPosition(FALSE, boards[currentMove]);
7731 boards[currentMove][fromY][fromX] = p; // take back, but display stays
7732 boards[currentMove][toY][toX] = q;
7733 DisplayMessage("Click in holdings to choose piece", "");
7736 PromotionPopUp(promoChoice);
7738 int oldMove = currentMove;
7739 UserMoveEvent(fromX, fromY, toX, toY, promoChoice);
7740 if (!appData.highlightLastMove || gotPremove) ClearHighlights();
7741 if (gotPremove) SetPremoveHighlights(fromX, fromY, toX, toY);
7742 if(saveAnimate && !appData.animate && currentMove != oldMove && // drag-move was performed
7743 Explode(boards[currentMove-1], fromX, fromY, toX, toY))
7744 DrawPosition(TRUE, boards[currentMove]);
7745 MarkTargetSquares(1);
7748 appData.animate = saveAnimate;
7749 if (appData.animate || appData.animateDragging) {
7750 /* Undo animation damage if needed */
7751 DrawPosition(FALSE, NULL);
7756 RightClick (ClickType action, int x, int y, int *fromX, int *fromY)
7757 { // front-end-free part taken out of PieceMenuPopup
7758 int whichMenu; int xSqr, ySqr;
7760 if(seekGraphUp) { // [HGM] seekgraph
7761 if(action == Press) SeekGraphClick(Press, x, y, 2); // 2 indicates right-click: no pop-down on miss
7762 if(action == Release) SeekGraphClick(Release, x, y, 2); // and no challenge on hit
7766 if((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack)
7767 && !appData.zippyPlay && appData.bgObserve) { // [HGM] bughouse: show background game
7768 if(!partnerBoardValid) return -2; // suppress display of uninitialized boards
7769 if( appData.dualBoard) return -2; // [HGM] dual: is already displayed
7770 if(action == Press) {
7771 originalFlip = flipView;
7772 flipView = !flipView; // temporarily flip board to see game from partners perspective
7773 DrawPosition(TRUE, partnerBoard);
7774 DisplayMessage(partnerStatus, "");
7776 } else if(action == Release) {
7777 flipView = originalFlip;
7778 DrawPosition(TRUE, boards[currentMove]);
7784 xSqr = EventToSquare(x, BOARD_WIDTH);
7785 ySqr = EventToSquare(y, BOARD_HEIGHT);
7786 if (action == Release) {
7787 if(pieceSweep != EmptySquare) {
7788 EditPositionMenuEvent(pieceSweep, toX, toY);
7789 pieceSweep = EmptySquare;
7790 } else UnLoadPV(); // [HGM] pv
7792 if (action != Press) return -2; // return code to be ignored
7795 if(xSqr < BOARD_LEFT || xSqr >= BOARD_RGHT) return -1;
7797 if (xSqr == BOARD_LEFT-1 || xSqr == BOARD_RGHT) return -1;
7798 if (xSqr < 0 || ySqr < 0) return -1;
7799 if(appData.pieceMenu) { whichMenu = 0; break; } // edit-position menu
7800 pieceSweep = shiftKey ? BlackPawn : WhitePawn; // [HGM] sweep: prepare selecting piece by mouse sweep
7801 toX = xSqr; toY = ySqr; lastX = x, lastY = y;
7802 if(flipView) toX = BOARD_WIDTH - 1 - toX; else toY = BOARD_HEIGHT - 1 - toY;
7806 if(!appData.icsEngineAnalyze) return -1;
7807 case IcsPlayingWhite:
7808 case IcsPlayingBlack:
7809 if(!appData.zippyPlay) goto noZip;
7812 case MachinePlaysWhite:
7813 case MachinePlaysBlack:
7814 case TwoMachinesPlay: // [HGM] pv: use for showing PV
7815 if (!appData.dropMenu) {
7817 return 2; // flag front-end to grab mouse events
7819 if(gameMode == TwoMachinesPlay || gameMode == AnalyzeMode ||
7820 gameMode == AnalyzeFile || gameMode == IcsObserving) return -1;
7823 if (xSqr < 0 || ySqr < 0) return -1;
7824 if (!appData.dropMenu || appData.testLegality &&
7825 gameInfo.variant != VariantBughouse &&
7826 gameInfo.variant != VariantCrazyhouse) return -1;
7827 whichMenu = 1; // drop menu
7833 if (((*fromX = xSqr) < 0) ||
7834 ((*fromY = ySqr) < 0)) {
7835 *fromX = *fromY = -1;
7839 *fromX = BOARD_WIDTH - 1 - *fromX;
7841 *fromY = BOARD_HEIGHT - 1 - *fromY;
7847 SendProgramStatsToFrontend (ChessProgramState * cps, ChessProgramStats * cpstats)
7849 // char * hint = lastHint;
7850 FrontEndProgramStats stats;
7852 stats.which = cps == &first ? 0 : 1;
7853 stats.depth = cpstats->depth;
7854 stats.nodes = cpstats->nodes;
7855 stats.score = cpstats->score;
7856 stats.time = cpstats->time;
7857 stats.pv = cpstats->movelist;
7858 stats.hint = lastHint;
7859 stats.an_move_index = 0;
7860 stats.an_move_count = 0;
7862 if( gameMode == AnalyzeMode || gameMode == AnalyzeFile ) {
7863 stats.hint = cpstats->move_name;
7864 stats.an_move_index = cpstats->nr_moves - cpstats->moves_left;
7865 stats.an_move_count = cpstats->nr_moves;
7868 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
7870 SetProgramStats( &stats );
7874 ClearEngineOutputPane (int which)
7876 static FrontEndProgramStats dummyStats;
7877 dummyStats.which = which;
7878 dummyStats.pv = "#";
7879 SetProgramStats( &dummyStats );
7882 #define MAXPLAYERS 500
7885 TourneyStandings (int display)
7887 int i, w, b, color, wScore, bScore, dummy, nr=0, nPlayers=0;
7888 int score[MAXPLAYERS], ranking[MAXPLAYERS], points[MAXPLAYERS], games[MAXPLAYERS];
7889 char result, *p, *names[MAXPLAYERS];
7891 if(appData.tourneyType < 0 && !strchr(appData.results, '*'))
7892 return strdup(_("Swiss tourney finished")); // standings of Swiss yet TODO
7893 names[0] = p = strdup(appData.participants);
7894 while(p = strchr(p, '\n')) *p++ = NULLCHAR, names[++nPlayers] = p; // count participants
7896 for(i=0; i<nPlayers; i++) score[i] = games[i] = 0;
7898 while(result = appData.results[nr]) {
7899 color = Pairing(nr, nPlayers, &w, &b, &dummy);
7900 if(!(color ^ matchGame & 1)) { dummy = w; w = b; b = dummy; }
7901 wScore = bScore = 0;
7903 case '+': wScore = 2; break;
7904 case '-': bScore = 2; break;
7905 case '=': wScore = bScore = 1; break;
7907 case '*': return strdup("busy"); // tourney not finished
7915 if(appData.tourneyType > 0) nPlayers = appData.tourneyType; // in gauntlet, list only gauntlet engine(s)
7916 for(w=0; w<nPlayers; w++) {
7918 for(i=0; i<nPlayers; i++) if(score[i] > bScore) bScore = score[i], b = i;
7919 ranking[w] = b; points[w] = bScore; score[b] = -2;
7921 p = malloc(nPlayers*34+1);
7922 for(w=0; w<nPlayers && w<display; w++)
7923 sprintf(p+34*w, "%2d. %5.1f/%-3d %-19.19s\n", w+1, points[w]/2., games[ranking[w]], names[ranking[w]]);
7929 Count (Board board, int pCnt[], int *nW, int *nB, int *wStale, int *bStale, int *bishopColor)
7930 { // count all piece types
7932 *nB = *nW = *wStale = *bStale = *bishopColor = 0;
7933 for(p=WhitePawn; p<=EmptySquare; p++) pCnt[p] = 0;
7934 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
7937 if(p == WhitePawn && r == BOARD_HEIGHT-1) (*wStale)++; else
7938 if(p == BlackPawn && r == 0) (*bStale)++; // count last-Rank Pawns (XQ) separately
7939 if(p <= WhiteKing) (*nW)++; else if(p <= BlackKing) (*nB)++;
7940 if(p == WhiteBishop || p == WhiteFerz || p == WhiteAlfil ||
7941 p == BlackBishop || p == BlackFerz || p == BlackAlfil )
7942 *bishopColor |= 1 << ((f^r)&1); // track square color of color-bound pieces
7947 SufficientDefence (int pCnt[], int side, int nMine, int nHis)
7949 int myPawns = pCnt[WhitePawn+side]; // my total Pawn count;
7950 int majorDefense = pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackKnight-side];
7952 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side]; // discount defenders
7953 if(nMine - myPawns > 2) return FALSE; // no trivial draws with more than 1 major
7954 if(myPawns == 2 && nMine == 3) // KPP
7955 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 3;
7956 if(myPawns == 1 && nMine == 2) // KP
7957 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
7958 if(myPawns == 1 && nMine == 3 && pCnt[WhiteKnight+side]) // KHP
7959 return majorDefense || pCnt[BlackFerz-side] + pCnt[BlackAlfil-side]*2 >= 5;
7960 if(myPawns) return FALSE;
7961 if(pCnt[WhiteRook+side])
7962 return pCnt[BlackRook-side] ||
7963 pCnt[BlackCannon-side] && (pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] >= 2) ||
7964 pCnt[BlackKnight-side] && pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] > 2 ||
7965 pCnt[BlackFerz-side] + pCnt[BlackAlfil-side] >= 4;
7966 if(pCnt[WhiteCannon+side]) {
7967 if(pCnt[WhiteFerz+side] + myPawns == 0) return TRUE; // Cannon needs platform
7968 return majorDefense || pCnt[BlackAlfil-side] >= 2;
7970 if(pCnt[WhiteKnight+side])
7971 return majorDefense || pCnt[BlackFerz-side] >= 2 || pCnt[BlackAlfil-side] + pCnt[BlackPawn-side] >= 1;
7976 MatingPotential (int pCnt[], int side, int nMine, int nHis, int stale, int bisColor)
7978 VariantClass v = gameInfo.variant;
7980 if(v == VariantShogi || v == VariantCrazyhouse || v == VariantBughouse) return TRUE; // drop games always winnable
7981 if(v == VariantShatranj) return TRUE; // always winnable through baring
7982 if(v == VariantLosers || v == VariantSuicide || v == VariantGiveaway) return TRUE;
7983 if(v == Variant3Check || v == VariantAtomic) return nMine > 1; // can win through checking / exploding King
7985 if(v == VariantXiangqi) {
7986 int majors = 5*pCnt[BlackKnight-side] + 7*pCnt[BlackCannon-side] + 7*pCnt[BlackRook-side];
7988 nMine -= pCnt[WhiteFerz+side] + pCnt[WhiteAlfil+side] + stale; // discount defensive pieces and back-rank Pawns
7989 if(nMine + stale == 1) return (pCnt[BlackFerz-side] > 1 && pCnt[BlackKnight-side] > 0); // bare K can stalemate KHAA (!)
7990 if(nMine > 2) return TRUE; // if we don't have P, H or R, we must have CC
7991 if(nMine == 2 && pCnt[WhiteCannon+side] == 0) return TRUE; // We have at least one P, H or R
7992 // if we get here, we must have KC... or KP..., possibly with additional A, E or last-rank P
7993 if(stale) // we have at least one last-rank P plus perhaps C
7994 return majors // KPKX
7995 || pCnt[BlackFerz-side] && pCnt[BlackFerz-side] + pCnt[WhiteCannon+side] + stale > 2; // KPKAA, KPPKA and KCPKA
7997 return pCnt[WhiteFerz+side] // KCAK
7998 || pCnt[WhiteAlfil+side] && pCnt[BlackRook-side] + pCnt[BlackCannon-side] + pCnt[BlackFerz-side] // KCEKA, KCEKX (X!=H)
7999 || majors + (12*pCnt[BlackFerz-side] | 6*pCnt[BlackAlfil-side]) > 16; // KCKAA, KCKAX, KCKEEX, KCKEXX (XX!=HH), KCKXXX
8000 // TO DO: cases wih an unpromoted f-Pawn acting as platform for an opponent Cannon
8002 } else if(v == VariantKnightmate) {
8003 if(nMine == 1) return FALSE;
8004 if(nMine == 2 && nHis == 1 && pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side] + pCnt[WhiteKnight+side]) return FALSE; // KBK is only draw
8005 } else if(pCnt[WhiteKing] == 1 && pCnt[BlackKing] == 1) { // other variants with orthodox Kings
8006 int nBishops = pCnt[WhiteBishop+side] + pCnt[WhiteFerz+side];
8008 if(nMine == 1) return FALSE; // bare King
8009 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
8010 nMine += (nBishops > 0) - nBishops; // By now all Bishops (and Ferz) on like-colored squares, so count as one
8011 if(nMine > 2 && nMine != pCnt[WhiteAlfil+side] + 1) return TRUE; // At least two pieces, not all Alfils
8012 // by now we have King + 1 piece (or multiple Bishops on the same color)
8013 if(pCnt[WhiteKnight+side])
8014 return (pCnt[BlackKnight-side] + pCnt[BlackBishop-side] + pCnt[BlackMan-side] +
8015 pCnt[BlackWazir-side] + pCnt[BlackSilver-side] + bisColor // KNKN, KNKB, KNKF, KNKE, KNKW, KNKM, KNKS
8016 || nHis > 3); // be sure to cover suffocation mates in corner (e.g. KNKQCA)
8018 return (pCnt[BlackKnight-side]); // KBKN, KFKN
8019 if(pCnt[WhiteAlfil+side])
8020 return (nHis > 2); // Alfils can in general not reach a corner square, but there might be edge (suffocation) mates
8021 if(pCnt[WhiteWazir+side])
8022 return (pCnt[BlackKnight-side] + pCnt[BlackWazir-side] + pCnt[BlackAlfil-side]); // KWKN, KWKW, KWKE
8029 CompareWithRights (Board b1, Board b2)
8032 if(!CompareBoards(b1, b2)) return FALSE;
8033 if(b1[EP_STATUS] != b2[EP_STATUS]) return FALSE;
8034 /* compare castling rights */
8035 if( b1[CASTLING][2] != b2[CASTLING][2] && (b2[CASTLING][0] != NoRights || b2[CASTLING][1] != NoRights) )
8036 rights++; /* King lost rights, while rook still had them */
8037 if( b1[CASTLING][2] != NoRights ) { /* king has rights */
8038 if( b1[CASTLING][0] != b2[CASTLING][0] || b1[CASTLING][1] != b2[CASTLING][1] )
8039 rights++; /* but at least one rook lost them */
8041 if( b1[CASTLING][5] != b1[CASTLING][5] && (b2[CASTLING][3] != NoRights || b2[CASTLING][4] != NoRights) )
8043 if( b1[CASTLING][5] != NoRights ) {
8044 if( b1[CASTLING][3] != b2[CASTLING][3] || b1[CASTLING][4] != b2[CASTLING][4] )
8051 Adjudicate (ChessProgramState *cps)
8052 { // [HGM] some adjudications useful with buggy engines
8053 // [HGM] adjudicate: made into separate routine, which now can be called after every move
8054 // In any case it determnes if the game is a claimable draw (filling in EP_STATUS).
8055 // Actually ending the game is now based on the additional internal condition canAdjudicate.
8056 // Only when the game is ended, and the opponent is a computer, this opponent gets the move relayed.
8057 int k, drop, count = 0; static int bare = 1;
8058 ChessProgramState *engineOpponent = (gameMode == TwoMachinesPlay ? cps->other : (cps ? NULL : &first));
8059 Boolean canAdjudicate = !appData.icsActive;
8061 // most tests only when we understand the game, i.e. legality-checking on
8062 if( appData.testLegality )
8063 { /* [HGM] Some more adjudications for obstinate engines */
8064 int nrW, nrB, bishopColor, staleW, staleB, nr[EmptySquare+1], i;
8065 static int moveCount = 6;
8067 char *reason = NULL;
8069 /* Count what is on board. */
8070 Count(boards[forwardMostMove], nr, &nrW, &nrB, &staleW, &staleB, &bishopColor);
8072 /* Some material-based adjudications that have to be made before stalemate test */
8073 if(gameInfo.variant == VariantAtomic && nr[WhiteKing] + nr[BlackKing] < 2) {
8074 // [HGM] atomic: stm must have lost his King on previous move, as destroying own K is illegal
8075 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // make claimable as if stm is checkmated
8076 if(canAdjudicate && appData.checkMates) {
8078 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
8079 GameEnds( WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins,
8080 "Xboard adjudication: King destroyed", GE_XBOARD );
8085 /* Bare King in Shatranj (loses) or Losers (wins) */
8086 if( nrW == 1 || nrB == 1) {
8087 if( gameInfo.variant == VariantLosers) { // [HGM] losers: bare King wins (stm must have it first)
8088 boards[forwardMostMove][EP_STATUS] = EP_WINS; // mark as win, so it becomes claimable
8089 if(canAdjudicate && appData.checkMates) {
8091 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets to see move
8092 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
8093 "Xboard adjudication: Bare king", GE_XBOARD );
8097 if( gameInfo.variant == VariantShatranj && --bare < 0)
8099 boards[forwardMostMove][EP_STATUS] = EP_WINS; // make claimable as win for stm
8100 if(canAdjudicate && appData.checkMates) {
8101 /* but only adjudicate if adjudication enabled */
8103 SendMoveToProgram(forwardMostMove-1, engineOpponent); // make sure opponent gets move
8104 GameEnds( nrW > 1 ? WhiteWins : nrB > 1 ? BlackWins : GameIsDrawn,
8105 "Xboard adjudication: Bare king", GE_XBOARD );
8112 // don't wait for engine to announce game end if we can judge ourselves
8113 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
8115 if(gameInfo.variant == Variant3Check) { // [HGM] 3check: when in check, test if 3rd time
8116 int i, checkCnt = 0; // (should really be done by making nr of checks part of game state)
8117 for(i=forwardMostMove-2; i>=backwardMostMove; i-=2) {
8118 if(MateTest(boards[i], PosFlags(i)) == MT_CHECK)
8121 reason = "Xboard adjudication: 3rd check";
8122 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE;
8133 reason = "Xboard adjudication: Stalemate";
8134 if((signed char)boards[forwardMostMove][EP_STATUS] != EP_CHECKMATE) { // [HGM] don't touch win through baring or K-capt
8135 boards[forwardMostMove][EP_STATUS] = EP_STALEMATE; // default result for stalemate is draw
8136 if(gameInfo.variant == VariantLosers || gameInfo.variant == VariantGiveaway) // [HGM] losers:
8137 boards[forwardMostMove][EP_STATUS] = EP_WINS; // in these variants stalemated is always a win
8138 else if(gameInfo.variant == VariantSuicide) // in suicide it depends
8139 boards[forwardMostMove][EP_STATUS] = nrW == nrB ? EP_STALEMATE :
8140 ((nrW < nrB) != WhiteOnMove(forwardMostMove) ?
8141 EP_CHECKMATE : EP_WINS);
8142 else if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi)
8143 boards[forwardMostMove][EP_STATUS] = EP_CHECKMATE; // and in these variants being stalemated loses
8147 reason = "Xboard adjudication: Checkmate";
8148 boards[forwardMostMove][EP_STATUS] = (gameInfo.variant == VariantLosers ? EP_WINS : EP_CHECKMATE);
8149 if(gameInfo.variant == VariantShogi) {
8150 if(forwardMostMove > backwardMostMove
8151 && moveList[forwardMostMove-1][1] == '@'
8152 && CharToPiece(ToUpper(moveList[forwardMostMove-1][0])) == WhitePawn) {
8153 reason = "XBoard adjudication: pawn-drop mate";
8154 boards[forwardMostMove][EP_STATUS] = EP_WINS;
8160 switch(i = (signed char)boards[forwardMostMove][EP_STATUS]) {
8162 result = GameIsDrawn; break;
8164 result = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins; break;
8166 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins; break;
8170 if(canAdjudicate && appData.checkMates && result) { // [HGM] mates: adjudicate finished games if requested
8172 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8173 GameEnds( result, reason, GE_XBOARD );
8177 /* Next absolutely insufficient mating material. */
8178 if(!MatingPotential(nr, WhitePawn, nrW, nrB, staleW, bishopColor) &&
8179 !MatingPotential(nr, BlackPawn, nrB, nrW, staleB, bishopColor))
8180 { /* includes KBK, KNK, KK of KBKB with like Bishops */
8182 /* always flag draws, for judging claims */
8183 boards[forwardMostMove][EP_STATUS] = EP_INSUF_DRAW;
8185 if(canAdjudicate && appData.materialDraws) {
8186 /* but only adjudicate them if adjudication enabled */
8187 if(engineOpponent) {
8188 SendToProgram("force\n", engineOpponent); // suppress reply
8189 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see last move */
8191 GameEnds( GameIsDrawn, "Xboard adjudication: Insufficient mating material", GE_XBOARD );
8196 /* Then some trivial draws (only adjudicate, cannot be claimed) */
8197 if(gameInfo.variant == VariantXiangqi ?
8198 SufficientDefence(nr, WhitePawn, nrW, nrB) && SufficientDefence(nr, BlackPawn, nrB, nrW)
8200 ( nr[WhiteRook] == 1 && nr[BlackRook] == 1 /* KRKR */
8201 || nr[WhiteQueen] && nr[BlackQueen]==1 /* KQKQ */
8202 || nr[WhiteKnight]==2 || nr[BlackKnight]==2 /* KNNK */
8203 || nr[WhiteKnight]+nr[WhiteBishop] == 1 && nr[BlackKnight]+nr[BlackBishop] == 1 /* KBKN, KBKB, KNKN */
8205 if(--moveCount < 0 && appData.trivialDraws && canAdjudicate)
8206 { /* if the first 3 moves do not show a tactical win, declare draw */
8207 if(engineOpponent) {
8208 SendToProgram("force\n", engineOpponent); // suppress reply
8209 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8211 GameEnds( GameIsDrawn, "Xboard adjudication: Trivial draw", GE_XBOARD );
8214 } else moveCount = 6;
8217 // Repetition draws and 50-move rule can be applied independently of legality testing
8219 /* Check for rep-draws */
8221 drop = gameInfo.holdingsSize && (gameInfo.variant != VariantSuper && gameInfo.variant != VariantSChess
8222 && gameInfo.variant != VariantGreat && gameInfo.variant != VariantGrand);
8223 for(k = forwardMostMove-2;
8224 k>=backwardMostMove && k>=forwardMostMove-100 && (drop ||
8225 (signed char)boards[k][EP_STATUS] < EP_UNKNOWN &&
8226 (signed char)boards[k+2][EP_STATUS] <= EP_NONE && (signed char)boards[k+1][EP_STATUS] <= EP_NONE);
8229 if(CompareBoards(boards[k], boards[forwardMostMove])) {
8230 /* compare castling rights */
8231 if( boards[forwardMostMove][CASTLING][2] != boards[k][CASTLING][2] &&
8232 (boards[k][CASTLING][0] != NoRights || boards[k][CASTLING][1] != NoRights) )
8233 rights++; /* King lost rights, while rook still had them */
8234 if( boards[forwardMostMove][CASTLING][2] != NoRights ) { /* king has rights */
8235 if( boards[forwardMostMove][CASTLING][0] != boards[k][CASTLING][0] ||
8236 boards[forwardMostMove][CASTLING][1] != boards[k][CASTLING][1] )
8237 rights++; /* but at least one rook lost them */
8239 if( boards[forwardMostMove][CASTLING][5] != boards[k][CASTLING][5] &&
8240 (boards[k][CASTLING][3] != NoRights || boards[k][CASTLING][4] != NoRights) )
8242 if( boards[forwardMostMove][CASTLING][5] != NoRights ) {
8243 if( boards[forwardMostMove][CASTLING][3] != boards[k][CASTLING][3] ||
8244 boards[forwardMostMove][CASTLING][4] != boards[k][CASTLING][4] )
8247 if( rights == 0 && ++count > appData.drawRepeats-2 && canAdjudicate
8248 && appData.drawRepeats > 1) {
8249 /* adjudicate after user-specified nr of repeats */
8250 int result = GameIsDrawn;
8251 char *details = "XBoard adjudication: repetition draw";
8252 if((gameInfo.variant == VariantXiangqi || gameInfo.variant == VariantShogi) && appData.testLegality) {
8253 // [HGM] xiangqi: check for forbidden perpetuals
8254 int m, ourPerpetual = 1, hisPerpetual = 1;
8255 for(m=forwardMostMove; m>k; m-=2) {
8256 if(MateTest(boards[m], PosFlags(m)) != MT_CHECK)
8257 ourPerpetual = 0; // the current mover did not always check
8258 if(MateTest(boards[m-1], PosFlags(m-1)) != MT_CHECK)
8259 hisPerpetual = 0; // the opponent did not always check
8261 if(appData.debugMode) fprintf(debugFP, "XQ perpetual test, our=%d, his=%d\n",
8262 ourPerpetual, hisPerpetual);
8263 if(ourPerpetual && !hisPerpetual) { // we are actively checking him: forfeit
8264 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
8265 details = "Xboard adjudication: perpetual checking";
8267 if(hisPerpetual && !ourPerpetual) { // he is checking us, but did not repeat yet
8268 break; // (or we would have caught him before). Abort repetition-checking loop.
8270 if(gameInfo.variant == VariantShogi) { // in Shogi other repetitions are draws
8271 if(BOARD_HEIGHT == 5 && BOARD_RGHT - BOARD_LEFT == 5) { // but in mini-Shogi gote wins!
8273 details = "Xboard adjudication: repetition";
8275 } else // it must be XQ
8276 // Now check for perpetual chases
8277 if(!ourPerpetual && !hisPerpetual) { // no perpetual check, test for chase
8278 hisPerpetual = PerpetualChase(k, forwardMostMove);
8279 ourPerpetual = PerpetualChase(k+1, forwardMostMove);
8280 if(ourPerpetual && !hisPerpetual) { // we are actively chasing him: forfeit
8281 static char resdet[MSG_SIZ];
8282 result = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
8284 snprintf(resdet, MSG_SIZ, "Xboard adjudication: perpetual chasing of %c%c", ourPerpetual>>8, ourPerpetual&255);
8286 if(hisPerpetual && !ourPerpetual) // he is chasing us, but did not repeat yet
8287 break; // Abort repetition-checking loop.
8289 // if neither of us is checking or chasing all the time, or both are, it is draw
8291 if(engineOpponent) {
8292 SendToProgram("force\n", engineOpponent); // suppress reply
8293 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8295 GameEnds( result, details, GE_XBOARD );
8298 if( rights == 0 && count > 1 ) /* occurred 2 or more times before */
8299 boards[forwardMostMove][EP_STATUS] = EP_REP_DRAW;
8303 /* Now we test for 50-move draws. Determine ply count */
8304 count = forwardMostMove;
8305 /* look for last irreversble move */
8306 while( (signed char)boards[count][EP_STATUS] <= EP_NONE && count > backwardMostMove )
8308 /* if we hit starting position, add initial plies */
8309 if( count == backwardMostMove )
8310 count -= initialRulePlies;
8311 count = forwardMostMove - count;
8312 if(gameInfo.variant == VariantXiangqi && ( count >= 100 || count >= 2*appData.ruleMoves ) ) {
8313 // adjust reversible move counter for checks in Xiangqi
8314 int i = forwardMostMove - count, inCheck = 0, lastCheck;
8315 if(i < backwardMostMove) i = backwardMostMove;
8316 while(i <= forwardMostMove) {
8317 lastCheck = inCheck; // check evasion does not count
8318 inCheck = (MateTest(boards[i], PosFlags(i)) == MT_CHECK);
8319 if(inCheck || lastCheck) count--; // check does not count
8324 boards[forwardMostMove][EP_STATUS] = EP_RULE_DRAW;
8325 /* this is used to judge if draw claims are legal */
8326 if(canAdjudicate && appData.ruleMoves > 0 && count >= 2*appData.ruleMoves) {
8327 if(engineOpponent) {
8328 SendToProgram("force\n", engineOpponent); // suppress reply
8329 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8331 GameEnds( GameIsDrawn, "Xboard adjudication: 50-move rule", GE_XBOARD );
8335 /* if draw offer is pending, treat it as a draw claim
8336 * when draw condition present, to allow engines a way to
8337 * claim draws before making their move to avoid a race
8338 * condition occurring after their move
8340 if((gameMode == TwoMachinesPlay ? second.offeredDraw : userOfferedDraw) || first.offeredDraw ) {
8342 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_RULE_DRAW)
8343 p = "Draw claim: 50-move rule";
8344 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_REP_DRAW)
8345 p = "Draw claim: 3-fold repetition";
8346 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_INSUF_DRAW)
8347 p = "Draw claim: insufficient mating material";
8348 if( p != NULL && canAdjudicate) {
8349 if(engineOpponent) {
8350 SendToProgram("force\n", engineOpponent); // suppress reply
8351 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8353 GameEnds( GameIsDrawn, p, GE_XBOARD );
8358 if( canAdjudicate && appData.adjudicateDrawMoves > 0 && forwardMostMove > (2*appData.adjudicateDrawMoves) ) {
8359 if(engineOpponent) {
8360 SendToProgram("force\n", engineOpponent); // suppress reply
8361 SendMoveToProgram(forwardMostMove-1, engineOpponent); /* make sure opponent gets to see move */
8363 GameEnds( GameIsDrawn, "Xboard adjudication: long game", GE_XBOARD );
8369 typedef int (CDECL *PPROBE_EGBB) (int player, int *piece, int *square);
8370 typedef int (CDECL *PLOAD_EGBB) (char *path, int cache_size, int load_options);
8371 static int egbbCode[] = { 6, 5, 4, 3, 2, 1 };
8376 int pieces[10], squares[10], cnt=0, r, f, res;
8378 static PPROBE_EGBB probeBB;
8379 if(!appData.testLegality) return 10;
8380 if(BOARD_HEIGHT != 8 || BOARD_RGHT-BOARD_LEFT != 8) return 12;
8381 if(gameInfo.holdingsSize && gameInfo.variant != VariantSuper && gameInfo.variant != VariantSChess) return 12;
8382 if(loaded == 2 && forwardMostMove < 2) loaded = 0; // retry on new game
8383 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
8384 ChessSquare piece = boards[forwardMostMove][r][f];
8385 int black = (piece >= BlackPawn);
8386 int type = piece - black*BlackPawn;
8387 if(piece == EmptySquare) continue;
8388 if(type != WhiteKing && type > WhiteQueen) return 12; // unorthodox piece
8389 if(type == WhiteKing) type = WhiteQueen + 1;
8390 type = egbbCode[type];
8391 squares[cnt] = r*(BOARD_RGHT - BOARD_LEFT) + f - BOARD_LEFT;
8392 pieces[cnt] = type + black*6;
8393 if(++cnt > 5) return 11;
8395 pieces[cnt] = squares[cnt] = 0;
8397 if(loaded == 2) return 13; // loading failed before
8399 char *p, *path = strstr(appData.egtFormats, "scorpio:"), buf[MSG_SIZ];
8402 loaded = 2; // prepare for failure
8403 if(!path) return 13; // no egbb installed
8404 strncpy(buf, path + 8, MSG_SIZ);
8405 if(p = strchr(buf, ',')) *p = NULLCHAR; else p = buf + strlen(buf);
8406 snprintf(p, MSG_SIZ - strlen(buf), "%c%s", SLASH, EGBB_NAME);
8407 lib = LoadLibrary(buf);
8408 if(!lib) { DisplayError(_("could not load EGBB library"), 0); return 13; }
8409 loadBB = (PLOAD_EGBB) GetProcAddress(lib, "load_egbb_xmen");
8410 probeBB = (PPROBE_EGBB) GetProcAddress(lib, "probe_egbb_xmen");
8411 if(!loadBB || !probeBB) { DisplayError(_("wrong EGBB version"), 0); return 13; }
8412 p[1] = NULLCHAR; loadBB(buf, 64*1028, 2); // 2 = SMART_LOAD
8413 loaded = 1; // success!
8415 res = probeBB(forwardMostMove & 1, pieces, squares);
8416 return res > 0 ? 1 : res < 0 ? -1 : 0;
8420 SendMoveToBookUser (int moveNr, ChessProgramState *cps, int initial)
8421 { // [HGM] book: this routine intercepts moves to simulate book replies
8422 char *bookHit = NULL;
8424 if(cps->drawDepth && BitbaseProbe() == 0) { // [HG} egbb: reduce depth in drawn position
8426 snprintf(buf, MSG_SIZ, "sd %d\n", cps->drawDepth);
8427 SendToProgram(buf, cps);
8429 //first determine if the incoming move brings opponent into his book
8430 if(appData.usePolyglotBook && (cps == &first ? !appData.firstHasOwnBookUCI : !appData.secondHasOwnBookUCI))
8431 bookHit = ProbeBook(moveNr+1, appData.polyglotBook); // returns move
8432 if(appData.debugMode) fprintf(debugFP, "book hit = %s\n", bookHit ? bookHit : "(NULL)");
8433 if(bookHit != NULL && !cps->bookSuspend) {
8434 // make sure opponent is not going to reply after receiving move to book position
8435 SendToProgram("force\n", cps);
8436 cps->bookSuspend = TRUE; // flag indicating it has to be restarted
8438 if(bookHit) setboardSpoiledMachineBlack = FALSE; // suppress 'go' in SendMoveToProgram
8439 if(!initial) SendMoveToProgram(moveNr, cps); // with hit on initial position there is no move
8440 // now arrange restart after book miss
8442 // after a book hit we never send 'go', and the code after the call to this routine
8443 // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove').
8444 char buf[MSG_SIZ], *move = bookHit;
8446 int fromX, fromY, toX, toY;
8450 if (ParseOneMove(bookHit, forwardMostMove, &moveType,
8451 &fromX, &fromY, &toX, &toY, &promoChar)) {
8452 (void) CoordsToAlgebraic(boards[forwardMostMove],
8453 PosFlags(forwardMostMove),
8454 fromY, fromX, toY, toX, promoChar, move);
8456 if(appData.debugMode) fprintf(debugFP, "Book move could not be parsed\n");
8460 snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), move); // force book move into program supposed to play it
8461 SendToProgram(buf, cps);
8462 if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go'
8463 } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine
8464 SendToProgram("go\n", cps);
8465 cps->bookSuspend = FALSE; // after a 'go' we are never suspended
8466 } else { // 'go' might be sent based on 'firstMove' after this routine returns
8467 if(cps->bookSuspend && !firstMove) // 'go' needed, and it will not be done after we return
8468 SendToProgram("go\n", cps);
8469 cps->bookSuspend = FALSE; // anyhow, we will not be suspended after a miss
8471 return bookHit; // notify caller of hit, so it can take action to send move to opponent
8475 LoadError (char *errmess, ChessProgramState *cps)
8476 { // unloads engine and switches back to -ncp mode if it was first
8477 if(cps->initDone) return FALSE;
8478 cps->isr = NULL; // this should suppress further error popups from breaking pipes
8479 DestroyChildProcess(cps->pr, 9 ); // just to be sure
8482 appData.noChessProgram = TRUE;
8483 gameMode = MachinePlaysBlack; ModeHighlight(); // kludge to unmark Machine Black menu
8484 gameMode = BeginningOfGame; ModeHighlight();
8487 if(GetDelayedEvent()) CancelDelayedEvent(), ThawUI(); // [HGM] cancel remaining loading effort scheduled after feature timeout
8488 DisplayMessage("", ""); // erase waiting message
8489 if(errmess) DisplayError(errmess, 0); // announce reason, if given
8494 ChessProgramState *savedState;
8496 DeferredBookMove (void)
8498 if(savedState->lastPing != savedState->lastPong)
8499 ScheduleDelayedEvent(DeferredBookMove, 10);
8501 HandleMachineMove(savedMessage, savedState);
8504 static int savedWhitePlayer, savedBlackPlayer, pairingReceived;
8505 static ChessProgramState *stalledEngine;
8506 static char stashedInputMove[MSG_SIZ];
8509 HandleMachineMove (char *message, ChessProgramState *cps)
8511 static char firstLeg[20];
8512 char machineMove[MSG_SIZ], buf1[MSG_SIZ*10], buf2[MSG_SIZ];
8513 char realname[MSG_SIZ];
8514 int fromX, fromY, toX, toY;
8516 char promoChar, roar;
8518 int machineWhite, oldError;
8521 if(cps == &pairing && sscanf(message, "%d-%d", &savedWhitePlayer, &savedBlackPlayer) == 2) {
8522 // [HGM] pairing: Mega-hack! Pairing engine also uses this routine (so it could give other WB commands).
8523 if(savedWhitePlayer == 0 || savedBlackPlayer == 0) {
8524 DisplayError(_("Invalid pairing from pairing engine"), 0);
8527 pairingReceived = 1;
8529 return; // Skim the pairing messages here.
8532 oldError = cps->userError; cps->userError = 0;
8534 FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book hit
8536 * Kludge to ignore BEL characters
8538 while (*message == '\007') message++;
8541 * [HGM] engine debug message: ignore lines starting with '#' character
8543 if(cps->debug && *message == '#') return;
8546 * Look for book output
8548 if (cps == &first && bookRequested) {
8549 if (message[0] == '\t' || message[0] == ' ') {
8550 /* Part of the book output is here; append it */
8551 strcat(bookOutput, message);
8552 strcat(bookOutput, " \n");
8554 } else if (bookOutput[0] != NULLCHAR) {
8555 /* All of book output has arrived; display it */
8556 char *p = bookOutput;
8557 while (*p != NULLCHAR) {
8558 if (*p == '\t') *p = ' ';
8561 DisplayInformation(bookOutput);
8562 bookRequested = FALSE;
8563 /* Fall through to parse the current output */
8568 * Look for machine move.
8570 if ((sscanf(message, "%s %s %s", buf1, buf2, machineMove) == 3 && strcmp(buf2, "...") == 0) ||
8571 (sscanf(message, "%s %s", buf1, machineMove) == 2 && strcmp(buf1, "move") == 0))
8573 if(pausing && !cps->pause) { // for pausing engine that does not support 'pause', we stash its move for processing when we resume.
8574 if(appData.debugMode) fprintf(debugFP, "pause %s engine after move\n", cps->which);
8575 safeStrCpy(stashedInputMove, message, MSG_SIZ);
8576 stalledEngine = cps;
8577 if(appData.ponderNextMove) { // bring opponent out of ponder
8578 if(gameMode == TwoMachinesPlay) {
8579 if(cps->other->pause)
8580 PauseEngine(cps->other);
8582 SendToProgram("easy\n", cps->other);
8589 /* This method is only useful on engines that support ping */
8590 if (cps->lastPing != cps->lastPong) {
8591 if (gameMode == BeginningOfGame) {
8592 /* Extra move from before last new; ignore */
8593 if (appData.debugMode) {
8594 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8597 if (appData.debugMode) {
8598 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
8599 cps->which, gameMode);
8602 SendToProgram("undo\n", cps);
8608 case BeginningOfGame:
8609 /* Extra move from before last reset; ignore */
8610 if (appData.debugMode) {
8611 fprintf(debugFP, "Ignoring extra move from %s\n", cps->which);
8618 /* Extra move after we tried to stop. The mode test is
8619 not a reliable way of detecting this problem, but it's
8620 the best we can do on engines that don't support ping.
8622 if (appData.debugMode) {
8623 fprintf(debugFP, "Undoing extra move from %s, gameMode %d\n",
8624 cps->which, gameMode);
8626 SendToProgram("undo\n", cps);
8629 case MachinePlaysWhite:
8630 case IcsPlayingWhite:
8631 machineWhite = TRUE;
8634 case MachinePlaysBlack:
8635 case IcsPlayingBlack:
8636 machineWhite = FALSE;
8639 case TwoMachinesPlay:
8640 machineWhite = (cps->twoMachinesColor[0] == 'w');
8643 if (WhiteOnMove(forwardMostMove) != machineWhite) {
8644 if (appData.debugMode) {
8646 "Ignoring move out of turn by %s, gameMode %d"
8647 ", forwardMost %d\n",
8648 cps->which, gameMode, forwardMostMove);
8653 if(cps->alphaRank) AlphaRank(machineMove, 4);
8655 // [HGM] lion: (some very limited) support for Alien protocol
8657 if(machineMove[strlen(machineMove)-1] == ',') { // move ends in coma: non-final leg of composite move
8658 safeStrCpy(firstLeg, machineMove, 20); // just remember it for processing when second leg arrives
8660 } else if(firstLeg[0]) { // there was a previous leg;
8661 // only support case where same piece makes two step (and don't even test that!)
8662 char buf[20], *p = machineMove+1, *q = buf+1, f;
8663 safeStrCpy(buf, machineMove, 20);
8664 while(isdigit(*q)) q++; // find start of to-square
8665 safeStrCpy(machineMove, firstLeg, 20);
8666 while(isdigit(*p)) p++;
8667 safeStrCpy(p, q, 20); // glue to-square of second leg to from-square of first, to process over-all move
8668 sscanf(buf, "%c%d", &f, &killY); killX = f - AAA; killY -= ONE - '0'; // pass intermediate square to MakeMove in global
8669 firstLeg[0] = NULLCHAR;
8672 if (!ParseOneMove(machineMove, forwardMostMove, &moveType,
8673 &fromX, &fromY, &toX, &toY, &promoChar)) {
8674 /* Machine move could not be parsed; ignore it. */
8675 snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"),
8676 machineMove, _(cps->which));
8677 DisplayMoveError(buf1);
8678 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c via %c%c) res=%d",
8679 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, killX+AAA, killY+ONE, moveType);
8680 if (gameMode == TwoMachinesPlay) {
8681 GameEnds(machineWhite ? BlackWins : WhiteWins,
8687 /* [HGM] Apparently legal, but so far only tested with EP_UNKOWN */
8688 /* So we have to redo legality test with true e.p. status here, */
8689 /* to make sure an illegal e.p. capture does not slip through, */
8690 /* to cause a forfeit on a justified illegal-move complaint */
8691 /* of the opponent. */
8692 if( gameMode==TwoMachinesPlay && appData.testLegality ) {
8694 moveType = LegalityTest(boards[forwardMostMove], PosFlags(forwardMostMove),
8695 fromY, fromX, toY, toX, promoChar);
8696 if(moveType == IllegalMove) {
8697 snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c",
8698 machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0);
8699 GameEnds(machineWhite ? BlackWins : WhiteWins,
8702 } else if(!appData.fischerCastling)
8703 /* [HGM] Kludge to handle engines that send FRC-style castling
8704 when they shouldn't (like TSCP-Gothic) */
8706 case WhiteASideCastleFR:
8707 case BlackASideCastleFR:
8709 currentMoveString[2]++;
8711 case WhiteHSideCastleFR:
8712 case BlackHSideCastleFR:
8714 currentMoveString[2]--;
8716 default: ; // nothing to do, but suppresses warning of pedantic compilers
8719 hintRequested = FALSE;
8720 lastHint[0] = NULLCHAR;
8721 bookRequested = FALSE;
8722 /* Program may be pondering now */
8723 cps->maybeThinking = TRUE;
8724 if (cps->sendTime == 2) cps->sendTime = 1;
8725 if (cps->offeredDraw) cps->offeredDraw--;
8727 /* [AS] Save move info*/
8728 pvInfoList[ forwardMostMove ].score = programStats.score;
8729 pvInfoList[ forwardMostMove ].depth = programStats.depth;
8730 pvInfoList[ forwardMostMove ].time = programStats.time; // [HGM] PGNtime: take time from engine stats
8732 MakeMove(fromX, fromY, toX, toY, promoChar);/*updates forwardMostMove*/
8734 /* Test suites abort the 'game' after one move */
8735 if(*appData.finger) {
8737 char *fen = PositionToFEN(backwardMostMove, NULL, 0); // no counts in EPD
8738 if(!f) f = fopen(appData.finger, "w");
8739 if(f) fprintf(f, "%s bm %s;\n", fen, parseList[backwardMostMove]), fflush(f);
8740 else { DisplayFatalError("Bad output file", errno, 0); return; }
8742 GameEnds(GameUnfinished, NULL, GE_XBOARD);
8745 /* [AS] Adjudicate game if needed (note: remember that forwardMostMove now points past the last move) */
8746 if( gameMode == TwoMachinesPlay && appData.adjudicateLossThreshold != 0 && forwardMostMove >= adjudicateLossPlies ) {
8749 while( count < adjudicateLossPlies ) {
8750 int score = pvInfoList[ forwardMostMove - count - 1 ].score;
8753 score = -score; /* Flip score for winning side */
8756 if( score > appData.adjudicateLossThreshold ) {
8763 if( count >= adjudicateLossPlies ) {
8764 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8766 GameEnds( WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins,
8767 "Xboard adjudication",
8774 if(Adjudicate(cps)) {
8775 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8776 return; // [HGM] adjudicate: for all automatic game ends
8780 if ((gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack) &&
8782 if(cps->offeredDraw && (signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
8783 SendToICS(ics_prefix); // [HGM] drawclaim: send caim and move on one line for FICS
8785 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8787 SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar);
8789 if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */
8790 char buf[3*MSG_SIZ];
8792 snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n",
8793 programStats.score / 100.,
8795 programStats.time / 100.,
8796 (unsigned int)programStats.nodes,
8797 (unsigned int)programStats.nodes / (10*abs(programStats.time) + 1.),
8798 programStats.movelist);
8804 /* [AS] Clear stats for next move */
8805 ClearProgramStats();
8806 thinkOutput[0] = NULLCHAR;
8807 hiddenThinkOutputState = 0;
8810 if (gameMode == TwoMachinesPlay) {
8811 /* [HGM] relaying draw offers moved to after reception of move */
8812 /* and interpreting offer as claim if it brings draw condition */
8813 if (cps->offeredDraw == 1 && cps->other->sendDrawOffers) {
8814 SendToProgram("draw\n", cps->other);
8816 if (cps->other->sendTime) {
8817 SendTimeRemaining(cps->other,
8818 cps->other->twoMachinesColor[0] == 'w');
8820 bookHit = SendMoveToBookUser(forwardMostMove-1, cps->other, FALSE);
8821 if (firstMove && !bookHit) {
8823 if (cps->other->useColors) {
8824 SendToProgram(cps->other->twoMachinesColor, cps->other);
8826 SendToProgram("go\n", cps->other);
8828 cps->other->maybeThinking = TRUE;
8831 roar = (killX >= 0 && IS_LION(boards[forwardMostMove][toY][toX]));
8833 ShowMove(fromX, fromY, toX, toY); /*updates currentMove*/
8835 if (!pausing && appData.ringBellAfterMoves) {
8836 if(!roar) RingBell();
8840 * Reenable menu items that were disabled while
8841 * machine was thinking
8843 if (gameMode != TwoMachinesPlay)
8844 SetUserThinkingEnables();
8846 // [HGM] book: after book hit opponent has received move and is now in force mode
8847 // force the book reply into it, and then fake that it outputted this move by jumping
8848 // back to the beginning of HandleMachineMove, with cps toggled and message set to this move
8850 static char bookMove[MSG_SIZ]; // a bit generous?
8852 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
8853 strcat(bookMove, bookHit);
8856 programStats.nodes = programStats.depth = programStats.time =
8857 programStats.score = programStats.got_only_move = 0;
8858 sprintf(programStats.movelist, "%s (xbook)", bookHit);
8860 if(cps->lastPing != cps->lastPong) {
8861 savedMessage = message; // args for deferred call
8863 ScheduleDelayedEvent(DeferredBookMove, 10);
8872 /* Set special modes for chess engines. Later something general
8873 * could be added here; for now there is just one kludge feature,
8874 * needed because Crafty 15.10 and earlier don't ignore SIGINT
8875 * when "xboard" is given as an interactive command.
8877 if (strncmp(message, "kibitz Hello from Crafty", 24) == 0) {
8878 cps->useSigint = FALSE;
8879 cps->useSigterm = FALSE;
8881 if (strncmp(message, "feature ", 8) == 0) { // [HGM] moved forward to pre-empt non-compliant commands
8882 ParseFeatures(message+8, cps);
8883 return; // [HGM] This return was missing, causing option features to be recognized as non-compliant commands!
8886 if (!strncmp(message, "setup ", 6) &&
8887 (!appData.testLegality || gameInfo.variant == VariantFairy || gameInfo.variant == VariantUnknown ||
8888 NonStandardBoardSize(gameInfo.variant, gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize))
8889 ) { // [HGM] allow first engine to define opening position
8890 int dummy, w, h, hand, s=6; char buf[MSG_SIZ], varName[MSG_SIZ];
8891 if(appData.icsActive || forwardMostMove != 0 || cps != &first) return;
8893 if(sscanf(message, "setup (%s", buf) == 1) {
8894 s = 8 + strlen(buf), buf[s-9] = NULLCHAR, SetCharTable(pieceToChar, buf);
8895 ASSIGN(appData.pieceToCharTable, buf);
8897 dummy = sscanf(message+s, "%dx%d+%d_%s", &w, &h, &hand, varName);
8899 while(message[s] && message[s++] != ' ');
8900 if(BOARD_HEIGHT != h || BOARD_WIDTH != w + 4*(hand != 0) || gameInfo.holdingsSize != hand ||
8901 dummy == 4 && gameInfo.variant != StringToVariant(varName) ) { // engine wants to change board format or variant
8902 appData.NrFiles = w; appData.NrRanks = h; appData.holdingsSize = hand;
8903 if(dummy == 4) gameInfo.variant = StringToVariant(varName); // parent variant
8904 InitPosition(1); // calls InitDrawingSizes to let new parameters take effect
8905 if(*buf) SetCharTable(pieceToChar, buf); // do again, for it was spoiled by InitPosition
8906 startedFromSetupPosition = FALSE;
8909 if(startedFromSetupPosition) return;
8910 ParseFEN(boards[0], &dummy, message+s, FALSE);
8911 DrawPosition(TRUE, boards[0]);
8912 CopyBoard(initialPosition, boards[0]);
8913 startedFromSetupPosition = TRUE;
8916 if(sscanf(message, "piece %s %s", buf2, buf1) == 2) {
8917 ChessSquare piece = WhitePawn;
8919 if(*p == '+') piece = CHUPROMOTED WhitePawn, p++;
8920 piece += CharToPiece(*p) - WhitePawn;
8921 if(cps != &first || appData.testLegality && *engineVariant == NULLCHAR
8922 /* always accept definition of */ && piece != WhiteFalcon && piece != BlackFalcon
8923 /* wild-card pieces. */ && piece != WhiteCobra && piece != BlackCobra
8924 /* For variants we don't have */ && gameInfo.variant != VariantBerolina
8925 /* correct rules for, we cannot */ && gameInfo.variant != VariantCylinder
8926 /* enforce legality on our own! */ && gameInfo.variant != VariantUnknown
8927 && gameInfo.variant != VariantGreat
8928 && gameInfo.variant != VariantFairy ) return;
8929 if(piece < EmptySquare) {
8931 ASSIGN(pieceDesc[piece], buf1);
8932 if(isupper(*p) && p[1] == '&') { ASSIGN(pieceDesc[WHITE_TO_BLACK piece], buf1); }
8936 /* [HGM] Allow engine to set up a position. Don't ask me why one would
8937 * want this, I was asked to put it in, and obliged.
8939 if (!strncmp(message, "setboard ", 9)) {
8940 Board initial_position;
8942 GameEnds(GameUnfinished, "Engine aborts game", GE_XBOARD);
8944 if (!ParseFEN(initial_position, &blackPlaysFirst, message + 9, FALSE)) {
8945 DisplayError(_("Bad FEN received from engine"), 0);
8949 CopyBoard(boards[0], initial_position);
8950 initialRulePlies = FENrulePlies;
8951 if(blackPlaysFirst) gameMode = MachinePlaysWhite;
8952 else gameMode = MachinePlaysBlack;
8953 DrawPosition(FALSE, boards[currentMove]);
8959 * Look for communication commands
8961 if (!strncmp(message, "telluser ", 9)) {
8962 if(message[9] == '\\' && message[10] == '\\')
8963 EscapeExpand(message+9, message+11); // [HGM] esc: allow escape sequences in popup box
8965 DisplayNote(message + 9);
8968 if (!strncmp(message, "tellusererror ", 14)) {
8970 if(message[14] == '\\' && message[15] == '\\')
8971 EscapeExpand(message+14, message+16); // [HGM] esc: allow escape sequences in popup box
8973 DisplayError(message + 14, 0);
8976 if (!strncmp(message, "tellopponent ", 13)) {
8977 if (appData.icsActive) {
8979 snprintf(buf1, sizeof(buf1), "%ssay %s\n", ics_prefix, message + 13);
8983 DisplayNote(message + 13);
8987 if (!strncmp(message, "tellothers ", 11)) {
8988 if (appData.icsActive) {
8990 snprintf(buf1, sizeof(buf1), "%swhisper %s\n", ics_prefix, message + 11);
8993 } else if(appData.autoComment) AppendComment (forwardMostMove, message + 11, 1); // in local mode, add as move comment
8996 if (!strncmp(message, "tellall ", 8)) {
8997 if (appData.icsActive) {
8999 snprintf(buf1, sizeof(buf1), "%skibitz %s\n", ics_prefix, message + 8);
9003 DisplayNote(message + 8);
9007 if (strncmp(message, "warning", 7) == 0) {
9008 /* Undocumented feature, use tellusererror in new code */
9009 DisplayError(message, 0);
9012 if (sscanf(message, "askuser %s %[^\n]", buf1, buf2) == 2) {
9013 safeStrCpy(realname, cps->tidy, sizeof(realname)/sizeof(realname[0]));
9014 strcat(realname, " query");
9015 AskQuestion(realname, buf2, buf1, cps->pr);
9018 /* Commands from the engine directly to ICS. We don't allow these to be
9019 * sent until we are logged on. Crafty kibitzes have been known to
9020 * interfere with the login process.
9023 if (!strncmp(message, "tellics ", 8)) {
9024 SendToICS(message + 8);
9028 if (!strncmp(message, "tellicsnoalias ", 15)) {
9029 SendToICS(ics_prefix);
9030 SendToICS(message + 15);
9034 /* The following are for backward compatibility only */
9035 if (!strncmp(message,"whisper",7) || !strncmp(message,"kibitz",6) ||
9036 !strncmp(message,"draw",4) || !strncmp(message,"tell",3)) {
9037 SendToICS(ics_prefix);
9043 if (sscanf(message, "pong %d", &cps->lastPong) == 1) {
9044 if(initPing == cps->lastPong) {
9045 if(gameInfo.variant == VariantUnknown) {
9046 DisplayError(_("Engine did not send setup for non-standard variant"), 0);
9047 *engineVariant = NULLCHAR; appData.variant = VariantNormal; // back to normal as error recovery?
9048 GameEnds(GameUnfinished, NULL, GE_XBOARD);
9054 if(!strncmp(message, "highlight ", 10)) {
9055 if(appData.testLegality && appData.markers) return;
9056 MarkByFEN(message+10); // [HGM] alien: allow engine to mark board squares
9059 if(!strncmp(message, "click ", 6)) {
9060 char f, c=0; int x, y; // [HGM] alien: allow engine to finish user moves (i.e. engine-driven one-click moving)
9061 if(appData.testLegality || !appData.oneClick) return;
9062 sscanf(message+6, "%c%d%c", &f, &y, &c);
9063 x = f - 'a' + BOARD_LEFT, y -= ONE - '0';
9064 if(flipView) x = BOARD_WIDTH-1 - x; else y = BOARD_HEIGHT-1 - y;
9065 x = x*squareSize + (x+1)*lineGap + squareSize/2;
9066 y = y*squareSize + (y+1)*lineGap + squareSize/2;
9067 f = first.highlight; first.highlight = 0; // kludge to suppress lift/put in response to own clicks
9068 if(lastClickType == Press) // if button still down, fake release on same square, to be ready for next click
9069 LeftClick(Release, lastLeftX, lastLeftY);
9070 controlKey = (c == ',');
9071 LeftClick(Press, x, y);
9072 LeftClick(Release, x, y);
9073 first.highlight = f;
9077 * If the move is illegal, cancel it and redraw the board.
9078 * Also deal with other error cases. Matching is rather loose
9079 * here to accommodate engines written before the spec.
9081 if (strncmp(message + 1, "llegal move", 11) == 0 ||
9082 strncmp(message, "Error", 5) == 0) {
9083 if (StrStr(message, "name") ||
9084 StrStr(message, "rating") || StrStr(message, "?") ||
9085 StrStr(message, "result") || StrStr(message, "board") ||
9086 StrStr(message, "bk") || StrStr(message, "computer") ||
9087 StrStr(message, "variant") || StrStr(message, "hint") ||
9088 StrStr(message, "random") || StrStr(message, "depth") ||
9089 StrStr(message, "accepted")) {
9092 if (StrStr(message, "protover")) {
9093 /* Program is responding to input, so it's apparently done
9094 initializing, and this error message indicates it is
9095 protocol version 1. So we don't need to wait any longer
9096 for it to initialize and send feature commands. */
9097 FeatureDone(cps, 1);
9098 cps->protocolVersion = 1;
9101 cps->maybeThinking = FALSE;
9103 if (StrStr(message, "draw")) {
9104 /* Program doesn't have "draw" command */
9105 cps->sendDrawOffers = 0;
9108 if (cps->sendTime != 1 &&
9109 (StrStr(message, "time") || StrStr(message, "otim"))) {
9110 /* Program apparently doesn't have "time" or "otim" command */
9114 if (StrStr(message, "analyze")) {
9115 cps->analysisSupport = FALSE;
9116 cps->analyzing = FALSE;
9117 // Reset(FALSE, TRUE); // [HGM] this caused discrepancy between display and internal state!
9118 EditGameEvent(); // [HGM] try to preserve loaded game
9119 snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy);
9120 DisplayError(buf2, 0);
9123 if (StrStr(message, "(no matching move)st")) {
9124 /* Special kludge for GNU Chess 4 only */
9125 cps->stKludge = TRUE;
9126 SendTimeControl(cps, movesPerSession, timeControl,
9127 timeIncrement, appData.searchDepth,
9131 if (StrStr(message, "(no matching move)sd")) {
9132 /* Special kludge for GNU Chess 4 only */
9133 cps->sdKludge = TRUE;
9134 SendTimeControl(cps, movesPerSession, timeControl,
9135 timeIncrement, appData.searchDepth,
9139 if (!StrStr(message, "llegal")) {
9142 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
9143 gameMode == IcsIdle) return;
9144 if (forwardMostMove <= backwardMostMove) return;
9145 if (pausing) PauseEvent();
9146 if(appData.forceIllegal) {
9147 // [HGM] illegal: machine refused move; force position after move into it
9148 SendToProgram("force\n", cps);
9149 if(!cps->useSetboard) { // hideous kludge on kludge, because SendBoard sucks.
9150 // we have a real problem now, as SendBoard will use the a2a3 kludge
9151 // when black is to move, while there might be nothing on a2 or black
9152 // might already have the move. So send the board as if white has the move.
9153 // But first we must change the stm of the engine, as it refused the last move
9154 SendBoard(cps, 0); // always kludgeless, as white is to move on boards[0]
9155 if(WhiteOnMove(forwardMostMove)) {
9156 SendToProgram("a7a6\n", cps); // for the engine black still had the move
9157 SendBoard(cps, forwardMostMove); // kludgeless board
9159 SendToProgram("a2a3\n", cps); // for the engine white still had the move
9160 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
9161 SendBoard(cps, forwardMostMove+1); // kludgeless board
9163 } else SendBoard(cps, forwardMostMove); // FEN case, also sets stm properly
9164 if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
9165 gameMode == TwoMachinesPlay)
9166 SendToProgram("go\n", cps);
9169 if (gameMode == PlayFromGameFile) {
9170 /* Stop reading this game file */
9171 gameMode = EditGame;
9174 /* [HGM] illegal-move claim should forfeit game when Xboard */
9175 /* only passes fully legal moves */
9176 if( appData.testLegality && gameMode == TwoMachinesPlay ) {
9177 GameEnds( cps->twoMachinesColor[0] == 'w' ? BlackWins : WhiteWins,
9178 "False illegal-move claim", GE_XBOARD );
9179 return; // do not take back move we tested as valid
9181 currentMove = forwardMostMove-1;
9182 DisplayMove(currentMove-1); /* before DisplayMoveError */
9183 SwitchClocks(forwardMostMove-1); // [HGM] race
9184 DisplayBothClocks();
9185 snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"),
9186 parseList[currentMove], _(cps->which));
9187 DisplayMoveError(buf1);
9188 DrawPosition(FALSE, boards[currentMove]);
9190 SetUserThinkingEnables();
9193 if (strncmp(message, "time", 4) == 0 && StrStr(message, "Illegal")) {
9194 /* Program has a broken "time" command that
9195 outputs a string not ending in newline.
9199 if (cps->pseudo) { // [HGM] pseudo-engine, granted unusual powers
9200 if (sscanf(message, "wtime %ld\n", &whiteTimeRemaining) == 1 || // adjust clock times
9201 sscanf(message, "btime %ld\n", &blackTimeRemaining) == 1 ) return;
9205 * If chess program startup fails, exit with an error message.
9206 * Attempts to recover here are futile. [HGM] Well, we try anyway
9208 if ((StrStr(message, "unknown host") != NULL)
9209 || (StrStr(message, "No remote directory") != NULL)
9210 || (StrStr(message, "not found") != NULL)
9211 || (StrStr(message, "No such file") != NULL)
9212 || (StrStr(message, "can't alloc") != NULL)
9213 || (StrStr(message, "Permission denied") != NULL)) {
9215 cps->maybeThinking = FALSE;
9216 snprintf(buf1, sizeof(buf1), _("Failed to start %s chess program %s on %s: %s\n"),
9217 _(cps->which), cps->program, cps->host, message);
9218 RemoveInputSource(cps->isr);
9219 if(appData.icsActive) DisplayFatalError(buf1, 0, 1); else {
9220 if(LoadError(oldError ? NULL : buf1, cps)) return; // error has then been handled by LoadError
9221 if(!oldError) DisplayError(buf1, 0); // if reason neatly announced, suppress general error popup
9227 * Look for hint output
9229 if (sscanf(message, "Hint: %s", buf1) == 1) {
9230 if (cps == &first && hintRequested) {
9231 hintRequested = FALSE;
9232 if (ParseOneMove(buf1, forwardMostMove, &moveType,
9233 &fromX, &fromY, &toX, &toY, &promoChar)) {
9234 (void) CoordsToAlgebraic(boards[forwardMostMove],
9235 PosFlags(forwardMostMove),
9236 fromY, fromX, toY, toX, promoChar, buf1);
9237 snprintf(buf2, sizeof(buf2), _("Hint: %s"), buf1);
9238 DisplayInformation(buf2);
9240 /* Hint move could not be parsed!? */
9241 snprintf(buf2, sizeof(buf2),
9242 _("Illegal hint move \"%s\"\nfrom %s chess program"),
9243 buf1, _(cps->which));
9244 DisplayError(buf2, 0);
9247 safeStrCpy(lastHint, buf1, sizeof(lastHint)/sizeof(lastHint[0]));
9253 * Ignore other messages if game is not in progress
9255 if (gameMode == BeginningOfGame || gameMode == EndOfGame ||
9256 gameMode == IcsIdle || cps->lastPing != cps->lastPong) return;
9259 * look for win, lose, draw, or draw offer
9261 if (strncmp(message, "1-0", 3) == 0) {
9262 char *p, *q, *r = "";
9263 p = strchr(message, '{');
9271 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first)); /* [HGM] pass claimer indication for claim test */
9273 } else if (strncmp(message, "0-1", 3) == 0) {
9274 char *p, *q, *r = "";
9275 p = strchr(message, '{');
9283 /* Kludge for Arasan 4.1 bug */
9284 if (strcmp(r, "Black resigns") == 0) {
9285 GameEnds(WhiteWins, r, GE_ENGINE1 + (cps != &first));
9288 GameEnds(BlackWins, r, GE_ENGINE1 + (cps != &first));
9290 } else if (strncmp(message, "1/2", 3) == 0) {
9291 char *p, *q, *r = "";
9292 p = strchr(message, '{');
9301 GameEnds(GameIsDrawn, r, GE_ENGINE1 + (cps != &first));
9304 } else if (strncmp(message, "White resign", 12) == 0) {
9305 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
9307 } else if (strncmp(message, "Black resign", 12) == 0) {
9308 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
9310 } else if (strncmp(message, "White matches", 13) == 0 ||
9311 strncmp(message, "Black matches", 13) == 0 ) {
9312 /* [HGM] ignore GNUShogi noises */
9314 } else if (strncmp(message, "White", 5) == 0 &&
9315 message[5] != '(' &&
9316 StrStr(message, "Black") == NULL) {
9317 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9319 } else if (strncmp(message, "Black", 5) == 0 &&
9320 message[5] != '(') {
9321 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9323 } else if (strcmp(message, "resign") == 0 ||
9324 strcmp(message, "computer resigns") == 0) {
9326 case MachinePlaysBlack:
9327 case IcsPlayingBlack:
9328 GameEnds(WhiteWins, "Black resigns", GE_ENGINE);
9330 case MachinePlaysWhite:
9331 case IcsPlayingWhite:
9332 GameEnds(BlackWins, "White resigns", GE_ENGINE);
9334 case TwoMachinesPlay:
9335 if (cps->twoMachinesColor[0] == 'w')
9336 GameEnds(BlackWins, "White resigns", GE_ENGINE1 + (cps != &first));
9338 GameEnds(WhiteWins, "Black resigns", GE_ENGINE1 + (cps != &first));
9345 } else if (strncmp(message, "opponent mates", 14) == 0) {
9347 case MachinePlaysBlack:
9348 case IcsPlayingBlack:
9349 GameEnds(WhiteWins, "White mates", GE_ENGINE);
9351 case MachinePlaysWhite:
9352 case IcsPlayingWhite:
9353 GameEnds(BlackWins, "Black mates", GE_ENGINE);
9355 case TwoMachinesPlay:
9356 if (cps->twoMachinesColor[0] == 'w')
9357 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9359 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9366 } else if (strncmp(message, "computer mates", 14) == 0) {
9368 case MachinePlaysBlack:
9369 case IcsPlayingBlack:
9370 GameEnds(BlackWins, "Black mates", GE_ENGINE1);
9372 case MachinePlaysWhite:
9373 case IcsPlayingWhite:
9374 GameEnds(WhiteWins, "White mates", GE_ENGINE);
9376 case TwoMachinesPlay:
9377 if (cps->twoMachinesColor[0] == 'w')
9378 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9380 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9387 } else if (strncmp(message, "checkmate", 9) == 0) {
9388 if (WhiteOnMove(forwardMostMove)) {
9389 GameEnds(BlackWins, "Black mates", GE_ENGINE1 + (cps != &first));
9391 GameEnds(WhiteWins, "White mates", GE_ENGINE1 + (cps != &first));
9394 } else if (strstr(message, "Draw") != NULL ||
9395 strstr(message, "game is a draw") != NULL) {
9396 GameEnds(GameIsDrawn, "Draw", GE_ENGINE1 + (cps != &first));
9398 } else if (strstr(message, "offer") != NULL &&
9399 strstr(message, "draw") != NULL) {
9401 if (appData.zippyPlay && first.initDone) {
9402 /* Relay offer to ICS */
9403 SendToICS(ics_prefix);
9404 SendToICS("draw\n");
9407 cps->offeredDraw = 2; /* valid until this engine moves twice */
9408 if (gameMode == TwoMachinesPlay) {
9409 if (cps->other->offeredDraw) {
9410 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
9411 /* [HGM] in two-machine mode we delay relaying draw offer */
9412 /* until after we also have move, to see if it is really claim */
9414 } else if (gameMode == MachinePlaysWhite ||
9415 gameMode == MachinePlaysBlack) {
9416 if (userOfferedDraw) {
9417 DisplayInformation(_("Machine accepts your draw offer"));
9418 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
9420 DisplayInformation(_("Machine offers a draw.\nSelect Action / Draw to accept."));
9427 * Look for thinking output
9429 if ( appData.showThinking // [HGM] thinking: test all options that cause this output
9430 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
9432 int plylev, mvleft, mvtot, curscore, time;
9433 char mvname[MOVE_LEN];
9437 int prefixHint = FALSE;
9438 mvname[0] = NULLCHAR;
9441 case MachinePlaysBlack:
9442 case IcsPlayingBlack:
9443 if (WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
9445 case MachinePlaysWhite:
9446 case IcsPlayingWhite:
9447 if (!WhiteOnMove(forwardMostMove)) prefixHint = TRUE;
9452 case IcsObserving: /* [DM] icsEngineAnalyze */
9453 if (!appData.icsEngineAnalyze) ignore = TRUE;
9455 case TwoMachinesPlay:
9456 if ((cps->twoMachinesColor[0] == 'w') != WhiteOnMove(forwardMostMove)) {
9466 ChessProgramStats tempStats = programStats; // [HGM] info: filter out info lines
9468 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
9469 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5) {
9471 if(nodes>>32 == u64Const(0xFFFFFFFF)) // [HGM] negative node count read
9472 nodes += u64Const(0x100000000);
9474 if (plyext != ' ' && plyext != '\t') {
9478 /* [AS] Negate score if machine is playing black and reporting absolute scores */
9479 if( cps->scoreIsAbsolute &&
9480 ( gameMode == MachinePlaysBlack ||
9481 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b' ||
9482 gameMode == IcsPlayingBlack || // [HGM] also add other situations where engine should report black POV
9483 (gameMode == AnalyzeMode || gameMode == AnalyzeFile || gameMode == IcsObserving && appData.icsEngineAnalyze) &&
9484 !WhiteOnMove(currentMove)
9487 curscore = -curscore;
9490 if(appData.pvSAN[cps==&second]) pv = PvToSAN(buf1);
9492 if(serverMoves && (time > 100 || time == 0 && plylev > 7)) {
9495 snprintf(buf, MSG_SIZ, "%s", appData.serverMovesName);
9496 buf[strlen(buf)-1] = gameMode == MachinePlaysWhite ? 'w' :
9497 gameMode == MachinePlaysBlack ? 'b' : cps->twoMachinesColor[0];
9498 if(appData.debugMode) fprintf(debugFP, "write PV on file '%s'\n", buf);
9499 if(f = fopen(buf, "w")) { // export PV to applicable PV file
9500 fprintf(f, "%5.2f/%-2d %s", curscore/100., plylev, pv);
9504 /* TRANSLATORS: PV = principal variation, the variation the chess engine thinks is the best for everyone */
9505 DisplayError(_("failed writing PV"), 0);
9508 tempStats.depth = plylev;
9509 tempStats.nodes = nodes;
9510 tempStats.time = time;
9511 tempStats.score = curscore;
9512 tempStats.got_only_move = 0;
9514 if(cps->nps >= 0) { /* [HGM] nps: use engine nodes or time to decrement clock */
9517 if(cps->nps == 0) ticklen = 10*time; // use engine reported time
9518 else ticklen = (1000. * u64ToDouble(nodes)) / cps->nps; // convert node count to time
9519 if(WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysWhite ||
9520 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'w'))
9521 whiteTimeRemaining = timeRemaining[0][forwardMostMove] - ticklen;
9522 if(!WhiteOnMove(forwardMostMove) && (gameMode == MachinePlaysBlack ||
9523 gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b'))
9524 blackTimeRemaining = timeRemaining[1][forwardMostMove] - ticklen;
9527 /* Buffer overflow protection */
9528 if (pv[0] != NULLCHAR) {
9529 if (strlen(pv) >= sizeof(tempStats.movelist)
9530 && appData.debugMode) {
9532 "PV is too long; using the first %u bytes.\n",
9533 (unsigned) sizeof(tempStats.movelist) - 1);
9536 safeStrCpy( tempStats.movelist, pv, sizeof(tempStats.movelist)/sizeof(tempStats.movelist[0]) );
9538 sprintf(tempStats.movelist, " no PV\n");
9541 if (tempStats.seen_stat) {
9542 tempStats.ok_to_send = 1;
9545 if (strchr(tempStats.movelist, '(') != NULL) {
9546 tempStats.line_is_book = 1;
9547 tempStats.nr_moves = 0;
9548 tempStats.moves_left = 0;
9550 tempStats.line_is_book = 0;
9553 if(tempStats.score != 0 || tempStats.nodes != 0 || tempStats.time != 0)
9554 programStats = tempStats; // [HGM] info: only set stats if genuine PV and not an info line
9556 SendProgramStatsToFrontend( cps, &tempStats );
9559 [AS] Protect the thinkOutput buffer from overflow... this
9560 is only useful if buf1 hasn't overflowed first!
9562 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s",
9564 (gameMode == TwoMachinesPlay ?
9565 ToUpper(cps->twoMachinesColor[0]) : ' '),
9566 ((double) curscore) / 100.0,
9567 prefixHint ? lastHint : "",
9568 prefixHint ? " " : "" );
9570 if( buf1[0] != NULLCHAR ) {
9571 unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1;
9573 if( strlen(pv) > max_len ) {
9574 if( appData.debugMode) {
9575 fprintf(debugFP,"PV is too long for thinkOutput, truncating.\n");
9577 pv[max_len+1] = '\0';
9580 strcat( thinkOutput, pv);
9583 if (currentMove == forwardMostMove || gameMode == AnalyzeMode
9584 || gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
9585 DisplayMove(currentMove - 1);
9589 } else if ((p=StrStr(message, "(only move)")) != NULL) {
9590 /* crafty (9.25+) says "(only move) <move>"
9591 * if there is only 1 legal move
9593 sscanf(p, "(only move) %s", buf1);
9594 snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1);
9595 sprintf(programStats.movelist, "%s (only move)", buf1);
9596 programStats.depth = 1;
9597 programStats.nr_moves = 1;
9598 programStats.moves_left = 1;
9599 programStats.nodes = 1;
9600 programStats.time = 1;
9601 programStats.got_only_move = 1;
9603 /* Not really, but we also use this member to
9604 mean "line isn't going to change" (Crafty
9605 isn't searching, so stats won't change) */
9606 programStats.line_is_book = 1;
9608 SendProgramStatsToFrontend( cps, &programStats );
9610 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
9611 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
9612 DisplayMove(currentMove - 1);
9615 } else if (sscanf(message,"stat01: %d " u64Display " %d %d %d %s",
9616 &time, &nodes, &plylev, &mvleft,
9617 &mvtot, mvname) >= 5) {
9618 /* The stat01: line is from Crafty (9.29+) in response
9619 to the "." command */
9620 programStats.seen_stat = 1;
9621 cps->maybeThinking = TRUE;
9623 if (programStats.got_only_move || !appData.periodicUpdates)
9626 programStats.depth = plylev;
9627 programStats.time = time;
9628 programStats.nodes = nodes;
9629 programStats.moves_left = mvleft;
9630 programStats.nr_moves = mvtot;
9631 safeStrCpy(programStats.move_name, mvname, sizeof(programStats.move_name)/sizeof(programStats.move_name[0]));
9632 programStats.ok_to_send = 1;
9633 programStats.movelist[0] = '\0';
9635 SendProgramStatsToFrontend( cps, &programStats );
9639 } else if (strncmp(message,"++",2) == 0) {
9640 /* Crafty 9.29+ outputs this */
9641 programStats.got_fail = 2;
9644 } else if (strncmp(message,"--",2) == 0) {
9645 /* Crafty 9.29+ outputs this */
9646 programStats.got_fail = 1;
9649 } else if (thinkOutput[0] != NULLCHAR &&
9650 strncmp(message, " ", 4) == 0) {
9651 unsigned message_len;
9654 while (*p && *p == ' ') p++;
9656 message_len = strlen( p );
9658 /* [AS] Avoid buffer overflow */
9659 if( sizeof(thinkOutput) - strlen(thinkOutput) - 1 > message_len ) {
9660 strcat(thinkOutput, " ");
9661 strcat(thinkOutput, p);
9664 if( sizeof(programStats.movelist) - strlen(programStats.movelist) - 1 > message_len ) {
9665 strcat(programStats.movelist, " ");
9666 strcat(programStats.movelist, p);
9669 if (currentMove == forwardMostMove || gameMode==AnalyzeMode ||
9670 gameMode == AnalyzeFile || appData.icsEngineAnalyze) {
9671 DisplayMove(currentMove - 1);
9679 if (sscanf(message, "%d%c %d %d " u64Display " %[^\n]\n",
9680 &plylev, &plyext, &curscore, &time, &nodes, buf1) >= 5)
9682 ChessProgramStats cpstats;
9684 if (plyext != ' ' && plyext != '\t') {
9688 /* [AS] Negate score if machine is playing black and reporting absolute scores */
9689 if( cps->scoreIsAbsolute && ((gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b')) ) {
9690 curscore = -curscore;
9693 cpstats.depth = plylev;
9694 cpstats.nodes = nodes;
9695 cpstats.time = time;
9696 cpstats.score = curscore;
9697 cpstats.got_only_move = 0;
9698 cpstats.movelist[0] = '\0';
9700 if (buf1[0] != NULLCHAR) {
9701 safeStrCpy( cpstats.movelist, buf1, sizeof(cpstats.movelist)/sizeof(cpstats.movelist[0]) );
9704 cpstats.ok_to_send = 0;
9705 cpstats.line_is_book = 0;
9706 cpstats.nr_moves = 0;
9707 cpstats.moves_left = 0;
9709 SendProgramStatsToFrontend( cps, &cpstats );
9716 /* Parse a game score from the character string "game", and
9717 record it as the history of the current game. The game
9718 score is NOT assumed to start from the standard position.
9719 The display is not updated in any way.
9722 ParseGameHistory (char *game)
9725 int fromX, fromY, toX, toY, boardIndex;
9730 if (appData.debugMode)
9731 fprintf(debugFP, "Parsing game history: %s\n", game);
9733 if (gameInfo.event == NULL) gameInfo.event = StrSave("ICS game");
9734 gameInfo.site = StrSave(appData.icsHost);
9735 gameInfo.date = PGNDate();
9736 gameInfo.round = StrSave("-");
9738 /* Parse out names of players */
9739 while (*game == ' ') game++;
9741 while (*game != ' ') *p++ = *game++;
9743 gameInfo.white = StrSave(buf);
9744 while (*game == ' ') game++;
9746 while (*game != ' ' && *game != '\n') *p++ = *game++;
9748 gameInfo.black = StrSave(buf);
9751 boardIndex = blackPlaysFirst ? 1 : 0;
9754 yyboardindex = boardIndex;
9755 moveType = (ChessMove) Myylex();
9757 case IllegalMove: /* maybe suicide chess, etc. */
9758 if (appData.debugMode) {
9759 fprintf(debugFP, "Illegal move from ICS: '%s'\n", yy_text);
9760 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9761 setbuf(debugFP, NULL);
9763 case WhitePromotion:
9764 case BlackPromotion:
9765 case WhiteNonPromotion:
9766 case BlackNonPromotion:
9769 case WhiteCapturesEnPassant:
9770 case BlackCapturesEnPassant:
9771 case WhiteKingSideCastle:
9772 case WhiteQueenSideCastle:
9773 case BlackKingSideCastle:
9774 case BlackQueenSideCastle:
9775 case WhiteKingSideCastleWild:
9776 case WhiteQueenSideCastleWild:
9777 case BlackKingSideCastleWild:
9778 case BlackQueenSideCastleWild:
9780 case WhiteHSideCastleFR:
9781 case WhiteASideCastleFR:
9782 case BlackHSideCastleFR:
9783 case BlackASideCastleFR:
9785 fromX = currentMoveString[0] - AAA;
9786 fromY = currentMoveString[1] - ONE;
9787 toX = currentMoveString[2] - AAA;
9788 toY = currentMoveString[3] - ONE;
9789 promoChar = currentMoveString[4];
9793 if(currentMoveString[0] == '@') continue; // no null moves in ICS mode!
9794 fromX = moveType == WhiteDrop ?
9795 (int) CharToPiece(ToUpper(currentMoveString[0])) :
9796 (int) CharToPiece(ToLower(currentMoveString[0]));
9798 toX = currentMoveString[2] - AAA;
9799 toY = currentMoveString[3] - ONE;
9800 promoChar = NULLCHAR;
9804 snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text);
9805 if (appData.debugMode) {
9806 fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text);
9807 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9808 setbuf(debugFP, NULL);
9810 DisplayError(buf, 0);
9812 case ImpossibleMove:
9814 snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text);
9815 if (appData.debugMode) {
9816 fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text);
9817 fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth);
9818 setbuf(debugFP, NULL);
9820 DisplayError(buf, 0);
9823 if (boardIndex < backwardMostMove) {
9824 /* Oops, gap. How did that happen? */
9825 DisplayError(_("Gap in move list"), 0);
9828 backwardMostMove = blackPlaysFirst ? 1 : 0;
9829 if (boardIndex > forwardMostMove) {
9830 forwardMostMove = boardIndex;
9834 if (boardIndex > (blackPlaysFirst ? 1 : 0)) {
9835 strcat(parseList[boardIndex-1], " ");
9836 strcat(parseList[boardIndex-1], yy_text);
9848 case GameUnfinished:
9849 if (gameMode == IcsExamining) {
9850 if (boardIndex < backwardMostMove) {
9851 /* Oops, gap. How did that happen? */
9854 backwardMostMove = blackPlaysFirst ? 1 : 0;
9857 gameInfo.result = moveType;
9858 p = strchr(yy_text, '{');
9859 if (p == NULL) p = strchr(yy_text, '(');
9862 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
9864 q = strchr(p, *p == '{' ? '}' : ')');
9865 if (q != NULL) *q = NULLCHAR;
9868 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
9869 gameInfo.resultDetails = StrSave(p);
9872 if (boardIndex >= forwardMostMove &&
9873 !(gameMode == IcsObserving && ics_gamenum == -1)) {
9874 backwardMostMove = blackPlaysFirst ? 1 : 0;
9877 (void) CoordsToAlgebraic(boards[boardIndex], PosFlags(boardIndex),
9878 fromY, fromX, toY, toX, promoChar,
9879 parseList[boardIndex]);
9880 CopyBoard(boards[boardIndex + 1], boards[boardIndex]);
9881 /* currentMoveString is set as a side-effect of yylex */
9882 safeStrCpy(moveList[boardIndex], currentMoveString, sizeof(moveList[boardIndex])/sizeof(moveList[boardIndex][0]));
9883 strcat(moveList[boardIndex], "\n");
9885 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[boardIndex]);
9886 switch (MateTest(boards[boardIndex], PosFlags(boardIndex)) ) {
9892 if(!IS_SHOGI(gameInfo.variant))
9893 strcat(parseList[boardIndex - 1], "+");
9897 strcat(parseList[boardIndex - 1], "#");
9904 /* Apply a move to the given board */
9906 ApplyMove (int fromX, int fromY, int toX, int toY, int promoChar, Board board)
9908 ChessSquare captured = board[toY][toX], piece, pawn, king, killed; int p, rookX, oldEP, epRank, berolina = 0;
9909 int promoRank = gameInfo.variant == VariantMakruk || gameInfo.variant == VariantGrand || gameInfo.variant == VariantChuChess ? 3 : 1;
9911 /* [HGM] compute & store e.p. status and castling rights for new position */
9912 /* we can always do that 'in place', now pointers to these rights are passed to ApplyMove */
9914 if(gameInfo.variant == VariantBerolina) berolina = EP_BEROLIN_A;
9915 oldEP = (signed char)board[EP_FILE]; epRank = board[EP_RANK];
9916 board[EP_STATUS] = EP_NONE;
9917 board[EP_FILE] = board[EP_RANK] = 100;
9919 if (fromY == DROP_RANK) {
9921 if(fromX == EmptySquare) { // [HGM] pass: empty drop encodes null move; nothing to change.
9922 board[EP_STATUS] = EP_CAPTURE; // null move considered irreversible
9925 piece = board[toY][toX] = (ChessSquare) fromX;
9927 // ChessSquare victim;
9930 if( killX >= 0 && killY >= 0 ) // [HGM] lion: Lion trampled over something
9931 // victim = board[killY][killX],
9932 killed = board[killY][killX],
9933 board[killY][killX] = EmptySquare,
9934 board[EP_STATUS] = EP_CAPTURE;
9936 if( board[toY][toX] != EmptySquare ) {
9937 board[EP_STATUS] = EP_CAPTURE;
9938 if( (fromX != toX || fromY != toY) && // not igui!
9939 (captured == WhiteLion && board[fromY][fromX] != BlackLion ||
9940 captured == BlackLion && board[fromY][fromX] != WhiteLion ) ) { // [HGM] lion: Chu Lion-capture rules
9941 board[EP_STATUS] = EP_IRON_LION; // non-Lion x Lion: no counter-strike allowed
9945 pawn = board[fromY][fromX];
9946 if( pawn == WhiteLance || pawn == BlackLance ) {
9947 if( gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu ) {
9948 if(gameInfo.variant == VariantSpartan) board[EP_STATUS] = EP_PAWN_MOVE; // in Spartan no e.p. rights must be set
9949 else pawn += WhitePawn - WhiteLance; // Lance is Pawn-like in most variants, so let Pawn code treat it by this kludge
9952 if( pawn == WhitePawn ) {
9953 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9954 board[EP_STATUS] = EP_PAWN_MOVE;
9956 board[EP_FILE] = (fromX + toX)/2; board[EP_RANK] = toY - 1 | 128*(toY - fromY > 2);
9957 if(toX>BOARD_LEFT && board[toY][toX-1] == BlackPawn &&
9958 gameInfo.variant != VariantBerolina || toX < fromX)
9959 board[EP_STATUS] = toX | berolina;
9960 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == BlackPawn &&
9961 gameInfo.variant != VariantBerolina || toX > fromX)
9962 board[EP_STATUS] = toX;
9965 if( pawn == BlackPawn ) {
9966 if(fromY != toY) // [HGM] Xiangqi sideway Pawn moves should not count as 50-move breakers
9967 board[EP_STATUS] = EP_PAWN_MOVE;
9968 if( toY-fromY<= -2) {
9969 board[EP_FILE] = (fromX + toX)/2; board[EP_RANK] = toY + 1 | 128*(fromY - toY > 2);
9970 if(toX>BOARD_LEFT && board[toY][toX-1] == WhitePawn &&
9971 gameInfo.variant != VariantBerolina || toX < fromX)
9972 board[EP_STATUS] = toX | berolina;
9973 if(toX<BOARD_RGHT-1 && board[toY][toX+1] == WhitePawn &&
9974 gameInfo.variant != VariantBerolina || toX > fromX)
9975 board[EP_STATUS] = toX;
9979 if(fromY == 0) board[TOUCHED_W] |= 1<<fromX; else // new way to keep track of virginity
9980 if(fromY == BOARD_HEIGHT-1) board[TOUCHED_B] |= 1<<fromX;
9981 if(toY == 0) board[TOUCHED_W] |= 1<<toX; else
9982 if(toY == BOARD_HEIGHT-1) board[TOUCHED_B] |= 1<<toX;
9984 for(i=0; i<nrCastlingRights; i++) {
9985 if(board[CASTLING][i] == fromX && castlingRank[i] == fromY ||
9986 board[CASTLING][i] == toX && castlingRank[i] == toY
9987 ) board[CASTLING][i] = NoRights; // revoke for moved or captured piece
9990 if(gameInfo.variant == VariantSChess) { // update virginity
9991 if(fromY == 0) board[VIRGIN][fromX] &= ~VIRGIN_W; // loss by moving
9992 if(fromY == BOARD_HEIGHT-1) board[VIRGIN][fromX] &= ~VIRGIN_B;
9993 if(toY == 0) board[VIRGIN][toX] &= ~VIRGIN_W; // loss by capture
9994 if(toY == BOARD_HEIGHT-1) board[VIRGIN][toX] &= ~VIRGIN_B;
9997 if (fromX == toX && fromY == toY) return;
9999 piece = board[fromY][fromX]; /* [HGM] remember, for Shogi promotion */
10000 king = piece < (int) BlackPawn ? WhiteKing : BlackKing; /* [HGM] Knightmate simplify testing for castling */
10001 if(gameInfo.variant == VariantKnightmate)
10002 king += (int) WhiteUnicorn - (int) WhiteKing;
10004 if(piece != WhiteKing && piece != BlackKing && pieceDesc[piece] && killX >= 0 && strchr(pieceDesc[piece], 'O') // Betza castling-enabled
10005 && (piece < BlackPawn ? killed < BlackPawn : killed >= BlackPawn)) { // and captures own
10006 board[toY][toX] = piece; board[fromY][fromX] = EmptySquare;
10007 board[toY][toX + (killX < fromX ? 1 : -1)] = killed;
10008 board[EP_STATUS] = EP_NONE; // capture was fake!
10010 /* Code added by Tord: */
10011 /* FRC castling assumed when king captures friendly rook. [HGM] or RxK for S-Chess */
10012 if (board[fromY][fromX] == WhiteKing && board[toY][toX] == WhiteRook ||
10013 board[fromY][fromX] == WhiteRook && board[toY][toX] == WhiteKing) {
10014 board[EP_STATUS] = EP_NONE; // capture was fake!
10015 board[fromY][fromX] = EmptySquare;
10016 board[toY][toX] = EmptySquare;
10017 if((toX > fromX) != (piece == WhiteRook)) {
10018 board[0][BOARD_RGHT-2] = WhiteKing; board[0][BOARD_RGHT-3] = WhiteRook;
10020 board[0][BOARD_LEFT+2] = WhiteKing; board[0][BOARD_LEFT+3] = WhiteRook;
10022 } else if (board[fromY][fromX] == BlackKing && board[toY][toX] == BlackRook ||
10023 board[fromY][fromX] == BlackRook && board[toY][toX] == BlackKing) {
10024 board[EP_STATUS] = EP_NONE;
10025 board[fromY][fromX] = EmptySquare;
10026 board[toY][toX] = EmptySquare;
10027 if((toX > fromX) != (piece == BlackRook)) {
10028 board[BOARD_HEIGHT-1][BOARD_RGHT-2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_RGHT-3] = BlackRook;
10030 board[BOARD_HEIGHT-1][BOARD_LEFT+2] = BlackKing; board[BOARD_HEIGHT-1][BOARD_LEFT+3] = BlackRook;
10032 /* End of code added by Tord */
10034 } else if (board[fromY][fromX] == king
10035 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10036 && toY == fromY && toX > fromX+1) {
10037 board[fromY][fromX] = EmptySquare;
10038 board[toY][toX] = king;
10039 for(rookX=BOARD_RGHT-1; board[toY][rookX] == DarkSquare && rookX > toX + 1; rookX--);
10040 board[toY][toX-1] = board[fromY][rookX];
10041 board[fromY][rookX] = EmptySquare;
10042 } else if (board[fromY][fromX] == king
10043 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10044 && toY == fromY && toX < fromX-1) {
10045 board[fromY][fromX] = EmptySquare;
10046 board[toY][toX] = king;
10047 for(rookX=BOARD_LEFT; board[toY][rookX] == DarkSquare && rookX < toX - 1; rookX++);
10048 board[toY][toX+1] = board[fromY][rookX];
10049 board[fromY][rookX] = EmptySquare;
10050 } else if ((board[fromY][fromX] == WhitePawn && gameInfo.variant != VariantXiangqi ||
10051 board[fromY][fromX] == WhiteLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu)
10052 && toY >= BOARD_HEIGHT-promoRank && promoChar // defaulting to Q is done elsewhere
10054 /* white pawn promotion */
10055 board[toY][toX] = CharToPiece(ToUpper(promoChar));
10056 if(board[toY][toX] < WhiteCannon && PieceToChar(PROMOTED board[toY][toX]) == '~') /* [HGM] use shadow piece (if available) */
10057 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
10058 board[fromY][fromX] = EmptySquare;
10059 } else if ((fromY >= BOARD_HEIGHT>>1)
10060 && (oldEP == toX || oldEP == EP_UNKNOWN || appData.testLegality || abs(toX - fromX) > 4)
10062 && gameInfo.variant != VariantXiangqi
10063 && gameInfo.variant != VariantBerolina
10064 && (pawn == WhitePawn)
10065 && (board[toY][toX] == EmptySquare)) {
10066 board[fromY][fromX] = EmptySquare;
10067 board[toY][toX] = piece;
10068 if(toY == epRank - 128 + 1)
10069 captured = board[toY - 2][toX], board[toY - 2][toX] = EmptySquare;
10071 captured = board[toY - 1][toX], board[toY - 1][toX] = EmptySquare;
10072 } else if ((fromY == BOARD_HEIGHT-4)
10074 && gameInfo.variant == VariantBerolina
10075 && (board[fromY][fromX] == WhitePawn)
10076 && (board[toY][toX] == EmptySquare)) {
10077 board[fromY][fromX] = EmptySquare;
10078 board[toY][toX] = WhitePawn;
10079 if(oldEP & EP_BEROLIN_A) {
10080 captured = board[fromY][fromX-1];
10081 board[fromY][fromX-1] = EmptySquare;
10082 }else{ captured = board[fromY][fromX+1];
10083 board[fromY][fromX+1] = EmptySquare;
10085 } else if (board[fromY][fromX] == king
10086 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10087 && toY == fromY && toX > fromX+1) {
10088 board[fromY][fromX] = EmptySquare;
10089 board[toY][toX] = king;
10090 for(rookX=BOARD_RGHT-1; board[toY][rookX] == DarkSquare && rookX > toX + 1; rookX--);
10091 board[toY][toX-1] = board[fromY][rookX];
10092 board[fromY][rookX] = EmptySquare;
10093 } else if (board[fromY][fromX] == king
10094 && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1 // [HGM] cylinder */
10095 && toY == fromY && toX < fromX-1) {
10096 board[fromY][fromX] = EmptySquare;
10097 board[toY][toX] = king;
10098 for(rookX=BOARD_LEFT; board[toY][rookX] == DarkSquare && rookX < toX - 1; rookX++);
10099 board[toY][toX+1] = board[fromY][rookX];
10100 board[fromY][rookX] = EmptySquare;
10101 } else if (fromY == 7 && fromX == 3
10102 && board[fromY][fromX] == BlackKing
10103 && toY == 7 && toX == 5) {
10104 board[fromY][fromX] = EmptySquare;
10105 board[toY][toX] = BlackKing;
10106 board[fromY][7] = EmptySquare;
10107 board[toY][4] = BlackRook;
10108 } else if (fromY == 7 && fromX == 3
10109 && board[fromY][fromX] == BlackKing
10110 && toY == 7 && toX == 1) {
10111 board[fromY][fromX] = EmptySquare;
10112 board[toY][toX] = BlackKing;
10113 board[fromY][0] = EmptySquare;
10114 board[toY][2] = BlackRook;
10115 } else if ((board[fromY][fromX] == BlackPawn && gameInfo.variant != VariantXiangqi ||
10116 board[fromY][fromX] == BlackLance && gameInfo.variant != VariantSuper && gameInfo.variant != VariantChu)
10117 && toY < promoRank && promoChar
10119 /* black pawn promotion */
10120 board[toY][toX] = CharToPiece(ToLower(promoChar));
10121 if(board[toY][toX] < BlackCannon && PieceToChar(PROMOTED board[toY][toX]) == '~') /* [HGM] use shadow piece (if available) */
10122 board[toY][toX] = (ChessSquare) (PROMOTED board[toY][toX]);
10123 board[fromY][fromX] = EmptySquare;
10124 } else if ((fromY < BOARD_HEIGHT>>1)
10125 && (oldEP == toX || oldEP == EP_UNKNOWN || appData.testLegality || abs(toX - fromX) > 4)
10127 && gameInfo.variant != VariantXiangqi
10128 && gameInfo.variant != VariantBerolina
10129 && (pawn == BlackPawn)
10130 && (board[toY][toX] == EmptySquare)) {
10131 board[fromY][fromX] = EmptySquare;
10132 board[toY][toX] = piece;
10133 if(toY == epRank - 128 - 1)
10134 captured = board[toY + 2][toX], board[toY + 2][toX] = EmptySquare;
10136 captured = board[toY + 1][toX], board[toY + 1][toX] = EmptySquare;
10137 } else if ((fromY == 3)
10139 && gameInfo.variant == VariantBerolina
10140 && (board[fromY][fromX] == BlackPawn)
10141 && (board[toY][toX] == EmptySquare)) {
10142 board[fromY][fromX] = EmptySquare;
10143 board[toY][toX] = BlackPawn;
10144 if(oldEP & EP_BEROLIN_A) {
10145 captured = board[fromY][fromX-1];
10146 board[fromY][fromX-1] = EmptySquare;
10147 }else{ captured = board[fromY][fromX+1];
10148 board[fromY][fromX+1] = EmptySquare;
10151 ChessSquare piece = board[fromY][fromX]; // [HGM] lion: allow for igui (where from == to)
10152 board[fromY][fromX] = EmptySquare;
10153 board[toY][toX] = piece;
10157 if (gameInfo.holdingsWidth != 0) {
10159 /* !!A lot more code needs to be written to support holdings */
10160 /* [HGM] OK, so I have written it. Holdings are stored in the */
10161 /* penultimate board files, so they are automaticlly stored */
10162 /* in the game history. */
10163 if (fromY == DROP_RANK || gameInfo.variant == VariantSChess
10164 && promoChar && piece != WhitePawn && piece != BlackPawn) {
10165 /* Delete from holdings, by decreasing count */
10166 /* and erasing image if necessary */
10167 p = fromY == DROP_RANK ? (int) fromX : CharToPiece(piece > BlackPawn ? ToLower(promoChar) : ToUpper(promoChar));
10168 if(p < (int) BlackPawn) { /* white drop */
10169 p -= (int)WhitePawn;
10170 p = PieceToNumber((ChessSquare)p);
10171 if(p >= gameInfo.holdingsSize) p = 0;
10172 if(--board[p][BOARD_WIDTH-2] <= 0)
10173 board[p][BOARD_WIDTH-1] = EmptySquare;
10174 if((int)board[p][BOARD_WIDTH-2] < 0)
10175 board[p][BOARD_WIDTH-2] = 0;
10176 } else { /* black drop */
10177 p -= (int)BlackPawn;
10178 p = PieceToNumber((ChessSquare)p);
10179 if(p >= gameInfo.holdingsSize) p = 0;
10180 if(--board[BOARD_HEIGHT-1-p][1] <= 0)
10181 board[BOARD_HEIGHT-1-p][0] = EmptySquare;
10182 if((int)board[BOARD_HEIGHT-1-p][1] < 0)
10183 board[BOARD_HEIGHT-1-p][1] = 0;
10186 if (captured != EmptySquare && gameInfo.holdingsSize > 0
10187 && gameInfo.variant != VariantBughouse && gameInfo.variant != VariantSChess ) {
10188 /* [HGM] holdings: Add to holdings, if holdings exist */
10189 if(gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) {
10190 // [HGM] superchess: suppress flipping color of captured pieces by reverse pre-flip
10191 captured = (int) captured >= (int) BlackPawn ? BLACK_TO_WHITE captured : WHITE_TO_BLACK captured;
10193 p = (int) captured;
10194 if (p >= (int) BlackPawn) {
10195 p -= (int)BlackPawn;
10196 if(DEMOTED p >= 0 && PieceToChar(p) == '+') {
10197 /* Restore shogi-promoted piece to its original first */
10198 captured = (ChessSquare) (DEMOTED captured);
10201 p = PieceToNumber((ChessSquare)p);
10202 if(p >= gameInfo.holdingsSize) { p = 0; captured = BlackPawn; }
10203 board[p][BOARD_WIDTH-2]++;
10204 board[p][BOARD_WIDTH-1] = BLACK_TO_WHITE captured;
10206 p -= (int)WhitePawn;
10207 if(DEMOTED p >= 0 && PieceToChar(p) == '+') {
10208 captured = (ChessSquare) (DEMOTED captured);
10211 p = PieceToNumber((ChessSquare)p);
10212 if(p >= gameInfo.holdingsSize) { p = 0; captured = WhitePawn; }
10213 board[BOARD_HEIGHT-1-p][1]++;
10214 board[BOARD_HEIGHT-1-p][0] = WHITE_TO_BLACK captured;
10217 } else if (gameInfo.variant == VariantAtomic) {
10218 if (captured != EmptySquare) {
10220 for (y = toY-1; y <= toY+1; y++) {
10221 for (x = toX-1; x <= toX+1; x++) {
10222 if (y >= 0 && y < BOARD_HEIGHT && x >= BOARD_LEFT && x < BOARD_RGHT &&
10223 board[y][x] != WhitePawn && board[y][x] != BlackPawn) {
10224 board[y][x] = EmptySquare;
10228 board[toY][toX] = EmptySquare;
10232 if(gameInfo.variant == VariantSChess && promoChar != NULLCHAR && promoChar != '=' && piece != WhitePawn && piece != BlackPawn) {
10233 board[fromY][fromX] = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar)); // S-Chess gating
10235 if(promoChar == '+') {
10236 /* [HGM] Shogi-style promotions, to piece implied by original (Might overwrite ordinary Pawn promotion) */
10237 board[toY][toX] = (ChessSquare) (CHUPROMOTED piece);
10238 if(gameInfo.variant == VariantChuChess && (piece == WhiteKnight || piece == BlackKnight))
10239 board[toY][toX] = piece + WhiteLion - WhiteKnight; // adjust Knight promotions to Lion
10240 } else if(!appData.testLegality && promoChar != NULLCHAR && promoChar != '=') { // without legality testing, unconditionally believe promoChar
10241 ChessSquare newPiece = CharToPiece(piece < BlackPawn ? ToUpper(promoChar) : ToLower(promoChar));
10242 if((newPiece <= WhiteMan || newPiece >= BlackPawn && newPiece <= BlackMan) // unpromoted piece specified
10243 && pieceToChar[PROMOTED newPiece] == '~') newPiece = PROMOTED newPiece; // but promoted version available
10244 board[toY][toX] = newPiece;
10246 if((gameInfo.variant == VariantSuper || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
10247 && promoChar != NULLCHAR && gameInfo.holdingsSize) {
10248 // [HGM] superchess: take promotion piece out of holdings
10249 int k = PieceToNumber(CharToPiece(ToUpper(promoChar)));
10250 if((int)piece < (int)BlackPawn) { // determine stm from piece color
10251 if(!--board[k][BOARD_WIDTH-2])
10252 board[k][BOARD_WIDTH-1] = EmptySquare;
10254 if(!--board[BOARD_HEIGHT-1-k][1])
10255 board[BOARD_HEIGHT-1-k][0] = EmptySquare;
10260 /* Updates forwardMostMove */
10262 MakeMove (int fromX, int fromY, int toX, int toY, int promoChar)
10264 int x = toX, y = toY;
10265 char *s = parseList[forwardMostMove];
10266 ChessSquare p = boards[forwardMostMove][toY][toX];
10267 // forwardMostMove++; // [HGM] bare: moved downstream
10269 if(killX >= 0 && killY >= 0) x = killX, y = killY; // [HGM] lion: make SAN move to intermediate square, if there is one
10270 (void) CoordsToAlgebraic(boards[forwardMostMove],
10271 PosFlags(forwardMostMove),
10272 fromY, fromX, y, x, promoChar,
10274 if(killX >= 0 && killY >= 0)
10275 sprintf(s + strlen(s), "%c%c%d", p == EmptySquare || toX == fromX && toY == fromY ? '-' : 'x', toX + AAA, toY + ONE - '0');
10277 if(serverMoves != NULL) { /* [HGM] write moves on file for broadcasting (should be separate routine, really) */
10278 int timeLeft; static int lastLoadFlag=0; int king, piece;
10279 piece = boards[forwardMostMove][fromY][fromX];
10280 king = piece < (int) BlackPawn ? WhiteKing : BlackKing;
10281 if(gameInfo.variant == VariantKnightmate)
10282 king += (int) WhiteUnicorn - (int) WhiteKing;
10283 if(forwardMostMove == 0) {
10284 if(gameMode == MachinePlaysBlack || gameMode == BeginningOfGame)
10285 fprintf(serverMoves, "%s;", UserName());
10286 else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b')
10287 fprintf(serverMoves, "%s;", second.tidy);
10288 fprintf(serverMoves, "%s;", first.tidy);
10289 if(gameMode == MachinePlaysWhite)
10290 fprintf(serverMoves, "%s;", UserName());
10291 else if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
10292 fprintf(serverMoves, "%s;", second.tidy);
10293 } else fprintf(serverMoves, loadFlag|lastLoadFlag ? ":" : ";");
10294 lastLoadFlag = loadFlag;
10296 fprintf(serverMoves, "%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+toY);
10297 // print castling suffix
10298 if( toY == fromY && piece == king ) {
10300 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_RGHT-1, ONE+fromY, AAA+toX-1,ONE+toY);
10302 fprintf(serverMoves, ":%c%c:%c%c", AAA+BOARD_LEFT, ONE+fromY, AAA+toX+1,ONE+toY);
10305 if( (boards[forwardMostMove][fromY][fromX] == WhitePawn ||
10306 boards[forwardMostMove][fromY][fromX] == BlackPawn ) &&
10307 boards[forwardMostMove][toY][toX] == EmptySquare
10308 && fromX != toX && fromY != toY)
10309 fprintf(serverMoves, ":%c%c:%c%c", AAA+fromX, ONE+fromY, AAA+toX, ONE+fromY);
10310 // promotion suffix
10311 if(promoChar != NULLCHAR) {
10312 if(fromY == 0 || fromY == BOARD_HEIGHT-1)
10313 fprintf(serverMoves, ":%c%c:%c%c", WhiteOnMove(forwardMostMove) ? 'w' : 'b',
10314 ToLower(promoChar), AAA+fromX, ONE+fromY); // Seirawan gating
10315 else fprintf(serverMoves, ":%c:%c%c", ToLower(promoChar), AAA+toX, ONE+toY);
10318 char buf[MOVE_LEN*2], *p; int len;
10319 fprintf(serverMoves, "/%d/%d",
10320 pvInfoList[forwardMostMove].depth, pvInfoList[forwardMostMove].score);
10321 if(forwardMostMove+1 & 1) timeLeft = whiteTimeRemaining/1000;
10322 else timeLeft = blackTimeRemaining/1000;
10323 fprintf(serverMoves, "/%d", timeLeft);
10324 strncpy(buf, parseList[forwardMostMove], MOVE_LEN*2);
10325 if(p = strchr(buf, '/')) *p = NULLCHAR; else
10326 if(p = strchr(buf, '=')) *p = NULLCHAR;
10327 len = strlen(buf); if(len > 1 && buf[len-2] != '-') buf[len-2] = NULLCHAR; // strip to-square
10328 fprintf(serverMoves, "/%s", buf);
10330 fflush(serverMoves);
10333 if (forwardMostMove+1 > framePtr) { // [HGM] vari: do not run into saved variations..
10334 GameEnds(GameUnfinished, _("Game too long; increase MAX_MOVES and recompile"), GE_XBOARD);
10337 UnLoadPV(); // [HGM] pv: if we are looking at a PV, abort this
10338 if (commentList[forwardMostMove+1] != NULL) {
10339 free(commentList[forwardMostMove+1]);
10340 commentList[forwardMostMove+1] = NULL;
10342 CopyBoard(boards[forwardMostMove+1], boards[forwardMostMove]);
10343 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[forwardMostMove+1]);
10344 // forwardMostMove++; // [HGM] bare: moved to after ApplyMove, to make sure clock interrupt finds complete board
10345 SwitchClocks(forwardMostMove+1); // [HGM] race: incrementing move nr inside
10346 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
10347 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
10348 adjustedClock = FALSE;
10349 gameInfo.result = GameUnfinished;
10350 if (gameInfo.resultDetails != NULL) {
10351 free(gameInfo.resultDetails);
10352 gameInfo.resultDetails = NULL;
10354 CoordsToComputerAlgebraic(fromY, fromX, toY, toX, promoChar,
10355 moveList[forwardMostMove - 1]);
10356 switch (MateTest(boards[forwardMostMove], PosFlags(forwardMostMove)) ) {
10362 if(!IS_SHOGI(gameInfo.variant))
10363 strcat(parseList[forwardMostMove - 1], "+");
10367 strcat(parseList[forwardMostMove - 1], "#");
10372 /* Updates currentMove if not pausing */
10374 ShowMove (int fromX, int fromY, int toX, int toY)
10376 int instant = (gameMode == PlayFromGameFile) ?
10377 (matchMode || (appData.timeDelay == 0 && !pausing)) : pausing;
10378 if(appData.noGUI) return;
10379 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
10381 if (forwardMostMove == currentMove + 1) {
10382 AnimateMove(boards[forwardMostMove - 1],
10383 fromX, fromY, toX, toY);
10386 currentMove = forwardMostMove;
10389 killX = killY = -1; // [HGM] lion: used up
10391 if (instant) return;
10393 DisplayMove(currentMove - 1);
10394 if (!pausing || gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
10395 if (appData.highlightLastMove) { // [HGM] moved to after DrawPosition, as with arrow it could redraw old board
10396 SetHighlights(fromX, fromY, toX, toY);
10399 DrawPosition(FALSE, boards[currentMove]);
10400 DisplayBothClocks();
10401 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
10405 SendEgtPath (ChessProgramState *cps)
10406 { /* [HGM] EGT: match formats given in feature with those given by user, and send info for each match */
10407 char buf[MSG_SIZ], name[MSG_SIZ], *p;
10409 if((p = cps->egtFormats) == NULL || appData.egtFormats == NULL) return;
10412 char c, *q = name+1, *r, *s;
10414 name[0] = ','; // extract next format name from feature and copy with prefixed ','
10415 while(*p && *p != ',') *q++ = *p++;
10416 *q++ = ':'; *q = 0;
10417 if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] &&
10418 strcmp(name, ",nalimov:") == 0 ) {
10419 // take nalimov path from the menu-changeable option first, if it is defined
10420 snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB);
10421 SendToProgram(buf,cps); // send egtbpath command for nalimov
10423 if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats ||
10424 (s = StrStr(appData.egtFormats, name)) != NULL) {
10425 // format name occurs amongst user-supplied formats, at beginning or immediately after comma
10426 s = r = StrStr(s, ":") + 1; // beginning of path info
10427 while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string
10428 c = *r; *r = 0; // temporarily null-terminate path info
10429 *--q = 0; // strip of trailig ':' from name
10430 snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s);
10432 SendToProgram(buf,cps); // send egtbpath command for this format
10434 if(*p == ',') p++; // read away comma to position for next format name
10439 NonStandardBoardSize (VariantClass v, int boardWidth, int boardHeight, int holdingsSize)
10441 int width = 8, height = 8, holdings = 0; // most common sizes
10442 if( v == VariantUnknown || *engineVariant) return 0; // engine-defined name never needs prefix
10443 // correct the deviations default for each variant
10444 if( v == VariantXiangqi ) width = 9, height = 10;
10445 if( v == VariantShogi ) width = 9, height = 9, holdings = 7;
10446 if( v == VariantBughouse || v == VariantCrazyhouse) holdings = 5;
10447 if( v == VariantCapablanca || v == VariantCapaRandom ||
10448 v == VariantGothic || v == VariantFalcon || v == VariantJanus )
10450 if( v == VariantCourier ) width = 12;
10451 if( v == VariantSuper ) holdings = 8;
10452 if( v == VariantGreat ) width = 10, holdings = 8;
10453 if( v == VariantSChess ) holdings = 7;
10454 if( v == VariantGrand ) width = 10, height = 10, holdings = 7;
10455 if( v == VariantChuChess) width = 10, height = 10;
10456 if( v == VariantChu ) width = 12, height = 12;
10457 return boardWidth >= 0 && boardWidth != width || // -1 is default,
10458 boardHeight >= 0 && boardHeight != height || // and thus by definition OK
10459 holdingsSize >= 0 && holdingsSize != holdings;
10462 char variantError[MSG_SIZ];
10465 SupportedVariant (char *list, VariantClass v, int boardWidth, int boardHeight, int holdingsSize, int proto, char *engine)
10466 { // returns error message (recognizable by upper-case) if engine does not support the variant
10467 char *p, *variant = VariantName(v);
10468 static char b[MSG_SIZ];
10469 if(NonStandardBoardSize(v, boardWidth, boardHeight, holdingsSize)) { /* [HGM] make prefix for non-standard board size. */
10470 snprintf(b, MSG_SIZ, "%dx%d+%d_%s", boardWidth, boardHeight,
10471 holdingsSize, variant); // cook up sized variant name
10472 /* [HGM] varsize: try first if this deviant size variant is specifically known */
10473 if(StrStr(list, b) == NULL) {
10474 // specific sized variant not known, check if general sizing allowed
10475 if(proto != 1 && StrStr(list, "boardsize") == NULL) {
10476 snprintf(variantError, MSG_SIZ, "Board size %dx%d+%d not supported by %s",
10477 boardWidth, boardHeight, holdingsSize, engine);
10480 /* [HGM] here we really should compare with the maximum supported board size */
10482 } else snprintf(b, MSG_SIZ,"%s", variant);
10483 if(proto == 1) return b; // for protocol 1 we cannot check and hope for the best
10484 p = StrStr(list, b);
10485 while(p && (p != list && p[-1] != ',' || p[strlen(b)] && p[strlen(b)] != ',') ) p = StrStr(p+1, b);
10487 // occurs not at all in list, or only as sub-string
10488 snprintf(variantError, MSG_SIZ, _("Variant %s not supported by %s"), b, engine);
10489 if(p = StrStr(list, b)) { // handle requesting parent variant when only size-overridden is supported
10490 int l = strlen(variantError);
10492 while(p != list && p[-1] != ',') p--;
10493 q = strchr(p, ',');
10494 if(q) *q = NULLCHAR;
10495 snprintf(variantError + l, MSG_SIZ - l, _(", but %s is"), p);
10504 InitChessProgram (ChessProgramState *cps, int setup)
10505 /* setup needed to setup FRC opening position */
10507 char buf[MSG_SIZ], *b;
10508 if (appData.noChessProgram) return;
10509 hintRequested = FALSE;
10510 bookRequested = FALSE;
10512 ParseFeatures(appData.features[cps == &second], cps); // [HGM] allow user to overrule features
10513 /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */
10514 /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */
10515 if(cps->memSize) { /* [HGM] memory */
10516 snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB);
10517 SendToProgram(buf, cps);
10519 SendEgtPath(cps); /* [HGM] EGT */
10520 if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */
10521 snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores);
10522 SendToProgram(buf, cps);
10525 setboardSpoiledMachineBlack = FALSE;
10526 SendToProgram(cps->initString, cps);
10527 if (gameInfo.variant != VariantNormal &&
10528 gameInfo.variant != VariantLoadable
10529 /* [HGM] also send variant if board size non-standard */
10530 || gameInfo.boardWidth != 8 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 0) {
10532 b = SupportedVariant(cps->variants, gameInfo.variant, gameInfo.boardWidth,
10533 gameInfo.boardHeight, gameInfo.holdingsSize, cps->protocolVersion, cps->tidy);
10536 char c, *q = cps->variants, *p = strchr(q, ',');
10537 if(p) *p = NULLCHAR;
10538 v = StringToVariant(q);
10539 DisplayError(variantError, 0);
10540 if(v != VariantUnknown && cps == &first) {
10542 if(sscanf(q, "%dx%d+%d_%c", &w, &h, &s, &c) == 4) // get size overrides the engine needs with it (if any)
10543 appData.NrFiles = w, appData.NrRanks = h, appData.holdingsSize = s, q = strchr(q, '_') + 1;
10544 ASSIGN(appData.variant, q);
10545 Reset(TRUE, FALSE);
10551 snprintf(buf, MSG_SIZ, "variant %s\n", b);
10552 SendToProgram(buf, cps);
10554 currentlyInitializedVariant = gameInfo.variant;
10556 /* [HGM] send opening position in FRC to first engine */
10558 SendToProgram("force\n", cps);
10560 /* engine is now in force mode! Set flag to wake it up after first move. */
10561 setboardSpoiledMachineBlack = 1;
10564 if (cps->sendICS) {
10565 snprintf(buf, sizeof(buf), "ics %s\n", appData.icsActive ? appData.icsHost : "-");
10566 SendToProgram(buf, cps);
10568 cps->maybeThinking = FALSE;
10569 cps->offeredDraw = 0;
10570 if (!appData.icsActive) {
10571 SendTimeControl(cps, movesPerSession, timeControl,
10572 timeIncrement, appData.searchDepth,
10575 if (appData.showThinking
10576 // [HGM] thinking: four options require thinking output to be sent
10577 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp()
10579 SendToProgram("post\n", cps);
10581 SendToProgram("hard\n", cps);
10582 if (!appData.ponderNextMove) {
10583 /* Warning: "easy" is a toggle in GNU Chess, so don't send
10584 it without being sure what state we are in first. "hard"
10585 is not a toggle, so that one is OK.
10587 SendToProgram("easy\n", cps);
10589 if (cps->usePing) {
10590 snprintf(buf, MSG_SIZ, "ping %d\n", initPing = ++cps->lastPing);
10591 SendToProgram(buf, cps);
10593 cps->initDone = TRUE;
10594 ClearEngineOutputPane(cps == &second);
10599 ResendOptions (ChessProgramState *cps)
10600 { // send the stored value of the options
10603 Option *opt = cps->option;
10604 for(i=0; i<cps->nrOptions; i++, opt++) {
10605 switch(opt->type) {
10609 snprintf(buf, MSG_SIZ, "option %s=%d\n", opt->name, opt->value);
10612 snprintf(buf, MSG_SIZ, "option %s=%s\n", opt->name, opt->choice[opt->value]);
10615 snprintf(buf, MSG_SIZ, "option %s=%s\n", opt->name, opt->textValue);
10621 SendToProgram(buf, cps);
10626 StartChessProgram (ChessProgramState *cps)
10631 if (appData.noChessProgram) return;
10632 cps->initDone = FALSE;
10634 if (strcmp(cps->host, "localhost") == 0) {
10635 err = StartChildProcess(cps->program, cps->dir, &cps->pr);
10636 } else if (*appData.remoteShell == NULLCHAR) {
10637 err = OpenRcmd(cps->host, appData.remoteUser, cps->program, &cps->pr);
10639 if (*appData.remoteUser == NULLCHAR) {
10640 snprintf(buf, sizeof(buf), "%s %s %s", appData.remoteShell, cps->host,
10643 snprintf(buf, sizeof(buf), "%s %s -l %s %s", appData.remoteShell,
10644 cps->host, appData.remoteUser, cps->program);
10646 err = StartChildProcess(buf, "", &cps->pr);
10650 snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program);
10651 DisplayError(buf, err); // [HGM] bit of a rough kludge: ignore failure, (which XBoard would do anyway), and let I/O discover it
10652 if(cps != &first) return;
10653 appData.noChessProgram = TRUE;
10656 // DisplayFatalError(buf, err, 1);
10657 // cps->pr = NoProc;
10658 // cps->isr = NULL;
10662 cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps);
10663 if (cps->protocolVersion > 1) {
10664 snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion);
10665 if(!cps->reload) { // do not clear options when reloading because of -xreuse
10666 cps->nrOptions = 0; // [HGM] options: clear all engine-specific options
10667 cps->comboCnt = 0; // and values of combo boxes
10669 SendToProgram(buf, cps);
10670 if(cps->reload) ResendOptions(cps);
10672 SendToProgram("xboard\n", cps);
10677 TwoMachinesEventIfReady P((void))
10679 static int curMess = 0;
10680 if (first.lastPing != first.lastPong) {
10681 if(curMess != 1) DisplayMessage("", _("Waiting for first chess program")); curMess = 1;
10682 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
10685 if (second.lastPing != second.lastPong) {
10686 if(curMess != 2) DisplayMessage("", _("Waiting for second chess program")); curMess = 2;
10687 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10); // [HGM] fast: lowered from 1000
10690 DisplayMessage("", ""); curMess = 0;
10691 TwoMachinesEvent();
10695 MakeName (char *template)
10699 static char buf[MSG_SIZ];
10703 clock = time((time_t *)NULL);
10704 tm = localtime(&clock);
10706 while(*p++ = *template++) if(p[-1] == '%') {
10707 switch(*template++) {
10708 case 0: *p = 0; return buf;
10709 case 'Y': i = tm->tm_year+1900; break;
10710 case 'y': i = tm->tm_year-100; break;
10711 case 'M': i = tm->tm_mon+1; break;
10712 case 'd': i = tm->tm_mday; break;
10713 case 'h': i = tm->tm_hour; break;
10714 case 'm': i = tm->tm_min; break;
10715 case 's': i = tm->tm_sec; break;
10718 snprintf(p-1, MSG_SIZ-10 - (p - buf), "%02d", i); p += strlen(p);
10724 CountPlayers (char *p)
10727 while(p = strchr(p, '\n')) p++, n++; // count participants
10732 WriteTourneyFile (char *results, FILE *f)
10733 { // write tournament parameters on tourneyFile; on success return the stream pointer for closing
10734 if(f == NULL) f = fopen(appData.tourneyFile, "w");
10735 if(f == NULL) DisplayError(_("Could not write on tourney file"), 0); else {
10736 // create a file with tournament description
10737 fprintf(f, "-participants {%s}\n", appData.participants);
10738 fprintf(f, "-seedBase %d\n", appData.seedBase);
10739 fprintf(f, "-tourneyType %d\n", appData.tourneyType);
10740 fprintf(f, "-tourneyCycles %d\n", appData.tourneyCycles);
10741 fprintf(f, "-defaultMatchGames %d\n", appData.defaultMatchGames);
10742 fprintf(f, "-syncAfterRound %s\n", appData.roundSync ? "true" : "false");
10743 fprintf(f, "-syncAfterCycle %s\n", appData.cycleSync ? "true" : "false");
10744 fprintf(f, "-saveGameFile \"%s\"\n", appData.saveGameFile);
10745 fprintf(f, "-loadGameFile \"%s\"\n", appData.loadGameFile);
10746 fprintf(f, "-loadGameIndex %d\n", appData.loadGameIndex);
10747 fprintf(f, "-loadPositionFile \"%s\"\n", appData.loadPositionFile);
10748 fprintf(f, "-loadPositionIndex %d\n", appData.loadPositionIndex);
10749 fprintf(f, "-rewindIndex %d\n", appData.rewindIndex);
10750 fprintf(f, "-usePolyglotBook %s\n", appData.usePolyglotBook ? "true" : "false");
10751 fprintf(f, "-polyglotBook \"%s\"\n", appData.polyglotBook);
10752 fprintf(f, "-bookDepth %d\n", appData.bookDepth);
10753 fprintf(f, "-bookVariation %d\n", appData.bookStrength);
10754 fprintf(f, "-discourageOwnBooks %s\n", appData.defNoBook ? "true" : "false");
10755 fprintf(f, "-defaultHashSize %d\n", appData.defaultHashSize);
10756 fprintf(f, "-defaultCacheSizeEGTB %d\n", appData.defaultCacheSizeEGTB);
10757 fprintf(f, "-ponderNextMove %s\n", appData.ponderNextMove ? "true" : "false");
10758 fprintf(f, "-smpCores %d\n", appData.smpCores);
10760 fprintf(f, "-searchTime \"%d:%02d\"\n", searchTime/60, searchTime%60);
10762 fprintf(f, "-mps %d\n", appData.movesPerSession);
10763 fprintf(f, "-tc %s\n", appData.timeControl);
10764 fprintf(f, "-inc %.2f\n", appData.timeIncrement);
10766 fprintf(f, "-results \"%s\"\n", results);
10771 char *command[MAXENGINES], *mnemonic[MAXENGINES];
10774 Substitute (char *participants, int expunge)
10776 int i, changed, changes=0, nPlayers=0;
10777 char *p, *q, *r, buf[MSG_SIZ];
10778 if(participants == NULL) return;
10779 if(appData.tourneyFile[0] == NULLCHAR) { free(participants); return; }
10780 r = p = participants; q = appData.participants;
10781 while(*p && *p == *q) {
10782 if(*p == '\n') r = p+1, nPlayers++;
10785 if(*p) { // difference
10786 while(*p && *p++ != '\n');
10787 while(*q && *q++ != '\n');
10788 changed = nPlayers;
10789 changes = 1 + (strcmp(p, q) != 0);
10791 if(changes == 1) { // a single engine mnemonic was changed
10792 q = r; while(*q) nPlayers += (*q++ == '\n');
10793 p = buf; while(*r && (*p = *r++) != '\n') p++;
10795 NamesToList(firstChessProgramNames, command, mnemonic, "all");
10796 for(i=1; mnemonic[i]; i++) if(!strcmp(buf, mnemonic[i])) break;
10797 if(mnemonic[i]) { // The substitute is valid
10799 if(appData.tourneyFile[0] && (f = fopen(appData.tourneyFile, "r+")) ) {
10800 flock(fileno(f), LOCK_EX);
10801 ParseArgsFromFile(f);
10802 fseek(f, 0, SEEK_SET);
10803 FREE(appData.participants); appData.participants = participants;
10804 if(expunge) { // erase results of replaced engine
10805 int len = strlen(appData.results), w, b, dummy;
10806 for(i=0; i<len; i++) {
10807 Pairing(i, nPlayers, &w, &b, &dummy);
10808 if((w == changed || b == changed) && appData.results[i] == '*') {
10809 DisplayError(_("You cannot replace an engine while it is engaged!\nTerminate its game first."), 0);
10814 for(i=0; i<len; i++) {
10815 Pairing(i, nPlayers, &w, &b, &dummy);
10816 if(w == changed || b == changed) appData.results[i] = ' '; // mark as not played
10819 WriteTourneyFile(appData.results, f);
10820 fclose(f); // release lock
10823 } else DisplayError(_("No engine with the name you gave is installed"), 0);
10825 if(changes == 0) DisplayError(_("First change an engine by editing the participants list\nof the Tournament Options dialog"), 0);
10826 if(changes > 1) DisplayError(_("You can only change one engine at the time"), 0);
10827 free(participants);
10832 CheckPlayers (char *participants)
10835 char buf[MSG_SIZ], *p;
10836 NamesToList(firstChessProgramNames, command, mnemonic, "all");
10837 while(p = strchr(participants, '\n')) {
10839 for(i=1; mnemonic[i]; i++) if(!strcmp(participants, mnemonic[i])) break;
10841 snprintf(buf, MSG_SIZ, _("No engine %s is installed"), participants);
10843 DisplayError(buf, 0);
10847 participants = p + 1;
10853 CreateTourney (char *name)
10856 if(matchMode && strcmp(name, appData.tourneyFile)) {
10857 ASSIGN(name, appData.tourneyFile); //do not allow change of tourneyfile while playing
10859 if(name[0] == NULLCHAR) {
10860 if(appData.participants[0])
10861 DisplayError(_("You must supply a tournament file,\nfor storing the tourney progress"), 0);
10864 f = fopen(name, "r");
10865 if(f) { // file exists
10866 ASSIGN(appData.tourneyFile, name);
10867 ParseArgsFromFile(f); // parse it
10869 if(!appData.participants[0]) return 0; // ignore tourney file if non-existing & no participants
10870 if(CountPlayers(appData.participants) < (appData.tourneyType>0 ? appData.tourneyType+1 : 2)) {
10871 DisplayError(_("Not enough participants"), 0);
10874 if(CheckPlayers(appData.participants)) return 0;
10875 ASSIGN(appData.tourneyFile, name);
10876 if(appData.tourneyType < 0) appData.defaultMatchGames = 1; // Swiss forces games/pairing = 1
10877 if((f = WriteTourneyFile("", NULL)) == NULL) return 0;
10880 appData.noChessProgram = FALSE;
10881 appData.clockMode = TRUE;
10887 NamesToList (char *names, char **engineList, char **engineMnemonic, char *group)
10889 char buf[MSG_SIZ], *p, *q;
10890 int i=1, header, skip, all = !strcmp(group, "all"), depth = 0;
10891 insert = names; // afterwards, this global will point just after last retrieved engine line or group end in the 'names'
10892 skip = !all && group[0]; // if group requested, we start in skip mode
10893 for(;*names && depth >= 0 && i < MAXENGINES-1; names = p) {
10894 p = names; q = buf; header = 0;
10895 while(*p && *p != '\n') *q++ = *p++;
10897 if(*p == '\n') p++;
10898 if(buf[0] == '#') {
10899 if(strstr(buf, "# end") == buf) { if(!--depth) insert = p; continue; } // leave group, and suppress printing label
10900 depth++; // we must be entering a new group
10901 if(all) continue; // suppress printing group headers when complete list requested
10903 if(skip && !strcmp(group, buf)) { depth = 0; skip = FALSE; } // start when we reach requested group
10905 if(depth != header && !all || skip) continue; // skip contents of group (but print first-level header)
10906 if(engineList[i]) free(engineList[i]);
10907 engineList[i] = strdup(buf);
10908 if(buf[0] != '#') insert = p, TidyProgramName(engineList[i], "localhost", buf); // group headers not tidied
10909 if(engineMnemonic[i]) free(engineMnemonic[i]);
10910 if((q = strstr(engineList[i]+2, "variant")) && q[-2]== ' ' && (q[-1]=='/' || q[-1]=='-') && (q[7]==' ' || q[7]=='=')) {
10912 sscanf(q + 8, "%s", buf + strlen(buf));
10915 engineMnemonic[i] = strdup(buf);
10918 engineList[i] = engineMnemonic[i] = NULL;
10922 // following implemented as macro to avoid type limitations
10923 #define SWAP(item, temp) temp = appData.item[0]; appData.item[0] = appData.item[n]; appData.item[n] = temp;
10926 SwapEngines (int n)
10927 { // swap settings for first engine and other engine (so far only some selected options)
10932 SWAP(chessProgram, p)
10934 SWAP(hasOwnBookUCI, h)
10935 SWAP(protocolVersion, h)
10937 SWAP(scoreIsAbsolute, h)
10942 SWAP(engOptions, p)
10943 SWAP(engInitString, p)
10944 SWAP(computerString, p)
10946 SWAP(fenOverride, p)
10948 SWAP(accumulateTC, h)
10955 GetEngineLine (char *s, int n)
10959 extern char *icsNames;
10960 if(!s || !*s) return 0;
10961 NamesToList(n >= 10 ? icsNames : firstChessProgramNames, command, mnemonic, "all");
10962 for(i=1; mnemonic[i]; i++) if(!strcmp(s, mnemonic[i])) break;
10963 if(!mnemonic[i]) return 0;
10964 if(n == 11) return 1; // just testing if there was a match
10965 snprintf(buf, MSG_SIZ, "-%s %s", n == 10 ? "icshost" : "fcp", command[i]);
10966 if(n == 1) SwapEngines(n);
10967 ParseArgsFromString(buf);
10968 if(n == 1) SwapEngines(n);
10969 if(n == 0 && *appData.secondChessProgram == NULLCHAR) {
10970 SwapEngines(1); // set second same as first if not yet set (to suppress WB startup dialog)
10971 ParseArgsFromString(buf);
10977 SetPlayer (int player, char *p)
10978 { // [HGM] find the engine line of the partcipant given by number, and parse its options.
10980 char buf[MSG_SIZ], *engineName;
10981 for(i=0; i<player; i++) p = strchr(p, '\n') + 1;
10982 engineName = strdup(p); if(p = strchr(engineName, '\n')) *p = NULLCHAR;
10983 for(i=1; command[i]; i++) if(!strcmp(mnemonic[i], engineName)) break;
10985 snprintf(buf, MSG_SIZ, "-fcp %s", command[i]);
10986 ParseArgsFromString(resetOptions); appData.fenOverride[0] = NULL; appData.pvSAN[0] = FALSE;
10987 appData.firstHasOwnBookUCI = !appData.defNoBook; appData.protocolVersion[0] = PROTOVER;
10988 ParseArgsFromString(buf);
10989 } else { // no engine with this nickname is installed!
10990 snprintf(buf, MSG_SIZ, _("No engine %s is installed"), engineName);
10991 ReserveGame(nextGame, ' '); // unreserve game and drop out of match mode with error
10992 matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
10994 DisplayError(buf, 0);
11001 char *recentEngines;
11004 RecentEngineEvent (int nr)
11007 // SwapEngines(1); // bump first to second
11008 // ReplaceEngine(&second, 1); // and load it there
11009 NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
11010 n = SetPlayer(nr, recentEngines); // select new (using original menu order!)
11011 if(mnemonic[n]) { // if somehow the engine with the selected nickname is no longer found in the list, we skip
11012 ReplaceEngine(&first, 0);
11013 FloatToFront(&appData.recentEngineList, command[n]);
11018 Pairing (int nr, int nPlayers, int *whitePlayer, int *blackPlayer, int *syncInterval)
11019 { // determine players from game number
11020 int curCycle, curRound, curPairing, gamesPerCycle, gamesPerRound, roundsPerCycle=1, pairingsPerRound=1;
11022 if(appData.tourneyType == 0) {
11023 roundsPerCycle = (nPlayers - 1) | 1;
11024 pairingsPerRound = nPlayers / 2;
11025 } else if(appData.tourneyType > 0) {
11026 roundsPerCycle = nPlayers - appData.tourneyType;
11027 pairingsPerRound = appData.tourneyType;
11029 gamesPerRound = pairingsPerRound * appData.defaultMatchGames;
11030 gamesPerCycle = gamesPerRound * roundsPerCycle;
11031 appData.matchGames = gamesPerCycle * appData.tourneyCycles - 1; // fake like all games are one big match
11032 curCycle = nr / gamesPerCycle; nr %= gamesPerCycle;
11033 curRound = nr / gamesPerRound; nr %= gamesPerRound;
11034 curPairing = nr / appData.defaultMatchGames; nr %= appData.defaultMatchGames;
11035 matchGame = nr + curCycle * appData.defaultMatchGames + 1; // fake game nr that loads correct game or position from file
11036 roundNr = (curCycle * roundsPerCycle + curRound) * appData.defaultMatchGames + nr + 1;
11038 if(appData.cycleSync) *syncInterval = gamesPerCycle;
11039 if(appData.roundSync) *syncInterval = gamesPerRound;
11041 if(appData.debugMode) fprintf(debugFP, "cycle=%d, round=%d, pairing=%d curGame=%d\n", curCycle, curRound, curPairing, matchGame);
11043 if(appData.tourneyType == 0) {
11044 if(curPairing == (nPlayers-1)/2 ) {
11045 *whitePlayer = curRound;
11046 *blackPlayer = nPlayers - 1; // this is the 'bye' when nPlayer is odd
11048 *whitePlayer = curRound - (nPlayers-1)/2 + curPairing;
11049 if(*whitePlayer < 0) *whitePlayer += nPlayers-1+(nPlayers&1);
11050 *blackPlayer = curRound + (nPlayers-1)/2 - curPairing;
11051 if(*blackPlayer >= nPlayers-1+(nPlayers&1)) *blackPlayer -= nPlayers-1+(nPlayers&1);
11053 } else if(appData.tourneyType > 1) {
11054 *blackPlayer = curPairing; // in multi-gauntlet, assign gauntlet engines to second, so first an be kept loaded during round
11055 *whitePlayer = curRound + appData.tourneyType;
11056 } else if(appData.tourneyType > 0) {
11057 *whitePlayer = curPairing;
11058 *blackPlayer = curRound + appData.tourneyType;
11061 // take care of white/black alternation per round.
11062 // For cycles and games this is already taken care of by default, derived from matchGame!
11063 return curRound & 1;
11067 NextTourneyGame (int nr, int *swapColors)
11068 { // !!!major kludge!!! fiddle appData settings to get everything in order for next tourney game
11070 int whitePlayer, blackPlayer, firstBusy=1000000000, syncInterval = 0, nPlayers, OK = 1;
11072 if(appData.tourneyFile[0] == NULLCHAR) return 1; // no tourney, always allow next game
11073 tf = fopen(appData.tourneyFile, "r");
11074 if(tf == NULL) { DisplayFatalError(_("Bad tournament file"), 0, 1); return 0; }
11075 ParseArgsFromFile(tf); fclose(tf);
11076 InitTimeControls(); // TC might be altered from tourney file
11078 nPlayers = CountPlayers(appData.participants); // count participants
11079 if(appData.tourneyType < 0) syncInterval = nPlayers/2; else
11080 *swapColors = Pairing(nr<0 ? 0 : nr, nPlayers, &whitePlayer, &blackPlayer, &syncInterval);
11083 p = q = appData.results;
11084 while(*q) if(*q++ == '*' || q[-1] == ' ') { firstBusy = q - p - 1; break; }
11085 if(firstBusy/syncInterval < (nextGame/syncInterval)) {
11086 DisplayMessage(_("Waiting for other game(s)"),"");
11087 waitingForGame = TRUE;
11088 ScheduleDelayedEvent(NextMatchGame, 1000); // wait for all games of previous round to finish
11091 waitingForGame = FALSE;
11094 if(appData.tourneyType < 0) {
11095 if(nr>=0 && !pairingReceived) {
11097 if(pairing.pr == NoProc) {
11098 if(!appData.pairingEngine[0]) {
11099 DisplayFatalError(_("No pairing engine specified"), 0, 1);
11102 StartChessProgram(&pairing); // starts the pairing engine
11104 snprintf(buf, 1<<16, "results %d %s\n", nPlayers, appData.results);
11105 SendToProgram(buf, &pairing);
11106 snprintf(buf, 1<<16, "pairing %d\n", nr+1);
11107 SendToProgram(buf, &pairing);
11108 return 0; // wait for pairing engine to answer (which causes NextTourneyGame to be called again...
11110 pairingReceived = 0; // ... so we continue here
11112 appData.matchGames = appData.tourneyCycles * syncInterval - 1;
11113 whitePlayer = savedWhitePlayer-1; blackPlayer = savedBlackPlayer-1;
11114 matchGame = 1; roundNr = nr / syncInterval + 1;
11117 if(first.pr != NoProc && second.pr != NoProc || nr<0) return 1; // engines already loaded
11119 // redefine engines, engine dir, etc.
11120 NamesToList(firstChessProgramNames, command, mnemonic, "all"); // get mnemonics of installed engines
11121 if(first.pr == NoProc) {
11122 if(!SetPlayer(whitePlayer, appData.participants)) OK = 0; // find white player amongst it, and parse its engine line
11123 InitEngine(&first, 0); // initialize ChessProgramStates based on new settings.
11125 if(second.pr == NoProc) {
11127 if(!SetPlayer(blackPlayer, appData.participants)) OK = 0; // find black player amongst it, and parse its engine line
11128 SwapEngines(1); // and make that valid for second engine by swapping
11129 InitEngine(&second, 1);
11131 CommonEngineInit(); // after this TwoMachinesEvent will create correct engine processes
11132 UpdateLogos(FALSE); // leave display to ModeHiglight()
11138 { // performs game initialization that does not invoke engines, and then tries to start the game
11139 int res, firstWhite, swapColors = 0;
11140 if(!NextTourneyGame(nextGame, &swapColors)) return; // this sets matchGame, -fcp / -scp and other options for next game, if needed
11141 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
11143 snprintf(buf, MSG_SIZ, appData.nameOfDebugFile, nextGame+1); // expand name of debug file with %d in it
11144 if(strcmp(buf, currentDebugFile)) { // name has changed
11145 FILE *f = fopen(buf, "w");
11146 if(f) { // if opening the new file failed, just keep using the old one
11147 ASSIGN(currentDebugFile, buf);
11151 if(appData.serverFileName) {
11152 if(serverFP) fclose(serverFP);
11153 serverFP = fopen(appData.serverFileName, "w");
11154 if(serverFP && first.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", first.tidy);
11155 if(serverFP && second.pr != NoProc) fprintf(serverFP, "StartChildProcess (dir=\".\") .\\%s\n", second.tidy);
11159 firstWhite = appData.firstPlaysBlack ^ (matchGame & 1 | appData.sameColorGames > 1); // non-incremental default
11160 firstWhite ^= swapColors; // reverses if NextTourneyGame says we are in an odd round
11161 first.twoMachinesColor = firstWhite ? "white\n" : "black\n"; // perform actual color assignement
11162 second.twoMachinesColor = firstWhite ? "black\n" : "white\n";
11163 appData.noChessProgram = (first.pr == NoProc); // kludge to prevent Reset from starting up chess program
11164 if(appData.loadGameIndex == -2) srandom(appData.seedBase + 68163*(nextGame & ~1)); // deterministic seed to force same opening
11165 Reset(FALSE, first.pr != NoProc);
11166 res = LoadGameOrPosition(matchGame); // setup game
11167 appData.noChessProgram = FALSE; // LoadGameOrPosition might call Reset too!
11168 if(!res) return; // abort when bad game/pos file
11169 TwoMachinesEvent();
11173 UserAdjudicationEvent (int result)
11175 ChessMove gameResult = GameIsDrawn;
11178 gameResult = WhiteWins;
11180 else if( result < 0 ) {
11181 gameResult = BlackWins;
11184 if( gameMode == TwoMachinesPlay ) {
11185 GameEnds( gameResult, "User adjudication", GE_XBOARD );
11190 // [HGM] save: calculate checksum of game to make games easily identifiable
11192 StringCheckSum (char *s)
11195 if(s==NULL) return 0;
11196 while(*s) i = i*259 + *s++;
11204 for(i=backwardMostMove; i<forwardMostMove; i++) {
11205 sum += pvInfoList[i].depth;
11206 sum += StringCheckSum(parseList[i]);
11207 sum += StringCheckSum(commentList[i]);
11210 if(i>1 && sum==0) sum++; // make sure never zero for non-empty game
11211 return sum + StringCheckSum(commentList[i]);
11212 } // end of save patch
11215 GameEnds (ChessMove result, char *resultDetails, int whosays)
11217 GameMode nextGameMode;
11219 char buf[MSG_SIZ], popupRequested = 0, *ranking = NULL;
11221 if(endingGame) return; /* [HGM] crash: forbid recursion */
11223 if(twoBoards) { // [HGM] dual: switch back to one board
11224 twoBoards = partnerUp = 0; InitDrawingSizes(-2, 0);
11225 DrawPosition(TRUE, partnerBoard); // observed game becomes foreground
11227 if (appData.debugMode) {
11228 fprintf(debugFP, "GameEnds(%d, %s, %d)\n",
11229 result, resultDetails ? resultDetails : "(null)", whosays);
11232 fromX = fromY = killX = killY = -1; // [HGM] abort any move the user is entering. // [HGM] lion
11234 if(pausing) PauseEvent(); // can happen when we abort a paused game (New Game or Quit)
11236 if (appData.icsActive && (whosays == GE_ENGINE || whosays >= GE_ENGINE1)) {
11237 /* If we are playing on ICS, the server decides when the
11238 game is over, but the engine can offer to draw, claim
11242 if (appData.zippyPlay && first.initDone) {
11243 if (result == GameIsDrawn) {
11244 /* In case draw still needs to be claimed */
11245 SendToICS(ics_prefix);
11246 SendToICS("draw\n");
11247 } else if (StrCaseStr(resultDetails, "resign")) {
11248 SendToICS(ics_prefix);
11249 SendToICS("resign\n");
11253 endingGame = 0; /* [HGM] crash */
11257 /* If we're loading the game from a file, stop */
11258 if (whosays == GE_FILE) {
11259 (void) StopLoadGameTimer();
11263 /* Cancel draw offers */
11264 first.offeredDraw = second.offeredDraw = 0;
11266 /* If this is an ICS game, only ICS can really say it's done;
11267 if not, anyone can. */
11268 isIcsGame = (gameMode == IcsPlayingWhite ||
11269 gameMode == IcsPlayingBlack ||
11270 gameMode == IcsObserving ||
11271 gameMode == IcsExamining);
11273 if (!isIcsGame || whosays == GE_ICS) {
11274 /* OK -- not an ICS game, or ICS said it was done */
11276 if (!isIcsGame && !appData.noChessProgram)
11277 SetUserThinkingEnables();
11279 /* [HGM] if a machine claims the game end we verify this claim */
11280 if(gameMode == TwoMachinesPlay && appData.testClaims) {
11281 if(appData.testLegality && whosays >= GE_ENGINE1 ) {
11283 ChessMove trueResult = (ChessMove) -1;
11285 claimer = whosays == GE_ENGINE1 ? /* color of claimer */
11286 first.twoMachinesColor[0] :
11287 second.twoMachinesColor[0] ;
11289 // [HGM] losers: because the logic is becoming a bit hairy, determine true result first
11290 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_CHECKMATE) {
11291 /* [HGM] verify: engine mate claims accepted if they were flagged */
11292 trueResult = WhiteOnMove(forwardMostMove) ? BlackWins : WhiteWins;
11294 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_WINS) { // added code for games where being mated is a win
11295 /* [HGM] verify: engine mate claims accepted if they were flagged */
11296 trueResult = WhiteOnMove(forwardMostMove) ? WhiteWins : BlackWins;
11298 if((signed char)boards[forwardMostMove][EP_STATUS] == EP_STALEMATE) { // only used to indicate draws now
11299 trueResult = GameIsDrawn; // default; in variants where stalemate loses, Status is CHECKMATE
11302 // now verify win claims, but not in drop games, as we don't understand those yet
11303 if( (gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
11304 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand) &&
11305 (result == WhiteWins && claimer == 'w' ||
11306 result == BlackWins && claimer == 'b' ) ) { // case to verify: engine claims own win
11307 if (appData.debugMode) {
11308 fprintf(debugFP, "result=%d sp=%d move=%d\n",
11309 result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove);
11311 if(result != trueResult) {
11312 snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails);
11313 result = claimer == 'w' ? BlackWins : WhiteWins;
11314 resultDetails = buf;
11317 if( result == GameIsDrawn && (signed char)boards[forwardMostMove][EP_STATUS] > EP_DRAWS
11318 && (forwardMostMove <= backwardMostMove ||
11319 (signed char)boards[forwardMostMove-1][EP_STATUS] > EP_DRAWS ||
11320 (claimer=='b')==(forwardMostMove&1))
11322 /* [HGM] verify: draws that were not flagged are false claims */
11323 snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails);
11324 result = claimer == 'w' ? BlackWins : WhiteWins;
11325 resultDetails = buf;
11327 /* (Claiming a loss is accepted no questions asked!) */
11328 } else if(matchMode && result == GameIsDrawn && !strcmp(resultDetails, "Engine Abort Request")) {
11329 forwardMostMove = backwardMostMove; // [HGM] delete game to surpress saving
11330 result = GameUnfinished;
11331 if(!*appData.tourneyFile) matchGame--; // replay even in plain match
11333 /* [HGM] bare: don't allow bare King to win */
11334 if((gameInfo.holdingsWidth == 0 || gameInfo.variant == VariantSuper
11335 || gameInfo.variant == VariantGreat || gameInfo.variant == VariantGrand)
11336 && gameInfo.variant != VariantLosers && gameInfo.variant != VariantGiveaway
11337 && gameInfo.variant != VariantSuicide // [HGM] losers: except in losers, of course...
11338 && result != GameIsDrawn)
11339 { int i, j, k=0, color = (result==WhiteWins ? (int)WhitePawn : (int)BlackPawn);
11340 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) for(i=0; i<BOARD_HEIGHT; i++) {
11341 int p = (signed char)boards[forwardMostMove][i][j] - color;
11342 if(p >= 0 && p <= (int)WhiteKing) k++;
11344 if (appData.debugMode) {
11345 fprintf(debugFP, "GE(%d, %s, %d) bare king k=%d color=%d\n",
11346 result, resultDetails ? resultDetails : "(null)", whosays, k, color);
11349 result = GameIsDrawn;
11350 snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails);
11351 resultDetails = buf;
11357 if(serverMoves != NULL && !loadFlag) { char c = '=';
11358 if(result==WhiteWins) c = '+';
11359 if(result==BlackWins) c = '-';
11360 if(resultDetails != NULL)
11361 fprintf(serverMoves, ";%c;%s\n", c, resultDetails), fflush(serverMoves);
11363 if (resultDetails != NULL) {
11364 gameInfo.result = result;
11365 gameInfo.resultDetails = StrSave(resultDetails);
11367 /* display last move only if game was not loaded from file */
11368 if ((whosays != GE_FILE) && (currentMove == forwardMostMove))
11369 DisplayMove(currentMove - 1);
11371 if (forwardMostMove != 0) {
11372 if (gameMode != PlayFromGameFile && gameMode != EditGame
11373 && lastSavedGame != GameCheckSum() // [HGM] save: suppress duplicates
11375 if (*appData.saveGameFile != NULLCHAR) {
11376 if(result == GameUnfinished && matchMode && *appData.tourneyFile)
11377 AutoSaveGame(); // [HGM] protect tourney PGN from aborted games, and prompt for name instead
11379 SaveGameToFile(appData.saveGameFile, TRUE);
11380 } else if (appData.autoSaveGames) {
11381 if(gameMode != IcsObserving || !appData.onlyOwn) AutoSaveGame();
11383 if (*appData.savePositionFile != NULLCHAR) {
11384 SavePositionToFile(appData.savePositionFile);
11386 AddGameToBook(FALSE); // Only does something during Monte-Carlo book building
11390 /* Tell program how game ended in case it is learning */
11391 /* [HGM] Moved this to after saving the PGN, just in case */
11392 /* engine died and we got here through time loss. In that */
11393 /* case we will get a fatal error writing the pipe, which */
11394 /* would otherwise lose us the PGN. */
11395 /* [HGM] crash: not needed anymore, but doesn't hurt; */
11396 /* output during GameEnds should never be fatal anymore */
11397 if (gameMode == MachinePlaysWhite ||
11398 gameMode == MachinePlaysBlack ||
11399 gameMode == TwoMachinesPlay ||
11400 gameMode == IcsPlayingWhite ||
11401 gameMode == IcsPlayingBlack ||
11402 gameMode == BeginningOfGame) {
11404 snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result),
11406 if (first.pr != NoProc) {
11407 SendToProgram(buf, &first);
11409 if (second.pr != NoProc &&
11410 gameMode == TwoMachinesPlay) {
11411 SendToProgram(buf, &second);
11416 if (appData.icsActive) {
11417 if (appData.quietPlay &&
11418 (gameMode == IcsPlayingWhite ||
11419 gameMode == IcsPlayingBlack)) {
11420 SendToICS(ics_prefix);
11421 SendToICS("set shout 1\n");
11423 nextGameMode = IcsIdle;
11424 ics_user_moved = FALSE;
11425 /* clean up premove. It's ugly when the game has ended and the
11426 * premove highlights are still on the board.
11429 gotPremove = FALSE;
11430 ClearPremoveHighlights();
11431 DrawPosition(FALSE, boards[currentMove]);
11433 if (whosays == GE_ICS) {
11436 if (gameMode == IcsPlayingWhite)
11438 else if(gameMode == IcsPlayingBlack)
11439 PlayIcsLossSound();
11442 if (gameMode == IcsPlayingBlack)
11444 else if(gameMode == IcsPlayingWhite)
11445 PlayIcsLossSound();
11448 PlayIcsDrawSound();
11451 PlayIcsUnfinishedSound();
11454 if(appData.quitNext) { ExitEvent(0); return; }
11455 } else if (gameMode == EditGame ||
11456 gameMode == PlayFromGameFile ||
11457 gameMode == AnalyzeMode ||
11458 gameMode == AnalyzeFile) {
11459 nextGameMode = gameMode;
11461 nextGameMode = EndOfGame;
11466 nextGameMode = gameMode;
11469 if (appData.noChessProgram) {
11470 gameMode = nextGameMode;
11472 endingGame = 0; /* [HGM] crash */
11477 /* Put first chess program into idle state */
11478 if (first.pr != NoProc &&
11479 (gameMode == MachinePlaysWhite ||
11480 gameMode == MachinePlaysBlack ||
11481 gameMode == TwoMachinesPlay ||
11482 gameMode == IcsPlayingWhite ||
11483 gameMode == IcsPlayingBlack ||
11484 gameMode == BeginningOfGame)) {
11485 SendToProgram("force\n", &first);
11486 if (first.usePing) {
11488 snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing);
11489 SendToProgram(buf, &first);
11492 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
11493 /* Kill off first chess program */
11494 if (first.isr != NULL)
11495 RemoveInputSource(first.isr);
11498 if (first.pr != NoProc) {
11500 DoSleep( appData.delayBeforeQuit );
11501 SendToProgram("quit\n", &first);
11502 DestroyChildProcess(first.pr, 4 + first.useSigterm);
11503 first.reload = TRUE;
11507 if (second.reuse) {
11508 /* Put second chess program into idle state */
11509 if (second.pr != NoProc &&
11510 gameMode == TwoMachinesPlay) {
11511 SendToProgram("force\n", &second);
11512 if (second.usePing) {
11514 snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing);
11515 SendToProgram(buf, &second);
11518 } else if (result != GameUnfinished || nextGameMode == IcsIdle) {
11519 /* Kill off second chess program */
11520 if (second.isr != NULL)
11521 RemoveInputSource(second.isr);
11524 if (second.pr != NoProc) {
11525 DoSleep( appData.delayBeforeQuit );
11526 SendToProgram("quit\n", &second);
11527 DestroyChildProcess(second.pr, 4 + second.useSigterm);
11528 second.reload = TRUE;
11530 second.pr = NoProc;
11533 if (matchMode && (gameMode == TwoMachinesPlay || (waitingForGame || startingEngine) && exiting)) {
11534 char resChar = '=';
11538 if (first.twoMachinesColor[0] == 'w') {
11541 second.matchWins++;
11546 if (first.twoMachinesColor[0] == 'b') {
11549 second.matchWins++;
11552 case GameUnfinished:
11558 if(exiting) resChar = ' '; // quit while waiting for round sync: unreserve already reserved game
11559 if(appData.tourneyFile[0]){ // [HGM] we are in a tourney; update tourney file with game result
11560 if(appData.afterGame && appData.afterGame[0]) RunCommand(appData.afterGame);
11561 ReserveGame(nextGame, resChar); // sets nextGame
11562 if(nextGame > appData.matchGames) appData.tourneyFile[0] = 0, ranking = TourneyStandings(3); // tourney is done
11563 else ranking = strdup("busy"); //suppress popup when aborted but not finished
11564 } else roundNr = nextGame = matchGame + 1; // normal match, just increment; round equals matchGame
11566 if (nextGame <= appData.matchGames && !abortMatch) {
11567 gameMode = nextGameMode;
11568 matchGame = nextGame; // this will be overruled in tourney mode!
11569 GetTimeMark(&pauseStart); // [HGM] matchpause: stipulate a pause
11570 ScheduleDelayedEvent(NextMatchGame, 10); // but start game immediately (as it will wait out the pause itself)
11571 endingGame = 0; /* [HGM] crash */
11574 gameMode = nextGameMode;
11575 snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"),
11576 first.tidy, second.tidy,
11577 first.matchWins, second.matchWins,
11578 appData.matchGames - (first.matchWins + second.matchWins));
11579 if(!appData.tourneyFile[0]) matchGame++, DisplayTwoMachinesTitle(); // [HGM] update result in window title
11580 if(ranking && strcmp(ranking, "busy") && appData.afterTourney && appData.afterTourney[0]) RunCommand(appData.afterTourney);
11581 popupRequested++; // [HGM] crash: postpone to after resetting endingGame
11582 if (appData.firstPlaysBlack) { // [HGM] match: back to original for next match
11583 first.twoMachinesColor = "black\n";
11584 second.twoMachinesColor = "white\n";
11586 first.twoMachinesColor = "white\n";
11587 second.twoMachinesColor = "black\n";
11591 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile) &&
11592 !(nextGameMode == AnalyzeMode || nextGameMode == AnalyzeFile))
11594 gameMode = nextGameMode;
11596 endingGame = 0; /* [HGM] crash */
11597 if(popupRequested) { // [HGM] crash: this calls GameEnds recursively through ExitEvent! Make it a harmless tail recursion.
11598 if(matchMode == TRUE) { // match through command line: exit with or without popup
11600 ToNrEvent(forwardMostMove);
11601 if(strcmp(ranking, "busy")) DisplayFatalError(ranking, 0, 0);
11603 } else DisplayFatalError(buf, 0, 0);
11604 } else { // match through menu; just stop, with or without popup
11605 matchMode = FALSE; appData.matchGames = matchGame = roundNr = 0;
11608 if(strcmp(ranking, "busy")) DisplayNote(ranking);
11609 } else DisplayNote(buf);
11611 if(ranking) free(ranking);
11615 /* Assumes program was just initialized (initString sent).
11616 Leaves program in force mode. */
11618 FeedMovesToProgram (ChessProgramState *cps, int upto)
11622 if (appData.debugMode)
11623 fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n",
11624 startedFromSetupPosition ? "position and " : "",
11625 backwardMostMove, upto, cps->which);
11626 if(currentlyInitializedVariant != gameInfo.variant) {
11628 // [HGM] variantswitch: make engine aware of new variant
11629 if(!SupportedVariant(cps->variants, gameInfo.variant, gameInfo.boardWidth,
11630 gameInfo.boardHeight, gameInfo.holdingsSize, cps->protocolVersion, ""))
11631 return; // [HGM] refrain from feeding moves altogether if variant is unsupported!
11632 snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant));
11633 SendToProgram(buf, cps);
11634 currentlyInitializedVariant = gameInfo.variant;
11636 SendToProgram("force\n", cps);
11637 if (startedFromSetupPosition) {
11638 SendBoard(cps, backwardMostMove);
11639 if (appData.debugMode) {
11640 fprintf(debugFP, "feedMoves\n");
11643 for (i = backwardMostMove; i < upto; i++) {
11644 SendMoveToProgram(i, cps);
11650 ResurrectChessProgram ()
11652 /* The chess program may have exited.
11653 If so, restart it and feed it all the moves made so far. */
11654 static int doInit = 0;
11656 if (appData.noChessProgram) return 1;
11658 if(matchMode /*&& appData.tourneyFile[0]*/) { // [HGM] tourney: make sure we get features after engine replacement. (Should we always do this?)
11659 if(WaitForEngine(&first, TwoMachinesEventIfReady)) { doInit = 1; return 0; } // request to do init on next visit, because we started engine
11660 if(!doInit) return 1; // this replaces testing first.pr != NoProc, which is true when we get here, but first time no reason to abort
11661 doInit = 0; // we fell through (first time after starting the engine); make sure it doesn't happen again
11663 if (first.pr != NoProc) return 1;
11664 StartChessProgram(&first);
11666 InitChessProgram(&first, FALSE);
11667 FeedMovesToProgram(&first, currentMove);
11669 if (!first.sendTime) {
11670 /* can't tell gnuchess what its clock should read,
11671 so we bow to its notion. */
11673 timeRemaining[0][currentMove] = whiteTimeRemaining;
11674 timeRemaining[1][currentMove] = blackTimeRemaining;
11677 if ((gameMode == AnalyzeMode || gameMode == AnalyzeFile ||
11678 appData.icsEngineAnalyze) && first.analysisSupport) {
11679 SendToProgram("analyze\n", &first);
11680 first.analyzing = TRUE;
11686 * Button procedures
11689 Reset (int redraw, int init)
11693 if (appData.debugMode) {
11694 fprintf(debugFP, "Reset(%d, %d) from gameMode %d\n",
11695 redraw, init, gameMode);
11697 pieceDefs = FALSE; // [HGM] gen: reset engine-defined piece moves
11698 for(i=0; i<EmptySquare; i++) { FREE(pieceDesc[i]); pieceDesc[i] = NULL; }
11699 CleanupTail(); // [HGM] vari: delete any stored variations
11700 CommentPopDown(); // [HGM] make sure no comments to the previous game keep hanging on
11701 pausing = pauseExamInvalid = FALSE;
11702 startedFromSetupPosition = blackPlaysFirst = FALSE;
11704 whiteFlag = blackFlag = FALSE;
11705 userOfferedDraw = FALSE;
11706 hintRequested = bookRequested = FALSE;
11707 first.maybeThinking = FALSE;
11708 second.maybeThinking = FALSE;
11709 first.bookSuspend = FALSE; // [HGM] book
11710 second.bookSuspend = FALSE;
11711 thinkOutput[0] = NULLCHAR;
11712 lastHint[0] = NULLCHAR;
11713 ClearGameInfo(&gameInfo);
11714 gameInfo.variant = StringToVariant(appData.variant);
11715 if(gameInfo.variant == VariantNormal && strcmp(appData.variant, "normal")) gameInfo.variant = VariantUnknown;
11716 ics_user_moved = ics_clock_paused = FALSE;
11717 ics_getting_history = H_FALSE;
11719 white_holding[0] = black_holding[0] = NULLCHAR;
11720 ClearProgramStats();
11721 opponentKibitzes = FALSE; // [HGM] kibitz: do not reserve space in engine-output window in zippy mode
11725 flipView = appData.flipView;
11726 ClearPremoveHighlights();
11727 gotPremove = FALSE;
11728 alarmSounded = FALSE;
11729 killX = killY = -1; // [HGM] lion
11731 GameEnds(EndOfFile, NULL, GE_PLAYER);
11732 if(appData.serverMovesName != NULL) {
11733 /* [HGM] prepare to make moves file for broadcasting */
11734 clock_t t = clock();
11735 if(serverMoves != NULL) fclose(serverMoves);
11736 serverMoves = fopen(appData.serverMovesName, "r");
11737 if(serverMoves != NULL) {
11738 fclose(serverMoves);
11739 /* delay 15 sec before overwriting, so all clients can see end */
11740 while(clock()-t < appData.serverPause*CLOCKS_PER_SEC);
11742 serverMoves = fopen(appData.serverMovesName, "w");
11746 gameMode = BeginningOfGame;
11748 if(appData.icsActive) gameInfo.variant = VariantNormal;
11749 currentMove = forwardMostMove = backwardMostMove = 0;
11750 MarkTargetSquares(1);
11751 InitPosition(redraw);
11752 for (i = 0; i < MAX_MOVES; i++) {
11753 if (commentList[i] != NULL) {
11754 free(commentList[i]);
11755 commentList[i] = NULL;
11759 timeRemaining[0][0] = whiteTimeRemaining;
11760 timeRemaining[1][0] = blackTimeRemaining;
11762 if (first.pr == NoProc) {
11763 StartChessProgram(&first);
11766 InitChessProgram(&first, startedFromSetupPosition);
11769 DisplayMessage("", "");
11770 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
11771 lastSavedGame = 0; // [HGM] save: make sure next game counts as unsaved
11772 ClearMap(); // [HGM] exclude: invalidate map
11776 AutoPlayGameLoop ()
11779 if (!AutoPlayOneMove())
11781 if (matchMode || appData.timeDelay == 0)
11783 if (appData.timeDelay < 0)
11785 StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
11793 ReloadGame(1); // next game
11799 int fromX, fromY, toX, toY;
11801 if (appData.debugMode) {
11802 fprintf(debugFP, "AutoPlayOneMove(): current %d\n", currentMove);
11805 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile)
11808 if (gameMode == AnalyzeFile && currentMove > backwardMostMove && programStats.depth) {
11809 pvInfoList[currentMove].depth = programStats.depth;
11810 pvInfoList[currentMove].score = programStats.score;
11811 pvInfoList[currentMove].time = 0;
11812 if(currentMove < forwardMostMove) AppendComment(currentMove+1, lastPV[0], 2);
11813 else { // append analysis of final position as comment
11815 snprintf(buf, MSG_SIZ, "{final score %+4.2f/%d}", programStats.score/100., programStats.depth);
11816 AppendComment(currentMove, buf, 3); // the 3 prevents stripping of the score/depth!
11818 programStats.depth = 0;
11821 if (currentMove >= forwardMostMove) {
11822 if(gameMode == AnalyzeFile) {
11823 if(appData.loadGameIndex == -1) {
11824 GameEnds(gameInfo.result, gameInfo.resultDetails ? gameInfo.resultDetails : "", GE_FILE);
11825 ScheduleDelayedEvent(AnalyzeNextGame, 10);
11827 ExitAnalyzeMode(); SendToProgram("force\n", &first);
11830 // gameMode = EndOfGame;
11831 // ModeHighlight();
11833 /* [AS] Clear current move marker at the end of a game */
11834 /* HistorySet(parseList, backwardMostMove, forwardMostMove, -1); */
11839 toX = moveList[currentMove][2] - AAA;
11840 toY = moveList[currentMove][3] - ONE;
11842 if (moveList[currentMove][1] == '@') {
11843 if (appData.highlightLastMove) {
11844 SetHighlights(-1, -1, toX, toY);
11847 int viaX = moveList[currentMove][5] - AAA;
11848 int viaY = moveList[currentMove][6] - ONE;
11849 fromX = moveList[currentMove][0] - AAA;
11850 fromY = moveList[currentMove][1] - ONE;
11852 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove); /* [AS] */
11854 if(moveList[currentMove][4] == ';') { // multi-leg
11855 ChessSquare piece = boards[currentMove][viaY][viaX];
11856 AnimateMove(boards[currentMove], fromX, fromY, viaX, viaY);
11857 boards[currentMove][viaY][viaX] = boards[currentMove][fromY][fromX];
11858 AnimateMove(boards[currentMove], fromX=viaX, fromY=viaY, toX, toY);
11859 boards[currentMove][viaY][viaX] = piece;
11861 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
11863 if (appData.highlightLastMove) {
11864 SetHighlights(fromX, fromY, toX, toY);
11867 DisplayMove(currentMove);
11868 SendMoveToProgram(currentMove++, &first);
11869 DisplayBothClocks();
11870 DrawPosition(FALSE, boards[currentMove]);
11871 // [HGM] PV info: always display, routine tests if empty
11872 DisplayComment(currentMove - 1, commentList[currentMove]);
11878 LoadGameOneMove (ChessMove readAhead)
11880 int fromX = 0, fromY = 0, toX = 0, toY = 0, done;
11881 char promoChar = NULLCHAR;
11882 ChessMove moveType;
11883 char move[MSG_SIZ];
11886 if (gameMode != PlayFromGameFile && gameMode != AnalyzeFile &&
11887 gameMode != AnalyzeMode && gameMode != Training) {
11892 yyboardindex = forwardMostMove;
11893 if (readAhead != EndOfFile) {
11894 moveType = readAhead;
11896 if (gameFileFP == NULL)
11898 moveType = (ChessMove) Myylex();
11902 switch (moveType) {
11904 if (appData.debugMode)
11905 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
11908 /* append the comment but don't display it */
11909 AppendComment(currentMove, p, FALSE);
11912 case WhiteCapturesEnPassant:
11913 case BlackCapturesEnPassant:
11914 case WhitePromotion:
11915 case BlackPromotion:
11916 case WhiteNonPromotion:
11917 case BlackNonPromotion:
11920 case WhiteKingSideCastle:
11921 case WhiteQueenSideCastle:
11922 case BlackKingSideCastle:
11923 case BlackQueenSideCastle:
11924 case WhiteKingSideCastleWild:
11925 case WhiteQueenSideCastleWild:
11926 case BlackKingSideCastleWild:
11927 case BlackQueenSideCastleWild:
11929 case WhiteHSideCastleFR:
11930 case WhiteASideCastleFR:
11931 case BlackHSideCastleFR:
11932 case BlackASideCastleFR:
11934 if (appData.debugMode)
11935 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
11936 fromX = currentMoveString[0] - AAA;
11937 fromY = currentMoveString[1] - ONE;
11938 toX = currentMoveString[2] - AAA;
11939 toY = currentMoveString[3] - ONE;
11940 promoChar = currentMoveString[4];
11941 if(promoChar == ';') promoChar = NULLCHAR;
11946 if (appData.debugMode)
11947 fprintf(debugFP, "Parsed %s into %s\n", yy_text, currentMoveString);
11948 fromX = moveType == WhiteDrop ?
11949 (int) CharToPiece(ToUpper(currentMoveString[0])) :
11950 (int) CharToPiece(ToLower(currentMoveString[0]));
11952 toX = currentMoveString[2] - AAA;
11953 toY = currentMoveString[3] - ONE;
11959 case GameUnfinished:
11960 if (appData.debugMode)
11961 fprintf(debugFP, "Parsed game end: %s\n", yy_text);
11962 p = strchr(yy_text, '{');
11963 if (p == NULL) p = strchr(yy_text, '(');
11966 if (p[0] == '0' || p[0] == '1' || p[0] == '*') p = "";
11968 q = strchr(p, *p == '{' ? '}' : ')');
11969 if (q != NULL) *q = NULLCHAR;
11972 while(q = strchr(p, '\n')) *q = ' '; // [HGM] crush linefeeds in result message
11973 GameEnds(moveType, p, GE_FILE);
11975 if (cmailMsgLoaded) {
11977 flipView = WhiteOnMove(currentMove);
11978 if (moveType == GameUnfinished) flipView = !flipView;
11979 if (appData.debugMode)
11980 fprintf(debugFP, "Setting flipView to %d\n", flipView) ;
11985 if (appData.debugMode)
11986 fprintf(debugFP, "Parser hit end of file\n");
11987 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
11993 if (WhiteOnMove(currentMove)) {
11994 GameEnds(BlackWins, "Black mates", GE_FILE);
11996 GameEnds(WhiteWins, "White mates", GE_FILE);
12000 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
12006 case MoveNumberOne:
12007 if (lastLoadGameStart == GNUChessGame) {
12008 /* GNUChessGames have numbers, but they aren't move numbers */
12009 if (appData.debugMode)
12010 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
12011 yy_text, (int) moveType);
12012 return LoadGameOneMove(EndOfFile); /* tail recursion */
12014 /* else fall thru */
12019 /* Reached start of next game in file */
12020 if (appData.debugMode)
12021 fprintf(debugFP, "Parsed start of next game: %s\n", yy_text);
12022 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
12028 if (WhiteOnMove(currentMove)) {
12029 GameEnds(BlackWins, "Black mates", GE_FILE);
12031 GameEnds(WhiteWins, "White mates", GE_FILE);
12035 GameEnds(GameIsDrawn, "Stalemate", GE_FILE);
12041 case PositionDiagram: /* should not happen; ignore */
12042 case ElapsedTime: /* ignore */
12043 case NAG: /* ignore */
12044 if (appData.debugMode)
12045 fprintf(debugFP, "Parser ignoring: '%s' (%d)\n",
12046 yy_text, (int) moveType);
12047 return LoadGameOneMove(EndOfFile); /* tail recursion */
12050 if (appData.testLegality) {
12051 if (appData.debugMode)
12052 fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text);
12053 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
12054 (forwardMostMove / 2) + 1,
12055 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12056 DisplayError(move, 0);
12059 if (appData.debugMode)
12060 fprintf(debugFP, "Parsed %s into IllegalMove %s\n",
12061 yy_text, currentMoveString);
12062 fromX = currentMoveString[0] - AAA;
12063 fromY = currentMoveString[1] - ONE;
12064 toX = currentMoveString[2] - AAA;
12065 toY = currentMoveString[3] - ONE;
12066 promoChar = currentMoveString[4];
12070 case AmbiguousMove:
12071 if (appData.debugMode)
12072 fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text);
12073 snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"),
12074 (forwardMostMove / 2) + 1,
12075 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12076 DisplayError(move, 0);
12081 case ImpossibleMove:
12082 if (appData.debugMode)
12083 fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text);
12084 snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"),
12085 (forwardMostMove / 2) + 1,
12086 WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text);
12087 DisplayError(move, 0);
12093 if (appData.matchMode || (appData.timeDelay == 0 && !pausing)) {
12094 DrawPosition(FALSE, boards[currentMove]);
12095 DisplayBothClocks();
12096 if (!appData.matchMode) // [HGM] PV info: routine tests if empty
12097 DisplayComment(currentMove - 1, commentList[currentMove]);
12099 (void) StopLoadGameTimer();
12101 cmailOldMove = forwardMostMove;
12104 /* currentMoveString is set as a side-effect of yylex */
12106 thinkOutput[0] = NULLCHAR;
12107 MakeMove(fromX, fromY, toX, toY, promoChar);
12108 killX = killY = -1; // [HGM] lion: used up
12109 currentMove = forwardMostMove;
12114 /* Load the nth game from the given file */
12116 LoadGameFromFile (char *filename, int n, char *title, int useList)
12121 if (strcmp(filename, "-") == 0) {
12125 f = fopen(filename, "rb");
12127 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
12128 DisplayError(buf, errno);
12132 if (fseek(f, 0, 0) == -1) {
12133 /* f is not seekable; probably a pipe */
12136 if (useList && n == 0) {
12137 int error = GameListBuild(f);
12139 DisplayError(_("Cannot build game list"), error);
12140 } else if (!ListEmpty(&gameList) &&
12141 ((ListGame *) gameList.tailPred)->number > 1) {
12142 GameListPopUp(f, title);
12149 return LoadGame(f, n, title, FALSE);
12154 MakeRegisteredMove ()
12156 int fromX, fromY, toX, toY;
12158 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
12159 switch (cmailMoveType[lastLoadGameNumber - 1]) {
12162 if (appData.debugMode)
12163 fprintf(debugFP, "Restoring %s for game %d\n",
12164 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
12166 thinkOutput[0] = NULLCHAR;
12167 safeStrCpy(moveList[currentMove], cmailMove[lastLoadGameNumber - 1], sizeof(moveList[currentMove])/sizeof(moveList[currentMove][0]));
12168 fromX = cmailMove[lastLoadGameNumber - 1][0] - AAA;
12169 fromY = cmailMove[lastLoadGameNumber - 1][1] - ONE;
12170 toX = cmailMove[lastLoadGameNumber - 1][2] - AAA;
12171 toY = cmailMove[lastLoadGameNumber - 1][3] - ONE;
12172 promoChar = cmailMove[lastLoadGameNumber - 1][4];
12173 MakeMove(fromX, fromY, toX, toY, promoChar);
12174 ShowMove(fromX, fromY, toX, toY);
12176 switch (MateTest(boards[currentMove], PosFlags(currentMove)) ) {
12183 if (WhiteOnMove(currentMove)) {
12184 GameEnds(BlackWins, "Black mates", GE_PLAYER);
12186 GameEnds(WhiteWins, "White mates", GE_PLAYER);
12191 GameEnds(GameIsDrawn, "Stalemate", GE_PLAYER);
12198 if (WhiteOnMove(currentMove)) {
12199 GameEnds(BlackWins, "White resigns", GE_PLAYER);
12201 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
12206 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
12217 /* Wrapper around LoadGame for use when a Cmail message is loaded */
12219 CmailLoadGame (FILE *f, int gameNumber, char *title, int useList)
12223 if (gameNumber > nCmailGames) {
12224 DisplayError(_("No more games in this message"), 0);
12227 if (f == lastLoadGameFP) {
12228 int offset = gameNumber - lastLoadGameNumber;
12230 cmailMsg[0] = NULLCHAR;
12231 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
12232 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
12233 nCmailMovesRegistered--;
12235 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
12236 if (cmailResult[lastLoadGameNumber - 1] == CMAIL_NEW_RESULT) {
12237 cmailResult[lastLoadGameNumber - 1] = CMAIL_NOT_RESULT;
12240 if (! RegisterMove()) return FALSE;
12244 retVal = LoadGame(f, gameNumber, title, useList);
12246 /* Make move registered during previous look at this game, if any */
12247 MakeRegisteredMove();
12249 if (cmailCommentList[lastLoadGameNumber - 1] != NULL) {
12250 commentList[currentMove]
12251 = StrSave(cmailCommentList[lastLoadGameNumber - 1]);
12252 DisplayComment(currentMove - 1, commentList[currentMove]);
12258 /* Support for LoadNextGame, LoadPreviousGame, ReloadSameGame */
12260 ReloadGame (int offset)
12262 int gameNumber = lastLoadGameNumber + offset;
12263 if (lastLoadGameFP == NULL) {
12264 DisplayError(_("No game has been loaded yet"), 0);
12267 if (gameNumber <= 0) {
12268 DisplayError(_("Can't back up any further"), 0);
12271 if (cmailMsgLoaded) {
12272 return CmailLoadGame(lastLoadGameFP, gameNumber,
12273 lastLoadGameTitle, lastLoadGameUseList);
12275 return LoadGame(lastLoadGameFP, gameNumber,
12276 lastLoadGameTitle, lastLoadGameUseList);
12280 int keys[EmptySquare+1];
12283 PositionMatches (Board b1, Board b2)
12286 switch(appData.searchMode) {
12287 case 1: return CompareWithRights(b1, b2);
12289 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12290 if(b2[r][f] != EmptySquare && b1[r][f] != b2[r][f]) return FALSE;
12294 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12295 if((b2[r][f] == WhitePawn || b2[r][f] == BlackPawn) && b1[r][f] != b2[r][f]) return FALSE;
12296 sum += keys[b1[r][f]] - keys[b2[r][f]];
12300 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12301 sum += keys[b1[r][f]] - keys[b2[r][f]];
12313 int pieceList[256], quickBoard[256];
12314 ChessSquare pieceType[256] = { EmptySquare };
12315 Board soughtBoard, reverseBoard, flipBoard, rotateBoard;
12316 int counts[EmptySquare], minSought[EmptySquare], minReverse[EmptySquare], maxSought[EmptySquare], maxReverse[EmptySquare];
12317 int soughtTotal, turn;
12318 Boolean epOK, flipSearch;
12321 unsigned char piece, to;
12324 #define DSIZE (250000)
12326 Move initialSpace[DSIZE+1000]; // gamble on that game will not be more than 500 moves
12327 Move *moveDatabase = initialSpace;
12328 unsigned int movePtr, dataSize = DSIZE;
12331 MakePieceList (Board board, int *counts)
12333 int r, f, n=Q_PROMO, total=0;
12334 for(r=0;r<EmptySquare;r++) counts[r] = 0; // piece-type counts
12335 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12336 int sq = f + (r<<4);
12337 if(board[r][f] == EmptySquare) quickBoard[sq] = 0; else {
12338 quickBoard[sq] = ++n;
12340 pieceType[n] = board[r][f];
12341 counts[board[r][f]]++;
12342 if(board[r][f] == WhiteKing) pieceList[1] = n; else
12343 if(board[r][f] == BlackKing) pieceList[2] = n; // remember which are Kings, for castling
12347 epOK = gameInfo.variant != VariantXiangqi && gameInfo.variant != VariantBerolina;
12352 PackMove (int fromX, int fromY, int toX, int toY, ChessSquare promoPiece)
12354 int sq = fromX + (fromY<<4);
12355 int piece = quickBoard[sq], rook;
12356 quickBoard[sq] = 0;
12357 moveDatabase[movePtr].to = pieceList[piece] = sq = toX + (toY<<4);
12358 if(piece == pieceList[1] && fromY == toY) {
12359 if((toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
12360 int from = toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT;
12361 moveDatabase[movePtr++].piece = Q_WCASTL;
12362 quickBoard[sq] = piece;
12363 piece = quickBoard[from]; quickBoard[from] = 0;
12364 moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
12365 } else if((rook = quickBoard[sq]) && pieceType[rook] == WhiteRook) { // FRC castling
12366 quickBoard[sq] = 0; // remove Rook
12367 moveDatabase[movePtr].to = sq = (toX>fromX ? BOARD_RGHT-2 : BOARD_LEFT+2); // King to-square
12368 moveDatabase[movePtr++].piece = Q_WCASTL;
12369 quickBoard[sq] = pieceList[1]; // put King
12371 moveDatabase[movePtr].to = pieceList[rook] = sq = toX>fromX ? sq-1 : sq+1;
12374 if(piece == pieceList[2] && fromY == toY) {
12375 if((toX > fromX+1 || toX < fromX-1) && fromX != BOARD_LEFT && fromX != BOARD_RGHT-1) {
12376 int from = (toX>fromX ? BOARD_RGHT-1 : BOARD_LEFT) + (BOARD_HEIGHT-1 <<4);
12377 moveDatabase[movePtr++].piece = Q_BCASTL;
12378 quickBoard[sq] = piece;
12379 piece = quickBoard[from]; quickBoard[from] = 0;
12380 moveDatabase[movePtr].to = pieceList[piece] = sq = toX>fromX ? sq-1 : sq+1;
12381 } else if((rook = quickBoard[sq]) && pieceType[rook] == BlackRook) { // FRC castling
12382 quickBoard[sq] = 0; // remove Rook
12383 moveDatabase[movePtr].to = sq = (toX>fromX ? BOARD_RGHT-2 : BOARD_LEFT+2);
12384 moveDatabase[movePtr++].piece = Q_BCASTL;
12385 quickBoard[sq] = pieceList[2]; // put King
12387 moveDatabase[movePtr].to = pieceList[rook] = sq = toX>fromX ? sq-1 : sq+1;
12390 if(epOK && (pieceType[piece] == WhitePawn || pieceType[piece] == BlackPawn) && fromX != toX && quickBoard[sq] == 0) {
12391 quickBoard[(fromY<<4)+toX] = 0;
12392 moveDatabase[movePtr].piece = Q_EP;
12393 moveDatabase[movePtr++].to = (fromY<<4)+toX;
12394 moveDatabase[movePtr].to = sq;
12396 if(promoPiece != pieceType[piece]) {
12397 moveDatabase[movePtr++].piece = Q_PROMO;
12398 moveDatabase[movePtr].to = pieceType[piece] = (int) promoPiece;
12400 moveDatabase[movePtr].piece = piece;
12401 quickBoard[sq] = piece;
12406 PackGame (Board board)
12408 Move *newSpace = NULL;
12409 moveDatabase[movePtr].piece = 0; // terminate previous game
12410 if(movePtr > dataSize) {
12411 if(appData.debugMode) fprintf(debugFP, "move-cache overflow, enlarge to %d MB\n", dataSize/128);
12412 dataSize *= 8; // increase size by factor 8 (512KB -> 4MB -> 32MB -> 256MB -> 2GB)
12413 if(dataSize) newSpace = (Move*) calloc(dataSize + 1000, sizeof(Move));
12416 Move *p = moveDatabase, *q = newSpace;
12417 for(i=0; i<movePtr; i++) *q++ = *p++; // copy to newly allocated space
12418 if(dataSize > 8*DSIZE) free(moveDatabase); // and free old space (if it was allocated)
12419 moveDatabase = newSpace;
12420 } else { // calloc failed, we must be out of memory. Too bad...
12421 dataSize = 0; // prevent calloc events for all subsequent games
12422 return 0; // and signal this one isn't cached
12426 MakePieceList(board, counts);
12431 QuickCompare (Board board, int *minCounts, int *maxCounts)
12432 { // compare according to search mode
12434 switch(appData.searchMode)
12436 case 1: // exact position match
12437 if(!(turn & board[EP_STATUS-1])) return FALSE; // wrong side to move
12438 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12439 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12442 case 2: // can have extra material on empty squares
12443 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12444 if(board[r][f] == EmptySquare) continue;
12445 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12448 case 3: // material with exact Pawn structure
12449 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12450 if(board[r][f] != WhitePawn && board[r][f] != BlackPawn) continue;
12451 if(board[r][f] != pieceType[quickBoard[(r<<4)+f]]) return FALSE;
12452 } // fall through to material comparison
12453 case 4: // exact material
12454 for(r=0; r<EmptySquare; r++) if(counts[r] != maxCounts[r]) return FALSE;
12456 case 6: // material range with given imbalance
12457 for(r=0; r<BlackPawn; r++) if(counts[r] - minCounts[r] != counts[r+BlackPawn] - minCounts[r+BlackPawn]) return FALSE;
12458 // fall through to range comparison
12459 case 5: // material range
12460 for(r=0; r<EmptySquare; r++) if(counts[r] < minCounts[r] || counts[r] > maxCounts[r]) return FALSE;
12466 QuickScan (Board board, Move *move)
12467 { // reconstruct game,and compare all positions in it
12468 int cnt=0, stretch=0, found = -1, total = MakePieceList(board, counts);
12470 int piece = move->piece;
12471 int to = move->to, from = pieceList[piece];
12472 if(found < 0) { // if already found just scan to game end for final piece count
12473 if(QuickCompare(soughtBoard, minSought, maxSought) ||
12474 appData.ignoreColors && QuickCompare(reverseBoard, minReverse, maxReverse) ||
12475 flipSearch && (QuickCompare(flipBoard, minSought, maxSought) ||
12476 appData.ignoreColors && QuickCompare(rotateBoard, minReverse, maxReverse))
12478 static int lastCounts[EmptySquare+1];
12480 if(stretch) for(i=0; i<EmptySquare; i++) if(lastCounts[i] != counts[i]) { stretch = 0; break; } // reset if material changes
12481 if(stretch++ == 0) for(i=0; i<EmptySquare; i++) lastCounts[i] = counts[i]; // remember actual material
12482 } else stretch = 0;
12483 if(stretch && (appData.searchMode == 1 || stretch >= appData.stretch)) found = cnt + 1 - stretch;
12484 if(found >= 0 && !appData.minPieces) return found;
12486 if(piece <= Q_PROMO) { // special moves encoded by otherwise invalid piece numbers 1-4
12487 if(!piece) return (appData.minPieces && (total < appData.minPieces || total > appData.maxPieces) ? -1 : found);
12488 if(piece == Q_PROMO) { // promotion, encoded as (Q_PROMO, to) + (piece, promoType)
12489 piece = (++move)->piece;
12490 from = pieceList[piece];
12491 counts[pieceType[piece]]--;
12492 pieceType[piece] = (ChessSquare) move->to;
12493 counts[move->to]++;
12494 } else if(piece == Q_EP) { // e.p. capture, encoded as (Q_EP, ep-sqr) + (piece, to)
12495 counts[pieceType[quickBoard[to]]]--;
12496 quickBoard[to] = 0; total--;
12499 } else if(piece <= Q_BCASTL) { // castling, encoded as (Q_XCASTL, king-to) + (rook, rook-to)
12500 piece = pieceList[piece]; // first two elements of pieceList contain King numbers
12501 from = pieceList[piece]; // so this must be King
12502 quickBoard[from] = 0;
12503 pieceList[piece] = to;
12504 from = pieceList[(++move)->piece]; // for FRC this has to be done here
12505 quickBoard[from] = 0; // rook
12506 quickBoard[to] = piece;
12507 to = move->to; piece = move->piece;
12511 if(appData.searchMode > 2) counts[pieceType[quickBoard[to]]]--; // account capture
12512 if((total -= (quickBoard[to] != 0)) < soughtTotal && found < 0) return -1; // piece count dropped below what we search for
12513 quickBoard[from] = 0;
12515 quickBoard[to] = piece;
12516 pieceList[piece] = to;
12526 flipSearch = FALSE;
12527 CopyBoard(soughtBoard, boards[currentMove]);
12528 soughtTotal = MakePieceList(soughtBoard, maxSought);
12529 soughtBoard[EP_STATUS-1] = (currentMove & 1) + 1;
12530 if(currentMove == 0 && gameMode == EditPosition) soughtBoard[EP_STATUS-1] = blackPlaysFirst + 1; // (!)
12531 CopyBoard(reverseBoard, boards[currentMove]);
12532 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12533 int piece = boards[currentMove][BOARD_HEIGHT-1-r][f];
12534 if(piece < BlackPawn) piece += BlackPawn; else if(piece < EmptySquare) piece -= BlackPawn; // color-flip
12535 reverseBoard[r][f] = piece;
12537 reverseBoard[EP_STATUS-1] = soughtBoard[EP_STATUS-1] ^ 3;
12538 for(r=0; r<6; r++) reverseBoard[CASTLING][r] = boards[currentMove][CASTLING][(r+3)%6];
12539 if(appData.findMirror && appData.searchMode <= 3 && (!nrCastlingRights
12540 || (boards[currentMove][CASTLING][2] == NoRights ||
12541 boards[currentMove][CASTLING][0] == NoRights && boards[currentMove][CASTLING][1] == NoRights )
12542 && (boards[currentMove][CASTLING][5] == NoRights ||
12543 boards[currentMove][CASTLING][3] == NoRights && boards[currentMove][CASTLING][4] == NoRights ) )
12546 CopyBoard(flipBoard, soughtBoard);
12547 CopyBoard(rotateBoard, reverseBoard);
12548 for(r=0; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) {
12549 flipBoard[r][f] = soughtBoard[r][BOARD_WIDTH-1-f];
12550 rotateBoard[r][f] = reverseBoard[r][BOARD_WIDTH-1-f];
12553 for(r=0; r<BlackPawn; r++) maxReverse[r] = maxSought[r+BlackPawn], maxReverse[r+BlackPawn] = maxSought[r];
12554 if(appData.searchMode >= 5) {
12555 for(r=BOARD_HEIGHT/2; r<BOARD_HEIGHT; r++) for(f=BOARD_LEFT; f<BOARD_RGHT; f++) soughtBoard[r][f] = EmptySquare;
12556 MakePieceList(soughtBoard, minSought);
12557 for(r=0; r<BlackPawn; r++) minReverse[r] = minSought[r+BlackPawn], minReverse[r+BlackPawn] = minSought[r];
12559 if(gameInfo.variant == VariantCrazyhouse || gameInfo.variant == VariantShogi || gameInfo.variant == VariantBughouse)
12560 soughtTotal = 0; // in drop games nr of pieces does not fall monotonously
12563 GameInfo dummyInfo;
12564 static int creatingBook;
12567 GameContainsPosition (FILE *f, ListGame *lg)
12569 int next, btm=0, plyNr=0, scratch=forwardMostMove+2&~1;
12570 int fromX, fromY, toX, toY;
12572 static int initDone=FALSE;
12574 // weed out games based on numerical tag comparison
12575 if(lg->gameInfo.variant != gameInfo.variant) return -1; // wrong variant
12576 if(appData.eloThreshold1 && (lg->gameInfo.whiteRating < appData.eloThreshold1 && lg->gameInfo.blackRating < appData.eloThreshold1)) return -1;
12577 if(appData.eloThreshold2 && (lg->gameInfo.whiteRating < appData.eloThreshold2 || lg->gameInfo.blackRating < appData.eloThreshold2)) return -1;
12578 if(appData.dateThreshold && (!lg->gameInfo.date || atoi(lg->gameInfo.date) < appData.dateThreshold)) return -1;
12580 for(next = WhitePawn; next<EmptySquare; next++) keys[next] = random()>>8 ^ random()<<6 ^random()<<20;
12583 if(lg->gameInfo.fen) ParseFEN(boards[scratch], &btm, lg->gameInfo.fen, FALSE);
12584 else CopyBoard(boards[scratch], initialPosition); // default start position
12587 if((next = QuickScan( boards[scratch], &moveDatabase[lg->moves] )) < 0) return -1; // quick scan rules out it is there
12588 if(appData.searchMode >= 4) return next; // for material searches, trust QuickScan.
12591 if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
12592 fseek(f, lg->offset, 0);
12595 yyboardindex = scratch;
12596 quickFlag = plyNr+1;
12601 if(plyNr) return -1; // after we have seen moves, any tags will be start of next game
12607 if(plyNr) return -1; // after we have seen moves, this is for new game
12610 case AmbiguousMove: // we cannot reconstruct the game beyond these two
12611 case ImpossibleMove:
12612 case WhiteWins: // game ends here with these four
12615 case GameUnfinished:
12619 if(appData.testLegality) return -1;
12620 case WhiteCapturesEnPassant:
12621 case BlackCapturesEnPassant:
12622 case WhitePromotion:
12623 case BlackPromotion:
12624 case WhiteNonPromotion:
12625 case BlackNonPromotion:
12628 case WhiteKingSideCastle:
12629 case WhiteQueenSideCastle:
12630 case BlackKingSideCastle:
12631 case BlackQueenSideCastle:
12632 case WhiteKingSideCastleWild:
12633 case WhiteQueenSideCastleWild:
12634 case BlackKingSideCastleWild:
12635 case BlackQueenSideCastleWild:
12636 case WhiteHSideCastleFR:
12637 case WhiteASideCastleFR:
12638 case BlackHSideCastleFR:
12639 case BlackASideCastleFR:
12640 fromX = currentMoveString[0] - AAA;
12641 fromY = currentMoveString[1] - ONE;
12642 toX = currentMoveString[2] - AAA;
12643 toY = currentMoveString[3] - ONE;
12644 promoChar = currentMoveString[4];
12648 fromX = next == WhiteDrop ?
12649 (int) CharToPiece(ToUpper(currentMoveString[0])) :
12650 (int) CharToPiece(ToLower(currentMoveString[0]));
12652 toX = currentMoveString[2] - AAA;
12653 toY = currentMoveString[3] - ONE;
12657 // Move encountered; peform it. We need to shuttle between two boards, as even/odd index determines side to move
12659 ApplyMove(fromX, fromY, toX, toY, promoChar, boards[scratch]);
12660 if(PositionMatches(boards[scratch], boards[currentMove])) return plyNr;
12661 if(appData.ignoreColors && PositionMatches(boards[scratch], reverseBoard)) return plyNr;
12662 if(appData.findMirror) {
12663 if(PositionMatches(boards[scratch], flipBoard)) return plyNr;
12664 if(appData.ignoreColors && PositionMatches(boards[scratch], rotateBoard)) return plyNr;
12669 /* Load the nth game from open file f */
12671 LoadGame (FILE *f, int gameNumber, char *title, int useList)
12675 int gn = gameNumber;
12676 ListGame *lg = NULL;
12677 int numPGNTags = 0;
12679 GameMode oldGameMode;
12680 VariantClass oldVariant = gameInfo.variant; /* [HGM] PGNvariant */
12682 if (appData.debugMode)
12683 fprintf(debugFP, "LoadGame(): on entry, gameMode %d\n", gameMode);
12685 if (gameMode == Training )
12686 SetTrainingModeOff();
12688 oldGameMode = gameMode;
12689 if (gameMode != BeginningOfGame) {
12690 Reset(FALSE, TRUE);
12692 killX = killY = -1; // [HGM] lion: in case we did not Reset
12695 if (lastLoadGameFP != NULL && lastLoadGameFP != f) {
12696 fclose(lastLoadGameFP);
12700 lg = (ListGame *) ListElem(&gameList, gameNumber-1);
12703 fseek(f, lg->offset, 0);
12704 GameListHighlight(gameNumber);
12705 pos = lg->position;
12709 if(oldGameMode == AnalyzeFile && appData.loadGameIndex == -1)
12710 appData.loadGameIndex = 0; // [HGM] suppress error message if we reach file end after auto-stepping analysis
12712 DisplayError(_("Game number out of range"), 0);
12717 if (fseek(f, 0, 0) == -1) {
12718 if (f == lastLoadGameFP ?
12719 gameNumber == lastLoadGameNumber + 1 :
12723 DisplayError(_("Can't seek on game file"), 0);
12728 lastLoadGameFP = f;
12729 lastLoadGameNumber = gameNumber;
12730 safeStrCpy(lastLoadGameTitle, title, sizeof(lastLoadGameTitle)/sizeof(lastLoadGameTitle[0]));
12731 lastLoadGameUseList = useList;
12735 if (lg && lg->gameInfo.white && lg->gameInfo.black) {
12736 snprintf(buf, sizeof(buf), "%s %s %s", lg->gameInfo.white, _("vs."),
12737 lg->gameInfo.black);
12739 } else if (*title != NULLCHAR) {
12740 if (gameNumber > 1) {
12741 snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber);
12744 DisplayTitle(title);
12748 if (gameMode != AnalyzeFile && gameMode != AnalyzeMode) {
12749 gameMode = PlayFromGameFile;
12753 currentMove = forwardMostMove = backwardMostMove = 0;
12754 CopyBoard(boards[0], initialPosition);
12758 * Skip the first gn-1 games in the file.
12759 * Also skip over anything that precedes an identifiable
12760 * start of game marker, to avoid being confused by
12761 * garbage at the start of the file. Currently
12762 * recognized start of game markers are the move number "1",
12763 * the pattern "gnuchess .* game", the pattern
12764 * "^[#;%] [^ ]* game file", and a PGN tag block.
12765 * A game that starts with one of the latter two patterns
12766 * will also have a move number 1, possibly
12767 * following a position diagram.
12768 * 5-4-02: Let's try being more lenient and allowing a game to
12769 * start with an unnumbered move. Does that break anything?
12771 cm = lastLoadGameStart = EndOfFile;
12773 yyboardindex = forwardMostMove;
12774 cm = (ChessMove) Myylex();
12777 if (cmailMsgLoaded) {
12778 nCmailGames = CMAIL_MAX_GAMES - gn;
12781 DisplayError(_("Game not found in file"), 0);
12788 lastLoadGameStart = cm;
12791 case MoveNumberOne:
12792 switch (lastLoadGameStart) {
12797 case MoveNumberOne:
12799 gn--; /* count this game */
12800 lastLoadGameStart = cm;
12809 switch (lastLoadGameStart) {
12812 case MoveNumberOne:
12814 gn--; /* count this game */
12815 lastLoadGameStart = cm;
12818 lastLoadGameStart = cm; /* game counted already */
12826 yyboardindex = forwardMostMove;
12827 cm = (ChessMove) Myylex();
12828 } while (cm == PGNTag || cm == Comment);
12835 if (cmailMsgLoaded && (CMAIL_MAX_GAMES == lastLoadGameNumber)) {
12836 if ( cmailResult[CMAIL_MAX_GAMES - gn - 1]
12837 != CMAIL_OLD_RESULT) {
12839 cmailResult[ CMAIL_MAX_GAMES
12840 - gn - 1] = CMAIL_OLD_RESULT;
12847 /* Only a NormalMove can be at the start of a game
12848 * without a position diagram. */
12849 if (lastLoadGameStart == EndOfFile ) {
12851 lastLoadGameStart = MoveNumberOne;
12860 if (appData.debugMode)
12861 fprintf(debugFP, "Parsed game start '%s' (%d)\n", yy_text, (int) cm);
12863 if (cm == XBoardGame) {
12864 /* Skip any header junk before position diagram and/or move 1 */
12866 yyboardindex = forwardMostMove;
12867 cm = (ChessMove) Myylex();
12869 if (cm == EndOfFile ||
12870 cm == GNUChessGame || cm == XBoardGame) {
12871 /* Empty game; pretend end-of-file and handle later */
12876 if (cm == MoveNumberOne || cm == PositionDiagram ||
12877 cm == PGNTag || cm == Comment)
12880 } else if (cm == GNUChessGame) {
12881 if (gameInfo.event != NULL) {
12882 free(gameInfo.event);
12884 gameInfo.event = StrSave(yy_text);
12887 startedFromSetupPosition = FALSE;
12888 while (cm == PGNTag) {
12889 if (appData.debugMode)
12890 fprintf(debugFP, "Parsed PGNTag: %s\n", yy_text);
12891 err = ParsePGNTag(yy_text, &gameInfo);
12892 if (!err) numPGNTags++;
12894 /* [HGM] PGNvariant: automatically switch to variant given in PGN tag */
12895 if(gameInfo.variant != oldVariant && (gameInfo.variant != VariantNormal || gameInfo.variantName == NULL || *gameInfo.variantName == NULLCHAR)) {
12896 startedFromPositionFile = FALSE; /* [HGM] loadPos: variant switch likely makes position invalid */
12897 ResetFrontEnd(); // [HGM] might need other bitmaps. Cannot use Reset() because it clears gameInfo :-(
12898 InitPosition(TRUE);
12899 oldVariant = gameInfo.variant;
12900 if (appData.debugMode)
12901 fprintf(debugFP, "New variant %d\n", (int) oldVariant);
12905 if (gameInfo.fen != NULL) {
12906 Board initial_position;
12907 startedFromSetupPosition = TRUE;
12908 if (!ParseFEN(initial_position, &blackPlaysFirst, gameInfo.fen, TRUE)) {
12910 DisplayError(_("Bad FEN position in file"), 0);
12913 CopyBoard(boards[0], initial_position);
12914 if(*engineVariant) // [HGM] for now, assume FEN in engine-defined variant game is default initial position
12915 CopyBoard(initialPosition, initial_position);
12916 if (blackPlaysFirst) {
12917 currentMove = forwardMostMove = backwardMostMove = 1;
12918 CopyBoard(boards[1], initial_position);
12919 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
12920 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
12921 timeRemaining[0][1] = whiteTimeRemaining;
12922 timeRemaining[1][1] = blackTimeRemaining;
12923 if (commentList[0] != NULL) {
12924 commentList[1] = commentList[0];
12925 commentList[0] = NULL;
12928 currentMove = forwardMostMove = backwardMostMove = 0;
12930 /* [HGM] copy FEN attributes as well. Bugfix 4.3.14m and 4.3.15e: moved to after 'blackPlaysFirst' */
12932 initialRulePlies = FENrulePlies;
12933 for( i=0; i< nrCastlingRights; i++ )
12934 initialRights[i] = initial_position[CASTLING][i];
12936 yyboardindex = forwardMostMove;
12937 free(gameInfo.fen);
12938 gameInfo.fen = NULL;
12941 yyboardindex = forwardMostMove;
12942 cm = (ChessMove) Myylex();
12944 /* Handle comments interspersed among the tags */
12945 while (cm == Comment) {
12947 if (appData.debugMode)
12948 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
12950 AppendComment(currentMove, p, FALSE);
12951 yyboardindex = forwardMostMove;
12952 cm = (ChessMove) Myylex();
12956 /* don't rely on existence of Event tag since if game was
12957 * pasted from clipboard the Event tag may not exist
12959 if (numPGNTags > 0){
12961 if (gameInfo.variant == VariantNormal) {
12962 VariantClass v = StringToVariant(gameInfo.event);
12963 // [HGM] do not recognize variants from event tag that were introduced after supporting variant tag
12964 if(v < VariantShogi) gameInfo.variant = v;
12967 if( appData.autoDisplayTags ) {
12968 tags = PGNTags(&gameInfo);
12969 TagsPopUp(tags, CmailMsg());
12974 /* Make something up, but don't display it now */
12979 if (cm == PositionDiagram) {
12982 Board initial_position;
12984 if (appData.debugMode)
12985 fprintf(debugFP, "Parsed PositionDiagram: %s\n", yy_text);
12987 if (!startedFromSetupPosition) {
12989 for (i = BOARD_HEIGHT - 1; i >= 0; i--)
12990 for (j = BOARD_LEFT; j < BOARD_RGHT; p++)
13001 initial_position[i][j++] = CharToPiece(*p);
13004 while (*p == ' ' || *p == '\t' ||
13005 *p == '\n' || *p == '\r') p++;
13007 if (strncmp(p, "black", strlen("black"))==0)
13008 blackPlaysFirst = TRUE;
13010 blackPlaysFirst = FALSE;
13011 startedFromSetupPosition = TRUE;
13013 CopyBoard(boards[0], initial_position);
13014 if (blackPlaysFirst) {
13015 currentMove = forwardMostMove = backwardMostMove = 1;
13016 CopyBoard(boards[1], initial_position);
13017 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13018 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13019 timeRemaining[0][1] = whiteTimeRemaining;
13020 timeRemaining[1][1] = blackTimeRemaining;
13021 if (commentList[0] != NULL) {
13022 commentList[1] = commentList[0];
13023 commentList[0] = NULL;
13026 currentMove = forwardMostMove = backwardMostMove = 0;
13029 yyboardindex = forwardMostMove;
13030 cm = (ChessMove) Myylex();
13033 if(!creatingBook) {
13034 if (first.pr == NoProc) {
13035 StartChessProgram(&first);
13037 InitChessProgram(&first, FALSE);
13038 SendToProgram("force\n", &first);
13039 if (startedFromSetupPosition) {
13040 SendBoard(&first, forwardMostMove);
13041 if (appData.debugMode) {
13042 fprintf(debugFP, "Load Game\n");
13044 DisplayBothClocks();
13048 /* [HGM] server: flag to write setup moves in broadcast file as one */
13049 loadFlag = appData.suppressLoadMoves;
13051 while (cm == Comment) {
13053 if (appData.debugMode)
13054 fprintf(debugFP, "Parsed Comment: %s\n", yy_text);
13056 AppendComment(currentMove, p, FALSE);
13057 yyboardindex = forwardMostMove;
13058 cm = (ChessMove) Myylex();
13061 if ((cm == EndOfFile && lastLoadGameStart != EndOfFile ) ||
13062 cm == WhiteWins || cm == BlackWins ||
13063 cm == GameIsDrawn || cm == GameUnfinished) {
13064 DisplayMessage("", _("No moves in game"));
13065 if (cmailMsgLoaded) {
13066 if (appData.debugMode)
13067 fprintf(debugFP, "Setting flipView to %d.\n", FALSE);
13071 DrawPosition(FALSE, boards[currentMove]);
13072 DisplayBothClocks();
13073 gameMode = EditGame;
13080 // [HGM] PV info: routine tests if comment empty
13081 if (!matchMode && (pausing || appData.timeDelay != 0)) {
13082 DisplayComment(currentMove - 1, commentList[currentMove]);
13084 if (!matchMode && appData.timeDelay != 0)
13085 DrawPosition(FALSE, boards[currentMove]);
13087 if (gameMode == AnalyzeFile || gameMode == AnalyzeMode) {
13088 programStats.ok_to_send = 1;
13091 /* if the first token after the PGN tags is a move
13092 * and not move number 1, retrieve it from the parser
13094 if (cm != MoveNumberOne)
13095 LoadGameOneMove(cm);
13097 /* load the remaining moves from the file */
13098 while (LoadGameOneMove(EndOfFile)) {
13099 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
13100 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
13103 /* rewind to the start of the game */
13104 currentMove = backwardMostMove;
13106 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
13108 if (oldGameMode == AnalyzeFile) {
13109 appData.loadGameIndex = -1; // [HGM] order auto-stepping through games
13110 AnalyzeFileEvent();
13112 if (oldGameMode == AnalyzeMode) {
13113 AnalyzeFileEvent();
13116 if(gameInfo.result == GameUnfinished && gameInfo.resultDetails && appData.clockMode) {
13117 long int w, b; // [HGM] adjourn: restore saved clock times
13118 char *p = strstr(gameInfo.resultDetails, "(Clocks:");
13119 if(p && sscanf(p+8, "%ld,%ld", &w, &b) == 2) {
13120 timeRemaining[0][forwardMostMove] = whiteTimeRemaining = 1000*w + 500;
13121 timeRemaining[1][forwardMostMove] = blackTimeRemaining = 1000*b + 500;
13125 if(creatingBook) return TRUE;
13126 if (!matchMode && pos > 0) {
13127 ToNrEvent(pos); // [HGM] no autoplay if selected on position
13129 if (matchMode || appData.timeDelay == 0) {
13131 } else if (appData.timeDelay > 0) {
13132 AutoPlayGameLoop();
13135 if (appData.debugMode)
13136 fprintf(debugFP, "LoadGame(): on exit, gameMode %d\n", gameMode);
13138 loadFlag = 0; /* [HGM] true game starts */
13142 /* Support for LoadNextPosition, LoadPreviousPosition, ReloadSamePosition */
13144 ReloadPosition (int offset)
13146 int positionNumber = lastLoadPositionNumber + offset;
13147 if (lastLoadPositionFP == NULL) {
13148 DisplayError(_("No position has been loaded yet"), 0);
13151 if (positionNumber <= 0) {
13152 DisplayError(_("Can't back up any further"), 0);
13155 return LoadPosition(lastLoadPositionFP, positionNumber,
13156 lastLoadPositionTitle);
13159 /* Load the nth position from the given file */
13161 LoadPositionFromFile (char *filename, int n, char *title)
13166 if (strcmp(filename, "-") == 0) {
13167 return LoadPosition(stdin, n, "stdin");
13169 f = fopen(filename, "rb");
13171 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13172 DisplayError(buf, errno);
13175 return LoadPosition(f, n, title);
13180 /* Load the nth position from the given open file, and close it */
13182 LoadPosition (FILE *f, int positionNumber, char *title)
13184 char *p, line[MSG_SIZ];
13185 Board initial_position;
13186 int i, j, fenMode, pn;
13188 if (gameMode == Training )
13189 SetTrainingModeOff();
13191 if (gameMode != BeginningOfGame) {
13192 Reset(FALSE, TRUE);
13194 if (lastLoadPositionFP != NULL && lastLoadPositionFP != f) {
13195 fclose(lastLoadPositionFP);
13197 if (positionNumber == 0) positionNumber = 1;
13198 lastLoadPositionFP = f;
13199 lastLoadPositionNumber = positionNumber;
13200 safeStrCpy(lastLoadPositionTitle, title, sizeof(lastLoadPositionTitle)/sizeof(lastLoadPositionTitle[0]));
13201 if (first.pr == NoProc && !appData.noChessProgram) {
13202 StartChessProgram(&first);
13203 InitChessProgram(&first, FALSE);
13205 pn = positionNumber;
13206 if (positionNumber < 0) {
13207 /* Negative position number means to seek to that byte offset */
13208 if (fseek(f, -positionNumber, 0) == -1) {
13209 DisplayError(_("Can't seek on position file"), 0);
13214 if (fseek(f, 0, 0) == -1) {
13215 if (f == lastLoadPositionFP ?
13216 positionNumber == lastLoadPositionNumber + 1 :
13217 positionNumber == 1) {
13220 DisplayError(_("Can't seek on position file"), 0);
13225 /* See if this file is FEN or old-style xboard */
13226 if (fgets(line, MSG_SIZ, f) == NULL) {
13227 DisplayError(_("Position not found in file"), 0);
13230 // [HGM] FEN can begin with digit, any piece letter valid in this variant, or a + for Shogi promoted pieces
13231 fenMode = line[0] >= '0' && line[0] <= '9' || line[0] == '+' || CharToPiece(line[0]) != EmptySquare;
13234 if (fenMode || line[0] == '#') pn--;
13236 /* skip positions before number pn */
13237 if (fgets(line, MSG_SIZ, f) == NULL) {
13239 DisplayError(_("Position not found in file"), 0);
13242 if (fenMode || line[0] == '#') pn--;
13247 if (!ParseFEN(initial_position, &blackPlaysFirst, line, TRUE)) {
13248 DisplayError(_("Bad FEN position in file"), 0);
13252 (void) fgets(line, MSG_SIZ, f);
13253 (void) fgets(line, MSG_SIZ, f);
13255 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
13256 (void) fgets(line, MSG_SIZ, f);
13257 for (p = line, j = BOARD_LEFT; j < BOARD_RGHT; p++) {
13260 initial_position[i][j++] = CharToPiece(*p);
13264 blackPlaysFirst = FALSE;
13266 (void) fgets(line, MSG_SIZ, f);
13267 if (strncmp(line, "black", strlen("black"))==0)
13268 blackPlaysFirst = TRUE;
13271 startedFromSetupPosition = TRUE;
13273 CopyBoard(boards[0], initial_position);
13274 if (blackPlaysFirst) {
13275 currentMove = forwardMostMove = backwardMostMove = 1;
13276 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
13277 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
13278 CopyBoard(boards[1], initial_position);
13279 DisplayMessage("", _("Black to play"));
13281 currentMove = forwardMostMove = backwardMostMove = 0;
13282 DisplayMessage("", _("White to play"));
13284 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
13285 if(first.pr != NoProc) { // [HGM] in tourney-mode a position can be loaded before the chess engine is installed
13286 SendToProgram("force\n", &first);
13287 SendBoard(&first, forwardMostMove);
13289 if (appData.debugMode) {
13291 for(i=0;i<2;i++){for(j=0;j<6;j++)fprintf(debugFP, " %d", boards[i][CASTLING][j]);fprintf(debugFP,"\n");}
13292 for(j=0;j<6;j++)fprintf(debugFP, " %d", initialRights[j]);fprintf(debugFP,"\n");
13293 fprintf(debugFP, "Load Position\n");
13296 if (positionNumber > 1) {
13297 snprintf(line, MSG_SIZ, "%s %d", title, positionNumber);
13298 DisplayTitle(line);
13300 DisplayTitle(title);
13302 gameMode = EditGame;
13305 timeRemaining[0][1] = whiteTimeRemaining;
13306 timeRemaining[1][1] = blackTimeRemaining;
13307 DrawPosition(FALSE, boards[currentMove]);
13314 CopyPlayerNameIntoFileName (char **dest, char *src)
13316 while (*src != NULLCHAR && *src != ',') {
13321 *(*dest)++ = *src++;
13327 DefaultFileName (char *ext)
13329 static char def[MSG_SIZ];
13332 if (gameInfo.white != NULL && gameInfo.white[0] != '-') {
13334 CopyPlayerNameIntoFileName(&p, gameInfo.white);
13336 CopyPlayerNameIntoFileName(&p, gameInfo.black);
13338 safeStrCpy(p, ext, MSG_SIZ-2-strlen(gameInfo.white)-strlen(gameInfo.black));
13345 /* Save the current game to the given file */
13347 SaveGameToFile (char *filename, int append)
13351 int result, i, t,tot=0;
13353 if (strcmp(filename, "-") == 0) {
13354 return SaveGame(stdout, 0, NULL);
13356 for(i=0; i<10; i++) { // upto 10 tries
13357 f = fopen(filename, append ? "a" : "w");
13358 if(f && i) fprintf(f, "[Delay \"%d retries, %d msec\"]\n",i,tot);
13359 if(f || errno != 13) break;
13360 DoSleep(t = 5 + random()%11); // wait 5-15 msec
13364 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13365 DisplayError(buf, errno);
13368 safeStrCpy(buf, lastMsg, MSG_SIZ);
13369 DisplayMessage(_("Waiting for access to save file"), "");
13370 flock(fileno(f), LOCK_EX); // [HGM] lock: lock file while we are writing
13371 DisplayMessage(_("Saving game"), "");
13372 if(lseek(fileno(f), 0, SEEK_END) == -1) DisplayError(_("Bad Seek"), errno); // better safe than sorry...
13373 result = SaveGame(f, 0, NULL);
13374 DisplayMessage(buf, "");
13381 SavePart (char *str)
13383 static char buf[MSG_SIZ];
13386 p = strchr(str, ' ');
13387 if (p == NULL) return str;
13388 strncpy(buf, str, p - str);
13389 buf[p - str] = NULLCHAR;
13393 #define PGN_MAX_LINE 75
13395 #define PGN_SIDE_WHITE 0
13396 #define PGN_SIDE_BLACK 1
13399 FindFirstMoveOutOfBook (int side)
13403 if( backwardMostMove == 0 && ! startedFromSetupPosition) {
13404 int index = backwardMostMove;
13405 int has_book_hit = 0;
13407 if( (index % 2) != side ) {
13411 while( index < forwardMostMove ) {
13412 /* Check to see if engine is in book */
13413 int depth = pvInfoList[index].depth;
13414 int score = pvInfoList[index].score;
13420 else if( score == 0 && depth == 63 ) {
13421 in_book = 1; /* Zappa */
13423 else if( score == 2 && depth == 99 ) {
13424 in_book = 1; /* Abrok */
13427 has_book_hit += in_book;
13443 GetOutOfBookInfo (char * buf)
13447 int offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
13449 oob[0] = FindFirstMoveOutOfBook( PGN_SIDE_WHITE );
13450 oob[1] = FindFirstMoveOutOfBook( PGN_SIDE_BLACK );
13454 if( oob[0] >= 0 || oob[1] >= 0 ) {
13455 for( i=0; i<2; i++ ) {
13459 if( i > 0 && oob[0] >= 0 ) {
13460 strcat( buf, " " );
13463 sprintf( buf+strlen(buf), "%d%s. ", (idx - offset)/2 + 1, idx & 1 ? ".." : "" );
13464 sprintf( buf+strlen(buf), "%s%.2f",
13465 pvInfoList[idx].score >= 0 ? "+" : "",
13466 pvInfoList[idx].score / 100.0 );
13472 /* Save game in PGN style */
13474 SaveGamePGN2 (FILE *f)
13476 int i, offset, linelen, newblock;
13479 int movelen, numlen, blank;
13480 char move_buffer[100]; /* [AS] Buffer for move+PV info */
13482 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
13484 PrintPGNTags(f, &gameInfo);
13486 if(appData.numberTag && matchMode) fprintf(f, "[Number \"%d\"]\n", nextGame+1); // [HGM] number tag
13488 if (backwardMostMove > 0 || startedFromSetupPosition) {
13489 char *fen = PositionToFEN(backwardMostMove, NULL, 1);
13490 fprintf(f, "[FEN \"%s\"]\n[SetUp \"1\"]\n", fen);
13491 fprintf(f, "\n{--------------\n");
13492 PrintPosition(f, backwardMostMove);
13493 fprintf(f, "--------------}\n");
13497 /* [AS] Out of book annotation */
13498 if( appData.saveOutOfBookInfo ) {
13501 GetOutOfBookInfo( buf );
13503 if( buf[0] != '\0' ) {
13504 fprintf( f, "[%s \"%s\"]\n", PGN_OUT_OF_BOOK, buf );
13511 i = backwardMostMove;
13515 while (i < forwardMostMove) {
13516 /* Print comments preceding this move */
13517 if (commentList[i] != NULL) {
13518 if (linelen > 0) fprintf(f, "\n");
13519 fprintf(f, "%s", commentList[i]);
13524 /* Format move number */
13526 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1);
13529 snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1);
13531 numtext[0] = NULLCHAR;
13533 numlen = strlen(numtext);
13536 /* Print move number */
13537 blank = linelen > 0 && numlen > 0;
13538 if (linelen + (blank ? 1 : 0) + numlen > PGN_MAX_LINE) {
13547 fprintf(f, "%s", numtext);
13551 safeStrCpy(move_buffer, SavePart(parseList[i]), sizeof(move_buffer)/sizeof(move_buffer[0])); // [HGM] pgn: print move via buffer, so it can be edited
13552 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point before move */
13555 blank = linelen > 0 && movelen > 0;
13556 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
13565 fprintf(f, "%s", move_buffer);
13566 linelen += movelen;
13568 /* [AS] Add PV info if present */
13569 if( i >= 0 && appData.saveExtendedInfoInPGN && pvInfoList[i].depth > 0 ) {
13570 /* [HGM] add time */
13571 char buf[MSG_SIZ]; int seconds;
13573 seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest
13579 snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0);
13582 seconds = (seconds + 4)/10; // round to full seconds
13584 snprintf(buf, MSG_SIZ, " %d%c", seconds, 0);
13586 snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0);
13589 snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}",
13590 pvInfoList[i].score >= 0 ? "+" : "",
13591 pvInfoList[i].score / 100.0,
13592 pvInfoList[i].depth,
13595 movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */
13597 /* Print score/depth */
13598 blank = linelen > 0 && movelen > 0;
13599 if (linelen + (blank ? 1 : 0) + movelen > PGN_MAX_LINE) {
13608 fprintf(f, "%s", move_buffer);
13609 linelen += movelen;
13615 /* Start a new line */
13616 if (linelen > 0) fprintf(f, "\n");
13618 /* Print comments after last move */
13619 if (commentList[i] != NULL) {
13620 fprintf(f, "%s\n", commentList[i]);
13624 if (gameInfo.resultDetails != NULL &&
13625 gameInfo.resultDetails[0] != NULLCHAR) {
13626 char buf[MSG_SIZ], *p = gameInfo.resultDetails;
13627 if(gameInfo.result == GameUnfinished && appData.clockMode &&
13628 (gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay)) // [HGM] adjourn: save clock settings
13629 snprintf(buf, MSG_SIZ, "%s (Clocks: %ld, %ld)", p, whiteTimeRemaining/1000, blackTimeRemaining/1000), p = buf;
13630 fprintf(f, "{%s} %s\n\n", p, PGNResult(gameInfo.result));
13632 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
13636 /* Save game in PGN style and close the file */
13638 SaveGamePGN (FILE *f)
13642 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
13646 /* Save game in old style and close the file */
13648 SaveGameOldStyle (FILE *f)
13653 tm = time((time_t *) NULL);
13655 fprintf(f, "# %s game file -- %s", programName, ctime(&tm));
13658 if (backwardMostMove > 0 || startedFromSetupPosition) {
13659 fprintf(f, "\n[--------------\n");
13660 PrintPosition(f, backwardMostMove);
13661 fprintf(f, "--------------]\n");
13666 i = backwardMostMove;
13667 offset = backwardMostMove & (~1L); /* output move numbers start at 1 */
13669 while (i < forwardMostMove) {
13670 if (commentList[i] != NULL) {
13671 fprintf(f, "[%s]\n", commentList[i]);
13674 if ((i % 2) == 1) {
13675 fprintf(f, "%d. ... %s\n", (i - offset)/2 + 1, parseList[i]);
13678 fprintf(f, "%d. %s ", (i - offset)/2 + 1, parseList[i]);
13680 if (commentList[i] != NULL) {
13684 if (i >= forwardMostMove) {
13688 fprintf(f, "%s\n", parseList[i]);
13693 if (commentList[i] != NULL) {
13694 fprintf(f, "[%s]\n", commentList[i]);
13697 /* This isn't really the old style, but it's close enough */
13698 if (gameInfo.resultDetails != NULL &&
13699 gameInfo.resultDetails[0] != NULLCHAR) {
13700 fprintf(f, "%s (%s)\n\n", PGNResult(gameInfo.result),
13701 gameInfo.resultDetails);
13703 fprintf(f, "%s\n\n", PGNResult(gameInfo.result));
13710 /* Save the current game to open file f and close the file */
13712 SaveGame (FILE *f, int dummy, char *dummy2)
13714 if (gameMode == EditPosition) EditPositionDone(TRUE);
13715 lastSavedGame = GameCheckSum(); // [HGM] save: remember ID of last saved game to prevent double saving
13716 if (appData.oldSaveStyle)
13717 return SaveGameOldStyle(f);
13719 return SaveGamePGN(f);
13722 /* Save the current position to the given file */
13724 SavePositionToFile (char *filename)
13729 if (strcmp(filename, "-") == 0) {
13730 return SavePosition(stdout, 0, NULL);
13732 f = fopen(filename, "a");
13734 snprintf(buf, sizeof(buf), _("Can't open \"%s\""), filename);
13735 DisplayError(buf, errno);
13738 safeStrCpy(buf, lastMsg, MSG_SIZ);
13739 DisplayMessage(_("Waiting for access to save file"), "");
13740 flock(fileno(f), LOCK_EX); // [HGM] lock
13741 DisplayMessage(_("Saving position"), "");
13742 lseek(fileno(f), 0, SEEK_END); // better safe than sorry...
13743 SavePosition(f, 0, NULL);
13744 DisplayMessage(buf, "");
13750 /* Save the current position to the given open file and close the file */
13752 SavePosition (FILE *f, int dummy, char *dummy2)
13757 if (gameMode == EditPosition) EditPositionDone(TRUE);
13758 if (appData.oldSaveStyle) {
13759 tm = time((time_t *) NULL);
13761 fprintf(f, "# %s position file -- %s", programName, ctime(&tm));
13763 fprintf(f, "[--------------\n");
13764 PrintPosition(f, currentMove);
13765 fprintf(f, "--------------]\n");
13767 fen = PositionToFEN(currentMove, NULL, 1);
13768 fprintf(f, "%s\n", fen);
13776 ReloadCmailMsgEvent (int unregister)
13779 static char *inFilename = NULL;
13780 static char *outFilename;
13782 struct stat inbuf, outbuf;
13785 /* Any registered moves are unregistered if unregister is set, */
13786 /* i.e. invoked by the signal handler */
13788 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
13789 cmailMoveRegistered[i] = FALSE;
13790 if (cmailCommentList[i] != NULL) {
13791 free(cmailCommentList[i]);
13792 cmailCommentList[i] = NULL;
13795 nCmailMovesRegistered = 0;
13798 for (i = 0; i < CMAIL_MAX_GAMES; i ++) {
13799 cmailResult[i] = CMAIL_NOT_RESULT;
13803 if (inFilename == NULL) {
13804 /* Because the filenames are static they only get malloced once */
13805 /* and they never get freed */
13806 inFilename = (char *) malloc(strlen(appData.cmailGameName) + 9);
13807 sprintf(inFilename, "%s.game.in", appData.cmailGameName);
13809 outFilename = (char *) malloc(strlen(appData.cmailGameName) + 5);
13810 sprintf(outFilename, "%s.out", appData.cmailGameName);
13813 status = stat(outFilename, &outbuf);
13815 cmailMailedMove = FALSE;
13817 status = stat(inFilename, &inbuf);
13818 cmailMailedMove = (inbuf.st_mtime < outbuf.st_mtime);
13821 /* LoadGameFromFile(CMAIL_MAX_GAMES) with cmailMsgLoaded == TRUE
13822 counts the games, notes how each one terminated, etc.
13824 It would be nice to remove this kludge and instead gather all
13825 the information while building the game list. (And to keep it
13826 in the game list nodes instead of having a bunch of fixed-size
13827 parallel arrays.) Note this will require getting each game's
13828 termination from the PGN tags, as the game list builder does
13829 not process the game moves. --mann
13831 cmailMsgLoaded = TRUE;
13832 LoadGameFromFile(inFilename, CMAIL_MAX_GAMES, "", FALSE);
13834 /* Load first game in the file or popup game menu */
13835 LoadGameFromFile(inFilename, 0, appData.cmailGameName, TRUE);
13837 #endif /* !WIN32 */
13845 char string[MSG_SIZ];
13847 if ( cmailMailedMove
13848 || (cmailResult[lastLoadGameNumber - 1] == CMAIL_OLD_RESULT)) {
13849 return TRUE; /* Allow free viewing */
13852 /* Unregister move to ensure that we don't leave RegisterMove */
13853 /* with the move registered when the conditions for registering no */
13855 if (cmailMoveRegistered[lastLoadGameNumber - 1]) {
13856 cmailMoveRegistered[lastLoadGameNumber - 1] = FALSE;
13857 nCmailMovesRegistered --;
13859 if (cmailCommentList[lastLoadGameNumber - 1] != NULL)
13861 free(cmailCommentList[lastLoadGameNumber - 1]);
13862 cmailCommentList[lastLoadGameNumber - 1] = NULL;
13866 if (cmailOldMove == -1) {
13867 DisplayError(_("You have edited the game history.\nUse Reload Same Game and make your move again."), 0);
13871 if (currentMove > cmailOldMove + 1) {
13872 DisplayError(_("You have entered too many moves.\nBack up to the correct position and try again."), 0);
13876 if (currentMove < cmailOldMove) {
13877 DisplayError(_("Displayed position is not current.\nStep forward to the correct position and try again."), 0);
13881 if (forwardMostMove > currentMove) {
13882 /* Silently truncate extra moves */
13886 if ( (currentMove == cmailOldMove + 1)
13887 || ( (currentMove == cmailOldMove)
13888 && ( (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_ACCEPT)
13889 || (cmailMoveType[lastLoadGameNumber - 1] == CMAIL_RESIGN)))) {
13890 if (gameInfo.result != GameUnfinished) {
13891 cmailResult[lastLoadGameNumber - 1] = CMAIL_NEW_RESULT;
13894 if (commentList[currentMove] != NULL) {
13895 cmailCommentList[lastLoadGameNumber - 1]
13896 = StrSave(commentList[currentMove]);
13898 safeStrCpy(cmailMove[lastLoadGameNumber - 1], moveList[currentMove - 1], sizeof(cmailMove[lastLoadGameNumber - 1])/sizeof(cmailMove[lastLoadGameNumber - 1][0]));
13900 if (appData.debugMode)
13901 fprintf(debugFP, "Saving %s for game %d\n",
13902 cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber);
13904 snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber);
13906 f = fopen(string, "w");
13907 if (appData.oldSaveStyle) {
13908 SaveGameOldStyle(f); /* also closes the file */
13910 snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName);
13911 f = fopen(string, "w");
13912 SavePosition(f, 0, NULL); /* also closes the file */
13914 fprintf(f, "{--------------\n");
13915 PrintPosition(f, currentMove);
13916 fprintf(f, "--------------}\n\n");
13918 SaveGame(f, 0, NULL); /* also closes the file*/
13921 cmailMoveRegistered[lastLoadGameNumber - 1] = TRUE;
13922 nCmailMovesRegistered ++;
13923 } else if (nCmailGames == 1) {
13924 DisplayError(_("You have not made a move yet"), 0);
13935 static char *partCommandString = "cmail -xv%s -remail -game %s 2>&1";
13936 FILE *commandOutput;
13937 char buffer[MSG_SIZ], msg[MSG_SIZ], string[MSG_SIZ];
13938 int nBytes = 0; /* Suppress warnings on uninitialized variables */
13944 if (! cmailMsgLoaded) {
13945 DisplayError(_("The cmail message is not loaded.\nUse Reload CMail Message and make your move again."), 0);
13949 if (nCmailGames == nCmailResults) {
13950 DisplayError(_("No unfinished games"), 0);
13954 #if CMAIL_PROHIBIT_REMAIL
13955 if (cmailMailedMove) {
13956 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);
13957 DisplayError(msg, 0);
13962 if (! (cmailMailedMove || RegisterMove())) return;
13964 if ( cmailMailedMove
13965 || (nCmailMovesRegistered + nCmailResults == nCmailGames)) {
13966 snprintf(string, MSG_SIZ, partCommandString,
13967 appData.debugMode ? " -v" : "", appData.cmailGameName);
13968 commandOutput = popen(string, "r");
13970 if (commandOutput == NULL) {
13971 DisplayError(_("Failed to invoke cmail"), 0);
13973 for (nBuffers = 0; (! feof(commandOutput)); nBuffers ++) {
13974 nBytes = fread(buffer, 1, MSG_SIZ - 1, commandOutput);
13976 if (nBuffers > 1) {
13977 (void) memcpy(msg, buffer + nBytes, MSG_SIZ - nBytes - 1);
13978 (void) memcpy(msg + MSG_SIZ - nBytes - 1, buffer, nBytes);
13979 nBytes = MSG_SIZ - 1;
13981 (void) memcpy(msg, buffer, nBytes);
13983 *(msg + nBytes) = '\0'; /* \0 for end-of-string*/
13985 if(StrStr(msg, "Mailed cmail message to ") != NULL) {
13986 cmailMailedMove = TRUE; /* Prevent >1 moves */
13989 for (i = 0; i < nCmailGames; i ++) {
13990 if (cmailResult[i] == CMAIL_NOT_RESULT) {
13995 && ( (arcDir = (char *) getenv("CMAIL_ARCDIR"))
13997 snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive",
13999 appData.cmailGameName,
14001 LoadGameFromFile(buffer, 1, buffer, FALSE);
14002 cmailMsgLoaded = FALSE;
14006 DisplayInformation(msg);
14007 pclose(commandOutput);
14010 if ((*cmailMsg) != '\0') {
14011 DisplayInformation(cmailMsg);
14016 #endif /* !WIN32 */
14025 int prependComma = 0;
14027 char string[MSG_SIZ]; /* Space for game-list */
14030 if (!cmailMsgLoaded) return "";
14032 if (cmailMailedMove) {
14033 snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n"));
14035 /* Create a list of games left */
14036 snprintf(string, MSG_SIZ, "[");
14037 for (i = 0; i < nCmailGames; i ++) {
14038 if (! ( cmailMoveRegistered[i]
14039 || (cmailResult[i] == CMAIL_OLD_RESULT))) {
14040 if (prependComma) {
14041 snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1);
14043 snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1);
14047 strcat(string, number);
14050 strcat(string, "]");
14052 if (nCmailMovesRegistered + nCmailResults == 0) {
14053 switch (nCmailGames) {
14055 snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n"));
14059 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n"));
14063 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"),
14068 switch (nCmailGames - nCmailMovesRegistered - nCmailResults) {
14070 snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"),
14075 if (nCmailResults == nCmailGames) {
14076 snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n"));
14078 snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n"));
14083 snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"),
14095 if (gameMode == Training)
14096 SetTrainingModeOff();
14099 cmailMsgLoaded = FALSE;
14100 if (appData.icsActive) {
14101 SendToICS(ics_prefix);
14102 SendToICS("refresh\n");
14107 ExitEvent (int status)
14111 /* Give up on clean exit */
14115 /* Keep trying for clean exit */
14119 if (appData.icsActive) printf("\n"); // [HGM] end on new line after closing XBoard
14120 if (appData.icsActive && appData.colorize) Colorize(ColorNone, FALSE);
14122 if (telnetISR != NULL) {
14123 RemoveInputSource(telnetISR);
14125 if (icsPR != NoProc) {
14126 DestroyChildProcess(icsPR, TRUE);
14129 /* [HGM] crash: leave writing PGN and position entirely to GameEnds() */
14130 GameEnds(gameInfo.result, gameInfo.resultDetails==NULL ? "xboard exit" : gameInfo.resultDetails, GE_PLAYER);
14132 /* [HGM] crash: the above GameEnds() is a dud if another one was running */
14133 /* make sure this other one finishes before killing it! */
14134 if(endingGame) { int count = 0;
14135 if(appData.debugMode) fprintf(debugFP, "ExitEvent() during GameEnds(), wait\n");
14136 while(endingGame && count++ < 10) DoSleep(1);
14137 if(appData.debugMode && endingGame) fprintf(debugFP, "GameEnds() seems stuck, proceed exiting\n");
14140 /* Kill off chess programs */
14141 if (first.pr != NoProc) {
14144 DoSleep( appData.delayBeforeQuit );
14145 SendToProgram("quit\n", &first);
14146 DestroyChildProcess(first.pr, 4 + first.useSigterm /* [AS] first.useSigterm */ );
14148 if (second.pr != NoProc) {
14149 DoSleep( appData.delayBeforeQuit );
14150 SendToProgram("quit\n", &second);
14151 DestroyChildProcess(second.pr, 4 + second.useSigterm /* [AS] second.useSigterm */ );
14153 if (first.isr != NULL) {
14154 RemoveInputSource(first.isr);
14156 if (second.isr != NULL) {
14157 RemoveInputSource(second.isr);
14160 if (pairing.pr != NoProc) SendToProgram("quit\n", &pairing);
14161 if (pairing.isr != NULL) RemoveInputSource(pairing.isr);
14163 ShutDownFrontEnd();
14168 PauseEngine (ChessProgramState *cps)
14170 SendToProgram("pause\n", cps);
14175 UnPauseEngine (ChessProgramState *cps)
14177 SendToProgram("resume\n", cps);
14184 if (appData.debugMode)
14185 fprintf(debugFP, "PauseEvent(): pausing %d\n", pausing);
14189 if(stalledEngine) { // [HGM] pause: resume game by releasing withheld move
14191 if(gameMode == TwoMachinesPlay) { // we might have to make the opponent resume pondering
14192 if(stalledEngine->other->pause == 2) UnPauseEngine(stalledEngine->other);
14193 else if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine->other);
14195 if(appData.ponderNextMove) SendToProgram("hard\n", stalledEngine);
14196 HandleMachineMove(stashedInputMove, stalledEngine);
14197 stalledEngine = NULL;
14200 if (gameMode == MachinePlaysWhite ||
14201 gameMode == TwoMachinesPlay ||
14202 gameMode == MachinePlaysBlack) { // the thinking engine must have used pause mode, or it would have been stalledEngine
14203 if(first.pause) UnPauseEngine(&first);
14204 else if(appData.ponderNextMove) SendToProgram("hard\n", &first);
14205 if(second.pause) UnPauseEngine(&second);
14206 else if(gameMode == TwoMachinesPlay && appData.ponderNextMove) SendToProgram("hard\n", &second);
14209 DisplayBothClocks();
14211 if (gameMode == PlayFromGameFile) {
14212 if (appData.timeDelay >= 0)
14213 AutoPlayGameLoop();
14214 } else if (gameMode == IcsExamining && pauseExamInvalid) {
14215 Reset(FALSE, TRUE);
14216 SendToICS(ics_prefix);
14217 SendToICS("refresh\n");
14218 } else if (currentMove < forwardMostMove && gameMode != AnalyzeMode) {
14219 ForwardInner(forwardMostMove);
14221 pauseExamInvalid = FALSE;
14223 switch (gameMode) {
14227 pauseExamForwardMostMove = forwardMostMove;
14228 pauseExamInvalid = FALSE;
14231 case IcsPlayingWhite:
14232 case IcsPlayingBlack:
14236 case PlayFromGameFile:
14237 (void) StopLoadGameTimer();
14241 case BeginningOfGame:
14242 if (appData.icsActive) return;
14243 /* else fall through */
14244 case MachinePlaysWhite:
14245 case MachinePlaysBlack:
14246 case TwoMachinesPlay:
14247 if (forwardMostMove == 0)
14248 return; /* don't pause if no one has moved */
14249 if(gameMode == TwoMachinesPlay) { // [HGM] pause: stop clocks if engine can be paused immediately
14250 ChessProgramState *onMove = (WhiteOnMove(forwardMostMove) == (first.twoMachinesColor[0] == 'w') ? &first : &second);
14251 if(onMove->pause) { // thinking engine can be paused
14252 PauseEngine(onMove); // do it
14253 if(onMove->other->pause) // pondering opponent can always be paused immediately
14254 PauseEngine(onMove->other);
14256 SendToProgram("easy\n", onMove->other);
14258 } else if(appData.ponderNextMove) SendToProgram("easy\n", onMove); // pre-emptively bring out of ponder
14259 } else if(gameMode == (WhiteOnMove(forwardMostMove) ? MachinePlaysWhite : MachinePlaysBlack)) { // engine on move
14261 PauseEngine(&first);
14263 } else if(appData.ponderNextMove) SendToProgram("easy\n", &first); // pre-emptively bring out of ponder
14264 } else { // human on move, pause pondering by either method
14266 PauseEngine(&first);
14267 else if(appData.ponderNextMove)
14268 SendToProgram("easy\n", &first);
14271 // if no immediate pausing is possible, wait for engine to move, and stop clocks then
14281 EditCommentEvent ()
14283 char title[MSG_SIZ];
14285 if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) {
14286 safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0]));
14288 snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1,
14289 WhiteOnMove(currentMove - 1) ? " " : ".. ",
14290 parseList[currentMove - 1]);
14293 EditCommentPopUp(currentMove, title, commentList[currentMove]);
14300 char *tags = PGNTags(&gameInfo);
14302 EditTagsPopUp(tags, NULL);
14309 if(second.analyzing) {
14310 SendToProgram("exit\n", &second);
14311 second.analyzing = FALSE;
14313 if (second.pr == NoProc) StartChessProgram(&second);
14314 InitChessProgram(&second, FALSE);
14315 FeedMovesToProgram(&second, currentMove);
14317 SendToProgram("analyze\n", &second);
14318 second.analyzing = TRUE;
14322 /* Toggle ShowThinking */
14324 ToggleShowThinking()
14326 appData.showThinking = !appData.showThinking;
14327 ShowThinkingEvent();
14331 AnalyzeModeEvent ()
14335 if (!first.analysisSupport) {
14336 snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
14337 DisplayError(buf, 0);
14340 /* [DM] icsEngineAnalyze [HGM] This is horrible code; reverse the gameMode and isEngineAnalyze tests! */
14341 if (appData.icsActive) {
14342 if (gameMode != IcsObserving) {
14343 snprintf(buf, MSG_SIZ, _("You are not observing a game"));
14344 DisplayError(buf, 0);
14346 if (appData.icsEngineAnalyze) {
14347 if (appData.debugMode)
14348 fprintf(debugFP, "Found unexpected active ICS engine analyze \n");
14354 /* if enable, user wants to disable icsEngineAnalyze */
14355 if (appData.icsEngineAnalyze) {
14360 appData.icsEngineAnalyze = TRUE;
14361 if (appData.debugMode)
14362 fprintf(debugFP, "ICS engine analyze starting... \n");
14365 if (gameMode == AnalyzeMode) { ToggleSecond(); return 0; }
14366 if (appData.noChessProgram || gameMode == AnalyzeMode)
14369 if (gameMode != AnalyzeFile) {
14370 if (!appData.icsEngineAnalyze) {
14372 if (gameMode != EditGame) return 0;
14374 if (!appData.showThinking) ToggleShowThinking();
14375 ResurrectChessProgram();
14376 SendToProgram("analyze\n", &first);
14377 first.analyzing = TRUE;
14378 /*first.maybeThinking = TRUE;*/
14379 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14380 EngineOutputPopUp();
14382 if (!appData.icsEngineAnalyze) {
14383 gameMode = AnalyzeMode;
14384 ClearEngineOutputPane(0); // [TK] exclude: to print exclusion/multipv header
14390 StartAnalysisClock();
14391 GetTimeMark(&lastNodeCountTime);
14397 AnalyzeFileEvent ()
14399 if (appData.noChessProgram || gameMode == AnalyzeFile)
14402 if (!first.analysisSupport) {
14404 snprintf(buf, sizeof(buf), _("%s does not support analysis"), first.tidy);
14405 DisplayError(buf, 0);
14409 if (gameMode != AnalyzeMode) {
14410 keepInfo = 1; // mere annotating should not alter PGN tags
14413 if (gameMode != EditGame) return;
14414 if (!appData.showThinking) ToggleShowThinking();
14415 ResurrectChessProgram();
14416 SendToProgram("analyze\n", &first);
14417 first.analyzing = TRUE;
14418 /*first.maybeThinking = TRUE;*/
14419 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
14420 EngineOutputPopUp();
14422 gameMode = AnalyzeFile;
14426 StartAnalysisClock();
14427 GetTimeMark(&lastNodeCountTime);
14429 if(appData.timeDelay > 0) StartLoadGameTimer((long)(1000.0f * appData.timeDelay));
14430 AnalysisPeriodicEvent(1);
14434 MachineWhiteEvent ()
14437 char *bookHit = NULL;
14439 if (appData.noChessProgram || (gameMode == MachinePlaysWhite))
14443 if (gameMode == PlayFromGameFile ||
14444 gameMode == TwoMachinesPlay ||
14445 gameMode == Training ||
14446 gameMode == AnalyzeMode ||
14447 gameMode == EndOfGame)
14450 if (gameMode == EditPosition)
14451 EditPositionDone(TRUE);
14453 if (!WhiteOnMove(currentMove)) {
14454 DisplayError(_("It is not White's turn"), 0);
14458 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
14461 if (gameMode == EditGame || gameMode == AnalyzeMode ||
14462 gameMode == AnalyzeFile)
14465 ResurrectChessProgram(); /* in case it isn't running */
14466 if(gameMode == BeginningOfGame) { /* [HGM] time odds: to get right odds in human mode */
14467 gameMode = MachinePlaysWhite;
14470 gameMode = MachinePlaysWhite;
14474 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
14476 if (first.sendName) {
14477 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black);
14478 SendToProgram(buf, &first);
14480 if (first.sendTime) {
14481 if (first.useColors) {
14482 SendToProgram("black\n", &first); /*gnu kludge*/
14484 SendTimeRemaining(&first, TRUE);
14486 if (first.useColors) {
14487 SendToProgram("white\n", &first); // [HGM] book: send 'go' separately
14489 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
14490 SetMachineThinkingEnables();
14491 first.maybeThinking = TRUE;
14495 if (appData.autoFlipView && !flipView) {
14496 flipView = !flipView;
14497 DrawPosition(FALSE, NULL);
14498 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
14501 if(bookHit) { // [HGM] book: simulate book reply
14502 static char bookMove[MSG_SIZ]; // a bit generous?
14504 programStats.nodes = programStats.depth = programStats.time =
14505 programStats.score = programStats.got_only_move = 0;
14506 sprintf(programStats.movelist, "%s (xbook)", bookHit);
14508 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
14509 strcat(bookMove, bookHit);
14510 HandleMachineMove(bookMove, &first);
14515 MachineBlackEvent ()
14518 char *bookHit = NULL;
14520 if (appData.noChessProgram || (gameMode == MachinePlaysBlack))
14524 if (gameMode == PlayFromGameFile ||
14525 gameMode == TwoMachinesPlay ||
14526 gameMode == Training ||
14527 gameMode == AnalyzeMode ||
14528 gameMode == EndOfGame)
14531 if (gameMode == EditPosition)
14532 EditPositionDone(TRUE);
14534 if (WhiteOnMove(currentMove)) {
14535 DisplayError(_("It is not Black's turn"), 0);
14539 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile)
14542 if (gameMode == EditGame || gameMode == AnalyzeMode ||
14543 gameMode == AnalyzeFile)
14546 ResurrectChessProgram(); /* in case it isn't running */
14547 gameMode = MachinePlaysBlack;
14551 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
14553 if (first.sendName) {
14554 snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white);
14555 SendToProgram(buf, &first);
14557 if (first.sendTime) {
14558 if (first.useColors) {
14559 SendToProgram("white\n", &first); /*gnu kludge*/
14561 SendTimeRemaining(&first, FALSE);
14563 if (first.useColors) {
14564 SendToProgram("black\n", &first); // [HGM] book: 'go' sent separately
14566 bookHit = SendMoveToBookUser(forwardMostMove-1, &first, TRUE); // [HGM] book: send go or retrieve book move
14567 SetMachineThinkingEnables();
14568 first.maybeThinking = TRUE;
14571 if (appData.autoFlipView && flipView) {
14572 flipView = !flipView;
14573 DrawPosition(FALSE, NULL);
14574 DisplayBothClocks(); // [HGM] logo: clocks might have to be exchanged;
14576 if(bookHit) { // [HGM] book: simulate book reply
14577 static char bookMove[MSG_SIZ]; // a bit generous?
14579 programStats.nodes = programStats.depth = programStats.time =
14580 programStats.score = programStats.got_only_move = 0;
14581 sprintf(programStats.movelist, "%s (xbook)", bookHit);
14583 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
14584 strcat(bookMove, bookHit);
14585 HandleMachineMove(bookMove, &first);
14591 DisplayTwoMachinesTitle ()
14594 if (appData.matchGames > 0) {
14595 if(appData.tourneyFile[0]) {
14596 snprintf(buf, MSG_SIZ, "%s %s %s (%d/%d%s)",
14597 gameInfo.white, _("vs."), gameInfo.black,
14598 nextGame+1, appData.matchGames+1,
14599 appData.tourneyType>0 ? "gt" : appData.tourneyType<0 ? "sw" : "rr");
14601 if (first.twoMachinesColor[0] == 'w') {
14602 snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
14603 gameInfo.white, _("vs."), gameInfo.black,
14604 first.matchWins, second.matchWins,
14605 matchGame - 1 - (first.matchWins + second.matchWins));
14607 snprintf(buf, MSG_SIZ, "%s %s %s (%d-%d-%d)",
14608 gameInfo.white, _("vs."), gameInfo.black,
14609 second.matchWins, first.matchWins,
14610 matchGame - 1 - (first.matchWins + second.matchWins));
14613 snprintf(buf, MSG_SIZ, "%s %s %s", gameInfo.white, _("vs."), gameInfo.black);
14619 SettingsMenuIfReady ()
14621 if (second.lastPing != second.lastPong) {
14622 DisplayMessage("", _("Waiting for second chess program"));
14623 ScheduleDelayedEvent(SettingsMenuIfReady, 10); // [HGM] fast: lowered from 1000
14627 DisplayMessage("", "");
14628 SettingsPopUp(&second);
14632 WaitForEngine (ChessProgramState *cps, DelayedEventCallback retry)
14635 if (cps->pr == NoProc) {
14636 StartChessProgram(cps);
14637 if (cps->protocolVersion == 1) {
14639 ScheduleDelayedEvent(retry, 1); // Do this also through timeout to avoid recursive calling of 'retry'
14641 /* kludge: allow timeout for initial "feature" command */
14642 if(retry != TwoMachinesEventIfReady) FreezeUI();
14643 snprintf(buf, MSG_SIZ, _("Starting %s chess program"), _(cps->which));
14644 DisplayMessage("", buf);
14645 ScheduleDelayedEvent(retry, FEATURE_TIMEOUT);
14653 TwoMachinesEvent P((void))
14657 ChessProgramState *onmove;
14658 char *bookHit = NULL;
14659 static int stalling = 0;
14663 if (appData.noChessProgram) return;
14665 switch (gameMode) {
14666 case TwoMachinesPlay:
14668 case MachinePlaysWhite:
14669 case MachinePlaysBlack:
14670 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
14671 DisplayError(_("Wait until your turn,\nor select 'Move Now'."), 0);
14675 case BeginningOfGame:
14676 case PlayFromGameFile:
14679 if (gameMode != EditGame) return;
14682 EditPositionDone(TRUE);
14693 // forwardMostMove = currentMove;
14694 TruncateGame(); // [HGM] vari: MachineWhite and MachineBlack do this...
14695 startingEngine = TRUE;
14697 if(!ResurrectChessProgram()) return; /* in case first program isn't running (unbalances its ping due to InitChessProgram!) */
14699 if(!first.initDone && GetDelayedEvent() == TwoMachinesEventIfReady) return; // [HGM] engine #1 still waiting for feature timeout
14700 if(first.lastPing != first.lastPong) { // [HGM] wait till we are sure first engine has set up position
14701 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
14704 if(WaitForEngine(&second, TwoMachinesEventIfReady)) return; // (if needed:) started up second engine, so wait for features
14706 if(!SupportedVariant(second.variants, gameInfo.variant, gameInfo.boardWidth,
14707 gameInfo.boardHeight, gameInfo.holdingsSize, second.protocolVersion, second.tidy)) {
14708 startingEngine = matchMode = FALSE;
14709 DisplayError("second engine does not play this", 0);
14710 gameMode = TwoMachinesPlay; ModeHighlight(); // Needed to make sure menu item is unchecked
14711 EditGameEvent(); // switch back to EditGame mode
14716 InitChessProgram(&second, FALSE); // unbalances ping of second engine
14717 SendToProgram("force\n", &second);
14719 ScheduleDelayedEvent(TwoMachinesEventIfReady, 10);
14722 GetTimeMark(&now); // [HGM] matchpause: implement match pause after engine load
14723 if(appData.matchPause>10000 || appData.matchPause<10)
14724 appData.matchPause = 10000; /* [HGM] make pause adjustable */
14725 wait = SubtractTimeMarks(&now, &pauseStart);
14726 if(wait < appData.matchPause) {
14727 ScheduleDelayedEvent(TwoMachinesEventIfReady, appData.matchPause - wait);
14730 // we are now committed to starting the game
14732 DisplayMessage("", "");
14733 if (startedFromSetupPosition) {
14734 SendBoard(&second, backwardMostMove);
14735 if (appData.debugMode) {
14736 fprintf(debugFP, "Two Machines\n");
14739 for (i = backwardMostMove; i < forwardMostMove; i++) {
14740 SendMoveToProgram(i, &second);
14743 gameMode = TwoMachinesPlay;
14744 pausing = startingEngine = FALSE;
14745 ModeHighlight(); // [HGM] logo: this triggers display update of logos
14747 DisplayTwoMachinesTitle();
14749 if ((first.twoMachinesColor[0] == 'w') == WhiteOnMove(forwardMostMove)) {
14754 if(appData.debugMode) fprintf(debugFP, "New game (%d): %s-%s (%c)\n", matchGame, first.tidy, second.tidy, first.twoMachinesColor[0]);
14755 SendToProgram(first.computerString, &first);
14756 if (first.sendName) {
14757 snprintf(buf, MSG_SIZ, "name %s\n", second.tidy);
14758 SendToProgram(buf, &first);
14760 SendToProgram(second.computerString, &second);
14761 if (second.sendName) {
14762 snprintf(buf, MSG_SIZ, "name %s\n", first.tidy);
14763 SendToProgram(buf, &second);
14767 if (!first.sendTime || !second.sendTime) {
14768 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
14769 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
14771 if (onmove->sendTime) {
14772 if (onmove->useColors) {
14773 SendToProgram(onmove->other->twoMachinesColor, onmove); /*gnu kludge*/
14775 SendTimeRemaining(onmove, WhiteOnMove(forwardMostMove));
14777 if (onmove->useColors) {
14778 SendToProgram(onmove->twoMachinesColor, onmove);
14780 bookHit = SendMoveToBookUser(forwardMostMove-1, onmove, TRUE); // [HGM] book: send go or retrieve book move
14781 // SendToProgram("go\n", onmove);
14782 onmove->maybeThinking = TRUE;
14783 SetMachineThinkingEnables();
14787 if(bookHit) { // [HGM] book: simulate book reply
14788 static char bookMove[MSG_SIZ]; // a bit generous?
14790 programStats.nodes = programStats.depth = programStats.time =
14791 programStats.score = programStats.got_only_move = 0;
14792 sprintf(programStats.movelist, "%s (xbook)", bookHit);
14794 safeStrCpy(bookMove, "move ", sizeof(bookMove)/sizeof(bookMove[0]));
14795 strcat(bookMove, bookHit);
14796 savedMessage = bookMove; // args for deferred call
14797 savedState = onmove;
14798 ScheduleDelayedEvent(DeferredBookMove, 1);
14805 if (gameMode == Training) {
14806 SetTrainingModeOff();
14807 gameMode = PlayFromGameFile;
14808 DisplayMessage("", _("Training mode off"));
14810 gameMode = Training;
14811 animateTraining = appData.animate;
14813 /* make sure we are not already at the end of the game */
14814 if (currentMove < forwardMostMove) {
14815 SetTrainingModeOn();
14816 DisplayMessage("", _("Training mode on"));
14818 gameMode = PlayFromGameFile;
14819 DisplayError(_("Already at end of game"), 0);
14828 if (!appData.icsActive) return;
14829 switch (gameMode) {
14830 case IcsPlayingWhite:
14831 case IcsPlayingBlack:
14834 case BeginningOfGame:
14842 EditPositionDone(TRUE);
14855 gameMode = IcsIdle;
14865 switch (gameMode) {
14867 SetTrainingModeOff();
14869 case MachinePlaysWhite:
14870 case MachinePlaysBlack:
14871 case BeginningOfGame:
14872 SendToProgram("force\n", &first);
14873 SetUserThinkingEnables();
14875 case PlayFromGameFile:
14876 (void) StopLoadGameTimer();
14877 if (gameFileFP != NULL) {
14882 EditPositionDone(TRUE);
14887 SendToProgram("force\n", &first);
14889 case TwoMachinesPlay:
14890 GameEnds(EndOfFile, NULL, GE_PLAYER);
14891 ResurrectChessProgram();
14892 SetUserThinkingEnables();
14895 ResurrectChessProgram();
14897 case IcsPlayingBlack:
14898 case IcsPlayingWhite:
14899 DisplayError(_("Warning: You are still playing a game"), 0);
14902 DisplayError(_("Warning: You are still observing a game"), 0);
14905 DisplayError(_("Warning: You are still examining a game"), 0);
14916 first.offeredDraw = second.offeredDraw = 0;
14918 if (gameMode == PlayFromGameFile) {
14919 whiteTimeRemaining = timeRemaining[0][currentMove];
14920 blackTimeRemaining = timeRemaining[1][currentMove];
14924 if (gameMode == MachinePlaysWhite ||
14925 gameMode == MachinePlaysBlack ||
14926 gameMode == TwoMachinesPlay ||
14927 gameMode == EndOfGame) {
14928 i = forwardMostMove;
14929 while (i > currentMove) {
14930 SendToProgram("undo\n", &first);
14933 if(!adjustedClock) {
14934 whiteTimeRemaining = timeRemaining[0][currentMove];
14935 blackTimeRemaining = timeRemaining[1][currentMove];
14936 DisplayBothClocks();
14938 if (whiteFlag || blackFlag) {
14939 whiteFlag = blackFlag = 0;
14944 gameMode = EditGame;
14951 EditPositionEvent ()
14953 if (gameMode == EditPosition) {
14959 if (gameMode != EditGame) return;
14961 gameMode = EditPosition;
14964 if (currentMove > 0)
14965 CopyBoard(boards[0], boards[currentMove]);
14967 blackPlaysFirst = !WhiteOnMove(currentMove);
14969 currentMove = forwardMostMove = backwardMostMove = 0;
14970 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
14972 if(!appData.pieceMenu) DisplayMessage(_("Click clock to clear board"), "");
14978 /* [DM] icsEngineAnalyze - possible call from other functions */
14979 if (appData.icsEngineAnalyze) {
14980 appData.icsEngineAnalyze = FALSE;
14982 DisplayMessage("",_("Close ICS engine analyze..."));
14984 if (first.analysisSupport && first.analyzing) {
14985 SendToBoth("exit\n");
14986 first.analyzing = second.analyzing = FALSE;
14988 thinkOutput[0] = NULLCHAR;
14992 EditPositionDone (Boolean fakeRights)
14994 int king = gameInfo.variant == VariantKnightmate ? WhiteUnicorn : WhiteKing;
14996 startedFromSetupPosition = TRUE;
14997 InitChessProgram(&first, FALSE);
14998 if(fakeRights) { // [HGM] suppress this if we just pasted a FEN.
14999 boards[0][EP_STATUS] = EP_NONE;
15000 boards[0][CASTLING][2] = boards[0][CASTLING][5] = BOARD_WIDTH>>1;
15001 if(boards[0][0][BOARD_WIDTH>>1] == king) {
15002 boards[0][CASTLING][1] = boards[0][0][BOARD_LEFT] == WhiteRook ? BOARD_LEFT : NoRights;
15003 boards[0][CASTLING][0] = boards[0][0][BOARD_RGHT-1] == WhiteRook ? BOARD_RGHT-1 : NoRights;
15004 } else boards[0][CASTLING][2] = NoRights;
15005 if(boards[0][BOARD_HEIGHT-1][BOARD_WIDTH>>1] == WHITE_TO_BLACK king) {
15006 boards[0][CASTLING][4] = boards[0][BOARD_HEIGHT-1][BOARD_LEFT] == BlackRook ? BOARD_LEFT : NoRights;
15007 boards[0][CASTLING][3] = boards[0][BOARD_HEIGHT-1][BOARD_RGHT-1] == BlackRook ? BOARD_RGHT-1 : NoRights;
15008 } else boards[0][CASTLING][5] = NoRights;
15009 if(gameInfo.variant == VariantSChess) {
15011 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) { // pieces in their original position are assumed virgin
15012 boards[0][VIRGIN][i] = 0;
15013 if(boards[0][0][i] == FIDEArray[0][i-BOARD_LEFT]) boards[0][VIRGIN][i] |= VIRGIN_W;
15014 if(boards[0][BOARD_HEIGHT-1][i] == FIDEArray[1][i-BOARD_LEFT]) boards[0][VIRGIN][i] |= VIRGIN_B;
15018 SendToProgram("force\n", &first);
15019 if (blackPlaysFirst) {
15020 safeStrCpy(moveList[0], "", sizeof(moveList[0])/sizeof(moveList[0][0]));
15021 safeStrCpy(parseList[0], "", sizeof(parseList[0])/sizeof(parseList[0][0]));
15022 currentMove = forwardMostMove = backwardMostMove = 1;
15023 CopyBoard(boards[1], boards[0]);
15025 currentMove = forwardMostMove = backwardMostMove = 0;
15027 SendBoard(&first, forwardMostMove);
15028 if (appData.debugMode) {
15029 fprintf(debugFP, "EditPosDone\n");
15032 DisplayMessage("", "");
15033 timeRemaining[0][forwardMostMove] = whiteTimeRemaining;
15034 timeRemaining[1][forwardMostMove] = blackTimeRemaining;
15035 gameMode = EditGame;
15037 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
15038 ClearHighlights(); /* [AS] */
15041 /* Pause for `ms' milliseconds */
15042 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
15044 TimeDelay (long ms)
15051 } while (SubtractTimeMarks(&m2, &m1) < ms);
15054 /* !! Ugh, this is a kludge. Fix it sometime. --tpm */
15056 SendMultiLineToICS (char *buf)
15058 char temp[MSG_SIZ+1], *p;
15065 strncpy(temp, buf, len);
15070 if (*p == '\n' || *p == '\r')
15075 strcat(temp, "\n");
15077 SendToPlayer(temp, strlen(temp));
15081 SetWhiteToPlayEvent ()
15083 if (gameMode == EditPosition) {
15084 blackPlaysFirst = FALSE;
15085 DisplayBothClocks(); /* works because currentMove is 0 */
15086 } else if (gameMode == IcsExamining) {
15087 SendToICS(ics_prefix);
15088 SendToICS("tomove white\n");
15093 SetBlackToPlayEvent ()
15095 if (gameMode == EditPosition) {
15096 blackPlaysFirst = TRUE;
15097 currentMove = 1; /* kludge */
15098 DisplayBothClocks();
15100 } else if (gameMode == IcsExamining) {
15101 SendToICS(ics_prefix);
15102 SendToICS("tomove black\n");
15107 EditPositionMenuEvent (ChessSquare selection, int x, int y)
15110 ChessSquare piece = boards[0][y][x];
15111 static Board erasedBoard, currentBoard, menuBoard, nullBoard;
15112 static int lastVariant;
15114 if (gameMode != EditPosition && gameMode != IcsExamining) return;
15116 switch (selection) {
15118 fromX = fromY = killX = killY = -1; // [HGM] abort any move entry in progress
15119 MarkTargetSquares(1);
15120 CopyBoard(currentBoard, boards[0]);
15121 CopyBoard(menuBoard, initialPosition);
15122 if (gameMode == IcsExamining && ics_type == ICS_FICS) {
15123 SendToICS(ics_prefix);
15124 SendToICS("bsetup clear\n");
15125 } else if (gameMode == IcsExamining && ics_type == ICS_ICC) {
15126 SendToICS(ics_prefix);
15127 SendToICS("clearboard\n");
15130 for (x = 0; x < BOARD_WIDTH; x++) { ChessSquare p = EmptySquare;
15131 if(x == BOARD_LEFT-1 || x == BOARD_RGHT) p = (ChessSquare) 0; /* [HGM] holdings */
15132 for (y = 0; y < BOARD_HEIGHT; y++) {
15133 if (gameMode == IcsExamining) {
15134 if (boards[currentMove][y][x] != EmptySquare) {
15135 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix,
15139 } else if(boards[0][y][x] != DarkSquare) {
15140 if(boards[0][y][x] != p) nonEmpty++;
15141 boards[0][y][x] = p;
15145 if(gameMode != IcsExamining) { // [HGM] editpos: cycle trough boards
15147 for(r = 0; r < BOARD_HEIGHT; r++) {
15148 for(x = BOARD_LEFT; x < BOARD_RGHT; x++) { // create 'menu board' by removing duplicates
15149 ChessSquare p = menuBoard[r][x];
15150 for(y = x + 1; y < BOARD_RGHT; y++) if(menuBoard[r][y] == p) menuBoard[r][y] = EmptySquare;
15153 DisplayMessage("Clicking clock again restores position", "");
15154 if(gameInfo.variant != lastVariant) lastVariant = gameInfo.variant, CopyBoard(erasedBoard, boards[0]);
15155 if(!nonEmpty) { // asked to clear an empty board
15156 CopyBoard(boards[0], menuBoard);
15158 if(CompareBoards(currentBoard, menuBoard)) { // asked to clear an empty board
15159 CopyBoard(boards[0], initialPosition);
15161 if(CompareBoards(currentBoard, initialPosition) && !CompareBoards(currentBoard, erasedBoard)
15162 && !CompareBoards(nullBoard, erasedBoard)) {
15163 CopyBoard(boards[0], erasedBoard);
15165 CopyBoard(erasedBoard, currentBoard);
15169 if (gameMode == EditPosition) {
15170 DrawPosition(FALSE, boards[0]);
15175 SetWhiteToPlayEvent();
15179 SetBlackToPlayEvent();
15183 if (gameMode == IcsExamining) {
15184 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
15185 snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y);
15188 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
15189 if(x == BOARD_LEFT-2) {
15190 if(y < BOARD_HEIGHT-1-gameInfo.holdingsSize) break;
15191 boards[0][y][1] = 0;
15193 if(x == BOARD_RGHT+1) {
15194 if(y >= gameInfo.holdingsSize) break;
15195 boards[0][y][BOARD_WIDTH-2] = 0;
15198 boards[0][y][x] = EmptySquare;
15199 DrawPosition(FALSE, boards[0]);
15204 if(piece >= (int)WhitePawn && piece < (int)WhiteMan ||
15205 piece >= (int)BlackPawn && piece < (int)BlackMan ) {
15206 selection = (ChessSquare) (PROMOTED piece);
15207 } else if(piece == EmptySquare) selection = WhiteSilver;
15208 else selection = (ChessSquare)((int)piece - 1);
15212 if(piece > (int)WhiteMan && piece <= (int)WhiteKing ||
15213 piece > (int)BlackMan && piece <= (int)BlackKing ) {
15214 selection = (ChessSquare) (DEMOTED piece);
15215 } else if(piece == EmptySquare) selection = BlackSilver;
15216 else selection = (ChessSquare)((int)piece + 1);
15221 if(gameInfo.variant == VariantShatranj ||
15222 gameInfo.variant == VariantXiangqi ||
15223 gameInfo.variant == VariantCourier ||
15224 gameInfo.variant == VariantASEAN ||
15225 gameInfo.variant == VariantMakruk )
15226 selection = (ChessSquare)((int)selection - (int)WhiteQueen + (int)WhiteFerz);
15231 if(gameInfo.variant == VariantXiangqi)
15232 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteWazir);
15233 if(gameInfo.variant == VariantKnightmate)
15234 selection = (ChessSquare)((int)selection - (int)WhiteKing + (int)WhiteUnicorn);
15237 if (gameMode == IcsExamining) {
15238 if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings
15239 snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix,
15240 PieceToChar(selection), AAA + x, ONE + y);
15243 if(x < BOARD_LEFT || x >= BOARD_RGHT) {
15245 if(x == BOARD_LEFT-2 && selection >= BlackPawn) {
15246 n = PieceToNumber(selection - BlackPawn);
15247 if(n >= gameInfo.holdingsSize) { n = 0; selection = BlackPawn; }
15248 boards[0][BOARD_HEIGHT-1-n][0] = selection;
15249 boards[0][BOARD_HEIGHT-1-n][1]++;
15251 if(x == BOARD_RGHT+1 && selection < BlackPawn) {
15252 n = PieceToNumber(selection);
15253 if(n >= gameInfo.holdingsSize) { n = 0; selection = WhitePawn; }
15254 boards[0][n][BOARD_WIDTH-1] = selection;
15255 boards[0][n][BOARD_WIDTH-2]++;
15258 boards[0][y][x] = selection;
15259 DrawPosition(TRUE, boards[0]);
15261 fromX = fromY = -1;
15269 DropMenuEvent (ChessSquare selection, int x, int y)
15271 ChessMove moveType;
15273 switch (gameMode) {
15274 case IcsPlayingWhite:
15275 case MachinePlaysBlack:
15276 if (!WhiteOnMove(currentMove)) {
15277 DisplayMoveError(_("It is Black's turn"));
15280 moveType = WhiteDrop;
15282 case IcsPlayingBlack:
15283 case MachinePlaysWhite:
15284 if (WhiteOnMove(currentMove)) {
15285 DisplayMoveError(_("It is White's turn"));
15288 moveType = BlackDrop;
15291 moveType = WhiteOnMove(currentMove) ? WhiteDrop : BlackDrop;
15297 if (moveType == BlackDrop && selection < BlackPawn) {
15298 selection = (ChessSquare) ((int) selection
15299 + (int) BlackPawn - (int) WhitePawn);
15301 if (boards[currentMove][y][x] != EmptySquare) {
15302 DisplayMoveError(_("That square is occupied"));
15306 FinishMove(moveType, (int) selection, DROP_RANK, x, y, NULLCHAR);
15312 /* Accept a pending offer of any kind from opponent */
15314 if (appData.icsActive) {
15315 SendToICS(ics_prefix);
15316 SendToICS("accept\n");
15317 } else if (cmailMsgLoaded) {
15318 if (currentMove == cmailOldMove &&
15319 commentList[cmailOldMove] != NULL &&
15320 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
15321 "Black offers a draw" : "White offers a draw")) {
15323 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
15324 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
15326 DisplayError(_("There is no pending offer on this move"), 0);
15327 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
15330 /* Not used for offers from chess program */
15337 /* Decline a pending offer of any kind from opponent */
15339 if (appData.icsActive) {
15340 SendToICS(ics_prefix);
15341 SendToICS("decline\n");
15342 } else if (cmailMsgLoaded) {
15343 if (currentMove == cmailOldMove &&
15344 commentList[cmailOldMove] != NULL &&
15345 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
15346 "Black offers a draw" : "White offers a draw")) {
15348 AppendComment(cmailOldMove, "Draw declined", TRUE);
15349 DisplayComment(cmailOldMove - 1, "Draw declined");
15352 DisplayError(_("There is no pending offer on this move"), 0);
15355 /* Not used for offers from chess program */
15362 /* Issue ICS rematch command */
15363 if (appData.icsActive) {
15364 SendToICS(ics_prefix);
15365 SendToICS("rematch\n");
15372 /* Call your opponent's flag (claim a win on time) */
15373 if (appData.icsActive) {
15374 SendToICS(ics_prefix);
15375 SendToICS("flag\n");
15377 switch (gameMode) {
15380 case MachinePlaysWhite:
15383 GameEnds(GameIsDrawn, "Both players ran out of time",
15386 GameEnds(BlackWins, "Black wins on time", GE_PLAYER);
15388 DisplayError(_("Your opponent is not out of time"), 0);
15391 case MachinePlaysBlack:
15394 GameEnds(GameIsDrawn, "Both players ran out of time",
15397 GameEnds(WhiteWins, "White wins on time", GE_PLAYER);
15399 DisplayError(_("Your opponent is not out of time"), 0);
15407 ClockClick (int which)
15408 { // [HGM] code moved to back-end from winboard.c
15409 if(which) { // black clock
15410 if (gameMode == EditPosition || gameMode == IcsExamining) {
15411 if(!appData.pieceMenu && blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
15412 SetBlackToPlayEvent();
15413 } else if ((gameMode == AnalyzeMode || gameMode == EditGame ||
15414 gameMode == MachinePlaysBlack && PosFlags(0) & F_NULL_MOVE && !blackFlag && !shiftKey) && WhiteOnMove(currentMove)) {
15415 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move: if not out of time, enters null move
15416 } else if (shiftKey) {
15417 AdjustClock(which, -1);
15418 } else if (gameMode == IcsPlayingWhite ||
15419 gameMode == MachinePlaysBlack) {
15422 } else { // white clock
15423 if (gameMode == EditPosition || gameMode == IcsExamining) {
15424 if(!appData.pieceMenu && !blackPlaysFirst) EditPositionMenuEvent(ClearBoard, 0, 0);
15425 SetWhiteToPlayEvent();
15426 } else if ((gameMode == AnalyzeMode || gameMode == EditGame ||
15427 gameMode == MachinePlaysWhite && PosFlags(0) & F_NULL_MOVE && !whiteFlag && !shiftKey) && !WhiteOnMove(currentMove)) {
15428 UserMoveEvent((int)EmptySquare, DROP_RANK, 0, 0, 0); // [HGM] multi-move
15429 } else if (shiftKey) {
15430 AdjustClock(which, -1);
15431 } else if (gameMode == IcsPlayingBlack ||
15432 gameMode == MachinePlaysWhite) {
15441 /* Offer draw or accept pending draw offer from opponent */
15443 if (appData.icsActive) {
15444 /* Note: tournament rules require draw offers to be
15445 made after you make your move but before you punch
15446 your clock. Currently ICS doesn't let you do that;
15447 instead, you immediately punch your clock after making
15448 a move, but you can offer a draw at any time. */
15450 SendToICS(ics_prefix);
15451 SendToICS("draw\n");
15452 userOfferedDraw = TRUE; // [HGM] drawclaim: also set flag in ICS play
15453 } else if (cmailMsgLoaded) {
15454 if (currentMove == cmailOldMove &&
15455 commentList[cmailOldMove] != NULL &&
15456 StrStr(commentList[cmailOldMove], WhiteOnMove(cmailOldMove) ?
15457 "Black offers a draw" : "White offers a draw")) {
15458 GameEnds(GameIsDrawn, "Draw agreed", GE_PLAYER);
15459 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_ACCEPT;
15460 } else if (currentMove == cmailOldMove + 1) {
15461 char *offer = WhiteOnMove(cmailOldMove) ?
15462 "White offers a draw" : "Black offers a draw";
15463 AppendComment(currentMove, offer, TRUE);
15464 DisplayComment(currentMove - 1, offer);
15465 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_DRAW;
15467 DisplayError(_("You must make your move before offering a draw"), 0);
15468 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_MOVE;
15470 } else if (first.offeredDraw) {
15471 GameEnds(GameIsDrawn, "Draw agreed", GE_XBOARD);
15473 if (first.sendDrawOffers) {
15474 SendToProgram("draw\n", &first);
15475 userOfferedDraw = TRUE;
15483 /* Offer Adjourn or accept pending Adjourn offer from opponent */
15485 if (appData.icsActive) {
15486 SendToICS(ics_prefix);
15487 SendToICS("adjourn\n");
15489 /* Currently GNU Chess doesn't offer or accept Adjourns */
15497 /* Offer Abort or accept pending Abort offer from opponent */
15499 if (appData.icsActive) {
15500 SendToICS(ics_prefix);
15501 SendToICS("abort\n");
15503 GameEnds(GameUnfinished, "Game aborted", GE_PLAYER);
15510 /* Resign. You can do this even if it's not your turn. */
15512 if (appData.icsActive) {
15513 SendToICS(ics_prefix);
15514 SendToICS("resign\n");
15516 switch (gameMode) {
15517 case MachinePlaysWhite:
15518 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
15520 case MachinePlaysBlack:
15521 GameEnds(BlackWins, "White resigns", GE_PLAYER);
15524 if (cmailMsgLoaded) {
15526 if (WhiteOnMove(cmailOldMove)) {
15527 GameEnds(BlackWins, "White resigns", GE_PLAYER);
15529 GameEnds(WhiteWins, "Black resigns", GE_PLAYER);
15531 cmailMoveType[lastLoadGameNumber - 1] = CMAIL_RESIGN;
15542 StopObservingEvent ()
15544 /* Stop observing current games */
15545 SendToICS(ics_prefix);
15546 SendToICS("unobserve\n");
15550 StopExaminingEvent ()
15552 /* Stop observing current game */
15553 SendToICS(ics_prefix);
15554 SendToICS("unexamine\n");
15558 ForwardInner (int target)
15560 int limit; int oldSeekGraphUp = seekGraphUp;
15562 if (appData.debugMode)
15563 fprintf(debugFP, "ForwardInner(%d), current %d, forward %d\n",
15564 target, currentMove, forwardMostMove);
15566 if (gameMode == EditPosition)
15569 seekGraphUp = FALSE;
15570 MarkTargetSquares(1);
15571 fromX = fromY = killX = killY = -1; // [HGM] abort any move entry in progress
15573 if (gameMode == PlayFromGameFile && !pausing)
15576 if (gameMode == IcsExamining && pausing)
15577 limit = pauseExamForwardMostMove;
15579 limit = forwardMostMove;
15581 if (target > limit) target = limit;
15583 if (target > 0 && moveList[target - 1][0]) {
15584 int fromX, fromY, toX, toY;
15585 toX = moveList[target - 1][2] - AAA;
15586 toY = moveList[target - 1][3] - ONE;
15587 if (moveList[target - 1][1] == '@') {
15588 if (appData.highlightLastMove) {
15589 SetHighlights(-1, -1, toX, toY);
15592 int viaX = moveList[target - 1][5] - AAA;
15593 int viaY = moveList[target - 1][6] - ONE;
15594 fromX = moveList[target - 1][0] - AAA;
15595 fromY = moveList[target - 1][1] - ONE;
15596 if (target == currentMove + 1) {
15597 if(moveList[target - 1][4] == ';') { // multi-leg
15598 ChessSquare piece = boards[currentMove][viaY][viaX];
15599 AnimateMove(boards[currentMove], fromX, fromY, viaX, viaY);
15600 boards[currentMove][viaY][viaX] = boards[currentMove][fromY][fromX];
15601 AnimateMove(boards[currentMove], viaX, viaY, toX, toY);
15602 boards[currentMove][viaY][viaX] = piece;
15604 AnimateMove(boards[currentMove], fromX, fromY, toX, toY);
15606 if (appData.highlightLastMove) {
15607 SetHighlights(fromX, fromY, toX, toY);
15611 if (gameMode == EditGame || gameMode == AnalyzeMode ||
15612 gameMode == Training || gameMode == PlayFromGameFile ||
15613 gameMode == AnalyzeFile) {
15614 while (currentMove < target) {
15615 if(second.analyzing) SendMoveToProgram(currentMove, &second);
15616 SendMoveToProgram(currentMove++, &first);
15619 currentMove = target;
15622 if (gameMode == EditGame || gameMode == EndOfGame) {
15623 whiteTimeRemaining = timeRemaining[0][currentMove];
15624 blackTimeRemaining = timeRemaining[1][currentMove];
15626 DisplayBothClocks();
15627 DisplayMove(currentMove - 1);
15628 DrawPosition(oldSeekGraphUp, boards[currentMove]);
15629 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
15630 if ( !matchMode && gameMode != Training) { // [HGM] PV info: routine tests if empty
15631 DisplayComment(currentMove - 1, commentList[currentMove]);
15633 ClearMap(); // [HGM] exclude: invalidate map
15640 if (gameMode == IcsExamining && !pausing) {
15641 SendToICS(ics_prefix);
15642 SendToICS("forward\n");
15644 ForwardInner(currentMove + 1);
15651 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15652 /* to optimze, we temporarily turn off analysis mode while we feed
15653 * the remaining moves to the engine. Otherwise we get analysis output
15656 if (first.analysisSupport) {
15657 SendToProgram("exit\nforce\n", &first);
15658 first.analyzing = FALSE;
15662 if (gameMode == IcsExamining && !pausing) {
15663 SendToICS(ics_prefix);
15664 SendToICS("forward 999999\n");
15666 ForwardInner(forwardMostMove);
15669 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15670 /* we have fed all the moves, so reactivate analysis mode */
15671 SendToProgram("analyze\n", &first);
15672 first.analyzing = TRUE;
15673 /*first.maybeThinking = TRUE;*/
15674 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
15679 BackwardInner (int target)
15681 int full_redraw = TRUE; /* [AS] Was FALSE, had to change it! */
15683 if (appData.debugMode)
15684 fprintf(debugFP, "BackwardInner(%d), current %d, forward %d\n",
15685 target, currentMove, forwardMostMove);
15687 if (gameMode == EditPosition) return;
15688 seekGraphUp = FALSE;
15689 MarkTargetSquares(1);
15690 fromX = fromY = killX = killY = -1; // [HGM] abort any move entry in progress
15691 if (currentMove <= backwardMostMove) {
15693 DrawPosition(full_redraw, boards[currentMove]);
15696 if (gameMode == PlayFromGameFile && !pausing)
15699 if (moveList[target][0]) {
15700 int fromX, fromY, toX, toY;
15701 toX = moveList[target][2] - AAA;
15702 toY = moveList[target][3] - ONE;
15703 if (moveList[target][1] == '@') {
15704 if (appData.highlightLastMove) {
15705 SetHighlights(-1, -1, toX, toY);
15708 fromX = moveList[target][0] - AAA;
15709 fromY = moveList[target][1] - ONE;
15710 if (target == currentMove - 1) {
15711 AnimateMove(boards[currentMove], toX, toY, fromX, fromY);
15713 if (appData.highlightLastMove) {
15714 SetHighlights(fromX, fromY, toX, toY);
15718 if (gameMode == EditGame || gameMode==AnalyzeMode ||
15719 gameMode == PlayFromGameFile || gameMode == AnalyzeFile) {
15720 while (currentMove > target) {
15721 if(moveList[currentMove-1][1] == '@' && moveList[currentMove-1][0] == '@') {
15722 // null move cannot be undone. Reload program with move history before it.
15724 for(i=target; i>backwardMostMove; i--) { // seek back to start or previous null move
15725 if(moveList[i-1][1] == '@' && moveList[i-1][0] == '@') break;
15727 SendBoard(&first, i);
15728 if(second.analyzing) SendBoard(&second, i);
15729 for(currentMove=i; currentMove<target; currentMove++) {
15730 SendMoveToProgram(currentMove, &first);
15731 if(second.analyzing) SendMoveToProgram(currentMove, &second);
15735 SendToBoth("undo\n");
15739 currentMove = target;
15742 if (gameMode == EditGame || gameMode == EndOfGame) {
15743 whiteTimeRemaining = timeRemaining[0][currentMove];
15744 blackTimeRemaining = timeRemaining[1][currentMove];
15746 DisplayBothClocks();
15747 DisplayMove(currentMove - 1);
15748 DrawPosition(full_redraw, boards[currentMove]);
15749 HistorySet(parseList,backwardMostMove,forwardMostMove,currentMove-1);
15750 // [HGM] PV info: routine tests if comment empty
15751 DisplayComment(currentMove - 1, commentList[currentMove]);
15752 ClearMap(); // [HGM] exclude: invalidate map
15758 if (gameMode == IcsExamining && !pausing) {
15759 SendToICS(ics_prefix);
15760 SendToICS("backward\n");
15762 BackwardInner(currentMove - 1);
15769 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15770 /* to optimize, we temporarily turn off analysis mode while we undo
15771 * all the moves. Otherwise we get analysis output after each undo.
15773 if (first.analysisSupport) {
15774 SendToProgram("exit\nforce\n", &first);
15775 first.analyzing = FALSE;
15779 if (gameMode == IcsExamining && !pausing) {
15780 SendToICS(ics_prefix);
15781 SendToICS("backward 999999\n");
15783 BackwardInner(backwardMostMove);
15786 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
15787 /* we have fed all the moves, so reactivate analysis mode */
15788 SendToProgram("analyze\n", &first);
15789 first.analyzing = TRUE;
15790 /*first.maybeThinking = TRUE;*/
15791 first.maybeThinking = FALSE; /* avoid killing GNU Chess */
15798 if (gameMode == PlayFromGameFile && !pausing) PauseEvent();
15799 if (to >= forwardMostMove) to = forwardMostMove;
15800 if (to <= backwardMostMove) to = backwardMostMove;
15801 if (to < currentMove) {
15809 RevertEvent (Boolean annotate)
15811 if(PopTail(annotate)) { // [HGM] vari: restore old game tail
15814 if (gameMode != IcsExamining) {
15815 DisplayError(_("You are not examining a game"), 0);
15819 DisplayError(_("You can't revert while pausing"), 0);
15822 SendToICS(ics_prefix);
15823 SendToICS("revert\n");
15827 RetractMoveEvent ()
15829 switch (gameMode) {
15830 case MachinePlaysWhite:
15831 case MachinePlaysBlack:
15832 if (WhiteOnMove(forwardMostMove) == (gameMode == MachinePlaysWhite)) {
15833 DisplayError(_("Wait until your turn,\nor select 'Move Now'."), 0);
15836 if (forwardMostMove < 2) return;
15837 currentMove = forwardMostMove = forwardMostMove - 2;
15838 whiteTimeRemaining = timeRemaining[0][currentMove];
15839 blackTimeRemaining = timeRemaining[1][currentMove];
15840 DisplayBothClocks();
15841 DisplayMove(currentMove - 1);
15842 ClearHighlights();/*!! could figure this out*/
15843 DrawPosition(TRUE, boards[currentMove]); /* [AS] Changed to full redraw! */
15844 SendToProgram("remove\n", &first);
15845 /*first.maybeThinking = TRUE;*/ /* GNU Chess does not ponder here */
15848 case BeginningOfGame:
15852 case IcsPlayingWhite:
15853 case IcsPlayingBlack:
15854 if (WhiteOnMove(forwardMostMove) == (gameMode == IcsPlayingWhite)) {
15855 SendToICS(ics_prefix);
15856 SendToICS("takeback 2\n");
15858 SendToICS(ics_prefix);
15859 SendToICS("takeback 1\n");
15868 ChessProgramState *cps;
15870 switch (gameMode) {
15871 case MachinePlaysWhite:
15872 if (!WhiteOnMove(forwardMostMove)) {
15873 DisplayError(_("It is your turn"), 0);
15878 case MachinePlaysBlack:
15879 if (WhiteOnMove(forwardMostMove)) {
15880 DisplayError(_("It is your turn"), 0);
15885 case TwoMachinesPlay:
15886 if (WhiteOnMove(forwardMostMove) ==
15887 (first.twoMachinesColor[0] == 'w')) {
15893 case BeginningOfGame:
15897 SendToProgram("?\n", cps);
15901 TruncateGameEvent ()
15904 if (gameMode != EditGame) return;
15911 CleanupTail(); // [HGM] vari: only keep current variation if we explicitly truncate
15912 if (forwardMostMove > currentMove) {
15913 if (gameInfo.resultDetails != NULL) {
15914 free(gameInfo.resultDetails);
15915 gameInfo.resultDetails = NULL;
15916 gameInfo.result = GameUnfinished;
15918 forwardMostMove = currentMove;
15919 HistorySet(parseList, backwardMostMove, forwardMostMove,
15927 if (appData.noChessProgram) return;
15928 switch (gameMode) {
15929 case MachinePlaysWhite:
15930 if (WhiteOnMove(forwardMostMove)) {
15931 DisplayError(_("Wait until your turn."), 0);
15935 case BeginningOfGame:
15936 case MachinePlaysBlack:
15937 if (!WhiteOnMove(forwardMostMove)) {
15938 DisplayError(_("Wait until your turn."), 0);
15943 DisplayError(_("No hint available"), 0);
15946 SendToProgram("hint\n", &first);
15947 hintRequested = TRUE;
15951 SaveSelected (FILE *g, int dummy, char *dummy2)
15953 ListGame * lg = (ListGame *) gameList.head;
15957 if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
15958 DisplayError(_("Game list not loaded or empty"), 0);
15962 creatingBook = TRUE; // suppresses stuff during load game
15964 /* Get list size */
15965 for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
15966 if(lg->position >= 0) { // selected?
15967 LoadGame(f, nItem, "", TRUE);
15968 SaveGamePGN2(g); // leaves g open
15971 lg = (ListGame *) lg->node.succ;
15975 creatingBook = FALSE;
15983 ListGame * lg = (ListGame *) gameList.head;
15986 static int secondTime = FALSE;
15988 if( !(f = GameFile()) || ((ListGame *) gameList.tailPred)->number <= 0 ) {
15989 DisplayError(_("Game list not loaded or empty"), 0);
15993 if(!secondTime && (g = fopen(appData.polyglotBook, "r"))) {
15996 DisplayNote(_("Book file exists! Try again for overwrite."));
16000 creatingBook = TRUE;
16001 secondTime = FALSE;
16003 /* Get list size */
16004 for (nItem = 1; nItem <= ((ListGame *) gameList.tailPred)->number; nItem++){
16005 if(lg->position >= 0) {
16006 LoadGame(f, nItem, "", TRUE);
16007 AddGameToBook(TRUE);
16010 lg = (ListGame *) lg->node.succ;
16013 creatingBook = FALSE;
16020 if (appData.noChessProgram) return;
16021 switch (gameMode) {
16022 case MachinePlaysWhite:
16023 if (WhiteOnMove(forwardMostMove)) {
16024 DisplayError(_("Wait until your turn."), 0);
16028 case BeginningOfGame:
16029 case MachinePlaysBlack:
16030 if (!WhiteOnMove(forwardMostMove)) {
16031 DisplayError(_("Wait until your turn."), 0);
16036 EditPositionDone(TRUE);
16038 case TwoMachinesPlay:
16043 SendToProgram("bk\n", &first);
16044 bookOutput[0] = NULLCHAR;
16045 bookRequested = TRUE;
16051 char *tags = PGNTags(&gameInfo);
16052 TagsPopUp(tags, CmailMsg());
16056 /* end button procedures */
16059 PrintPosition (FILE *fp, int move)
16063 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
16064 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
16065 char c = PieceToChar(boards[move][i][j]);
16066 fputc(c == 'x' ? '.' : c, fp);
16067 fputc(j == BOARD_RGHT - 1 ? '\n' : ' ', fp);
16070 if ((gameMode == EditPosition) ? !blackPlaysFirst : (move % 2 == 0))
16071 fprintf(fp, "white to play\n");
16073 fprintf(fp, "black to play\n");
16077 PrintOpponents (FILE *fp)
16079 if (gameInfo.white != NULL) {
16080 fprintf(fp, "\t%s vs. %s\n", gameInfo.white, gameInfo.black);
16086 /* Find last component of program's own name, using some heuristics */
16088 TidyProgramName (char *prog, char *host, char buf[MSG_SIZ])
16091 int local = (strcmp(host, "localhost") == 0);
16092 while (!local && (p = strchr(prog, ';')) != NULL) {
16094 while (*p == ' ') p++;
16097 if (*prog == '"' || *prog == '\'') {
16098 q = strchr(prog + 1, *prog);
16100 q = strchr(prog, ' ');
16102 if (q == NULL) q = prog + strlen(prog);
16104 while (p >= prog && *p != '/' && *p != '\\') p--;
16106 if(p == prog && *p == '"') p++;
16108 if (q - p >= 4 && StrCaseCmp(q - 4, ".exe") == 0) *q = c, q -= 4; else *q = c;
16109 memcpy(buf, p, q - p);
16110 buf[q - p] = NULLCHAR;
16118 TimeControlTagValue ()
16121 if (!appData.clockMode) {
16122 safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0]));
16123 } else if (movesPerSession > 0) {
16124 snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000);
16125 } else if (timeIncrement == 0) {
16126 snprintf(buf, MSG_SIZ, "%ld", timeControl/1000);
16128 snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000);
16130 return StrSave(buf);
16136 /* This routine is used only for certain modes */
16137 VariantClass v = gameInfo.variant;
16138 ChessMove r = GameUnfinished;
16141 if(keepInfo) return;
16143 if(gameMode == EditGame) { // [HGM] vari: do not erase result on EditGame
16144 r = gameInfo.result;
16145 p = gameInfo.resultDetails;
16146 gameInfo.resultDetails = NULL;
16148 ClearGameInfo(&gameInfo);
16149 gameInfo.variant = v;
16151 switch (gameMode) {
16152 case MachinePlaysWhite:
16153 gameInfo.event = StrSave( appData.pgnEventHeader );
16154 gameInfo.site = StrSave(HostName());
16155 gameInfo.date = PGNDate();
16156 gameInfo.round = StrSave("-");
16157 gameInfo.white = StrSave(first.tidy);
16158 gameInfo.black = StrSave(UserName());
16159 gameInfo.timeControl = TimeControlTagValue();
16162 case MachinePlaysBlack:
16163 gameInfo.event = StrSave( appData.pgnEventHeader );
16164 gameInfo.site = StrSave(HostName());
16165 gameInfo.date = PGNDate();
16166 gameInfo.round = StrSave("-");
16167 gameInfo.white = StrSave(UserName());
16168 gameInfo.black = StrSave(first.tidy);
16169 gameInfo.timeControl = TimeControlTagValue();
16172 case TwoMachinesPlay:
16173 gameInfo.event = StrSave( appData.pgnEventHeader );
16174 gameInfo.site = StrSave(HostName());
16175 gameInfo.date = PGNDate();
16178 snprintf(buf, MSG_SIZ, "%d", roundNr);
16179 gameInfo.round = StrSave(buf);
16181 gameInfo.round = StrSave("-");
16183 if (first.twoMachinesColor[0] == 'w') {
16184 gameInfo.white = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
16185 gameInfo.black = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
16187 gameInfo.white = StrSave(appData.pgnName[1][0] ? appData.pgnName[1] : second.tidy);
16188 gameInfo.black = StrSave(appData.pgnName[0][0] ? appData.pgnName[0] : first.tidy);
16190 gameInfo.timeControl = TimeControlTagValue();
16194 gameInfo.event = StrSave("Edited game");
16195 gameInfo.site = StrSave(HostName());
16196 gameInfo.date = PGNDate();
16197 gameInfo.round = StrSave("-");
16198 gameInfo.white = StrSave("-");
16199 gameInfo.black = StrSave("-");
16200 gameInfo.result = r;
16201 gameInfo.resultDetails = p;
16205 gameInfo.event = StrSave("Edited position");
16206 gameInfo.site = StrSave(HostName());
16207 gameInfo.date = PGNDate();
16208 gameInfo.round = StrSave("-");
16209 gameInfo.white = StrSave("-");
16210 gameInfo.black = StrSave("-");
16213 case IcsPlayingWhite:
16214 case IcsPlayingBlack:
16219 case PlayFromGameFile:
16220 gameInfo.event = StrSave("Game from non-PGN file");
16221 gameInfo.site = StrSave(HostName());
16222 gameInfo.date = PGNDate();
16223 gameInfo.round = StrSave("-");
16224 gameInfo.white = StrSave("?");
16225 gameInfo.black = StrSave("?");
16234 ReplaceComment (int index, char *text)
16240 if(index && sscanf(text, "%f/%d", &score, &len) == 2 &&
16241 pvInfoList[index-1].depth == len &&
16242 fabs(pvInfoList[index-1].score - score*100.) < 0.5 &&
16243 (p = strchr(text, '\n'))) text = p; // [HGM] strip off first line with PV info, if any
16244 while (*text == '\n') text++;
16245 len = strlen(text);
16246 while (len > 0 && text[len - 1] == '\n') len--;
16248 if (commentList[index] != NULL)
16249 free(commentList[index]);
16252 commentList[index] = NULL;
16255 if( *text == '{' && strchr(text, '}') || // [HGM] braces: if certainy malformed, put braces
16256 *text == '[' && strchr(text, ']') || // otherwise hope the user knows what he is doing
16257 *text == '(' && strchr(text, ')')) { // (perhaps check if this parses as comment-only?)
16258 commentList[index] = (char *) malloc(len + 2);
16259 strncpy(commentList[index], text, len);
16260 commentList[index][len] = '\n';
16261 commentList[index][len + 1] = NULLCHAR;
16263 // [HGM] braces: if text does not start with known OK delimiter, put braces around it.
16265 commentList[index] = (char *) malloc(len + 7);
16266 safeStrCpy(commentList[index], "{\n", 3);
16267 safeStrCpy(commentList[index]+2, text, len+1);
16268 commentList[index][len+2] = NULLCHAR;
16269 while(p = strchr(commentList[index], '}')) *p = ')'; // kill all } to make it one comment
16270 strcat(commentList[index], "\n}\n");
16275 CrushCRs (char *text)
16283 if (ch == '\r') continue;
16285 } while (ch != '\0');
16289 AppendComment (int index, char *text, Boolean addBraces)
16290 /* addBraces tells if we should add {} */
16295 if(appData.debugMode) fprintf(debugFP, "Append: in='%s' %d\n", text, addBraces);
16296 if(addBraces == 3) addBraces = 0; else // force appending literally
16297 text = GetInfoFromComment( index, text ); /* [HGM] PV time: strip PV info from comment */
16300 while (*text == '\n') text++;
16301 len = strlen(text);
16302 while (len > 0 && text[len - 1] == '\n') len--;
16303 text[len] = NULLCHAR;
16305 if (len == 0) return;
16307 if (commentList[index] != NULL) {
16308 Boolean addClosingBrace = addBraces;
16309 old = commentList[index];
16310 oldlen = strlen(old);
16311 while(commentList[index][oldlen-1] == '\n')
16312 commentList[index][--oldlen] = NULLCHAR;
16313 commentList[index] = (char *) malloc(oldlen + len + 6); // might waste 4
16314 safeStrCpy(commentList[index], old, oldlen + len + 6);
16316 // [HGM] braces: join "{A\n}\n" + "{\nB}" as "{A\nB\n}"
16317 if(commentList[index][oldlen-1] == '}' && (text[0] == '{' || addBraces == TRUE)) {
16318 if(addBraces == TRUE) addBraces = FALSE; else { text++; len--; }
16319 while (*text == '\n') { text++; len--; }
16320 commentList[index][--oldlen] = NULLCHAR;
16322 if(addBraces) strcat(commentList[index], addBraces == 2 ? "\n(" : "\n{\n");
16323 else strcat(commentList[index], "\n");
16324 strcat(commentList[index], text);
16325 if(addClosingBrace) strcat(commentList[index], addClosingBrace == 2 ? ")\n" : "\n}\n");
16326 else strcat(commentList[index], "\n");
16328 commentList[index] = (char *) malloc(len + 6); // perhaps wastes 4...
16330 safeStrCpy(commentList[index], addBraces == 2 ? "(" : "{\n", 3);
16331 else commentList[index][0] = NULLCHAR;
16332 strcat(commentList[index], text);
16333 strcat(commentList[index], addBraces == 2 ? ")\n" : "\n");
16334 if(addBraces == TRUE) strcat(commentList[index], "}\n");
16339 FindStr (char * text, char * sub_text)
16341 char * result = strstr( text, sub_text );
16343 if( result != NULL ) {
16344 result += strlen( sub_text );
16350 /* [AS] Try to extract PV info from PGN comment */
16351 /* [HGM] PV time: and then remove it, to prevent it appearing twice */
16353 GetInfoFromComment (int index, char * text)
16355 char * sep = text, *p;
16357 if( text != NULL && index > 0 ) {
16360 int time = -1, sec = 0, deci;
16361 char * s_eval = FindStr( text, "[%eval " );
16362 char * s_emt = FindStr( text, "[%emt " );
16364 if( s_eval != NULL || s_emt != NULL ) {
16366 if(0) { // [HGM] this code is not finished, and could actually be detrimental
16371 if( s_eval != NULL ) {
16372 if( sscanf( s_eval, "%d,%d%c", &score, &depth, &delim ) != 3 ) {
16376 if( delim != ']' ) {
16381 if( s_emt != NULL ) {
16386 /* We expect something like: [+|-]nnn.nn/dd */
16389 if(*text != '{') return text; // [HGM] braces: must be normal comment
16391 sep = strchr( text, '/' );
16392 if( sep == NULL || sep < (text+4) ) {
16397 if(!strncmp(p+1, "final score ", 12)) p += 12, index++; else
16398 if(p[1] == '(') { // comment starts with PV
16399 p = strchr(p, ')'); // locate end of PV
16400 if(p == NULL || sep < p+5) return text;
16401 // at this point we have something like "{(.*) +0.23/6 ..."
16402 p = text; while(*++p != ')') p[-1] = *p; p[-1] = ')';
16403 *p = '\n'; while(*p == ' ' || *p == '\n') p++; *--p = '{';
16404 // we now moved the brace to behind the PV: "(.*) {+0.23/6 ..."
16406 time = -1; sec = -1; deci = -1;
16407 if( sscanf( p+1, "%d.%d/%d %d:%d", &score, &score_lo, &depth, &time, &sec ) != 5 &&
16408 sscanf( p+1, "%d.%d/%d %d.%d", &score, &score_lo, &depth, &time, &deci ) != 5 &&
16409 sscanf( p+1, "%d.%d/%d %d", &score, &score_lo, &depth, &time ) != 4 &&
16410 sscanf( p+1, "%d.%d/%d", &score, &score_lo, &depth ) != 3 ) {
16414 if( score_lo < 0 || score_lo >= 100 ) {
16418 if(sec >= 0) time = 600*time + 10*sec; else
16419 if(deci >= 0) time = 10*time + deci; else time *= 10; // deci-sec
16421 score = score > 0 || !score & p[1] != '-' ? score*100 + score_lo : score*100 - score_lo;
16423 /* [HGM] PV time: now locate end of PV info */
16424 while( *++sep >= '0' && *sep <= '9'); // strip depth
16426 while( *++sep >= '0' && *sep <= '9' || *sep == '\n'); // strip time
16428 while( *++sep >= '0' && *sep <= '9'); // strip seconds
16430 while( *++sep >= '0' && *sep <= '9'); // strip fractional seconds
16431 while(*sep == ' ' || *sep == '\n' || *sep == '\r') sep++;
16442 pvInfoList[index-1].depth = depth;
16443 pvInfoList[index-1].score = score;
16444 pvInfoList[index-1].time = 10*time; // centi-sec
16445 if(*sep == '}') *sep = 0; else *--sep = '{';
16446 if(p != text) { while(*p++ = *sep++); sep = text; } // squeeze out space between PV and comment, and return both
16452 SendToProgram (char *message, ChessProgramState *cps)
16454 int count, outCount, error;
16457 if (cps->pr == NoProc) return;
16460 if (appData.debugMode) {
16463 fprintf(debugFP, "%ld >%-6s: %s",
16464 SubtractTimeMarks(&now, &programStartTime),
16465 cps->which, message);
16467 fprintf(serverFP, "%ld >%-6s: %s",
16468 SubtractTimeMarks(&now, &programStartTime),
16469 cps->which, message), fflush(serverFP);
16472 count = strlen(message);
16473 outCount = OutputToProcess(cps->pr, message, count, &error);
16474 if (outCount < count && !exiting
16475 && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */
16476 if(!cps->initDone) return; // [HGM] should not generate fatal error during engine load
16477 snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), _(cps->which));
16478 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
16479 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
16480 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
16481 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
16482 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
16484 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
16485 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
16486 gameInfo.result = res;
16488 gameInfo.resultDetails = StrSave(buf);
16490 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
16491 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
16496 ReceiveFromProgram (InputSourceRef isr, VOIDSTAR closure, char *message, int count, int error)
16500 ChessProgramState *cps = (ChessProgramState *)closure;
16502 if (isr != cps->isr) return; /* Killed intentionally */
16505 RemoveInputSource(cps->isr);
16506 snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"),
16507 _(cps->which), cps->program);
16508 if(LoadError(cps->userError ? NULL : buf, cps)) return; // [HGM] should not generate fatal error during engine load
16509 if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */
16510 if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) {
16511 snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), _(cps->which), cps->program);
16512 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(GameIsDrawn, buf, GE_XBOARD); return; }
16513 gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */
16515 ChessMove res = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins;
16516 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; GameEnds(res, buf, GE_XBOARD); return; }
16517 gameInfo.result = res;
16519 gameInfo.resultDetails = StrSave(buf);
16521 if(matchMode && appData.tourneyFile[0]) { cps->pr = NoProc; return; }
16522 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1;
16524 snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"),
16525 _(cps->which), cps->program);
16526 RemoveInputSource(cps->isr);
16528 /* [AS] Program is misbehaving badly... kill it */
16529 if( count == -2 ) {
16530 DestroyChildProcess( cps->pr, 9 );
16534 if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, error, 1); else errorExitStatus = 1;
16539 if ((end_str = strchr(message, '\r')) != NULL)
16540 *end_str = NULLCHAR;
16541 if ((end_str = strchr(message, '\n')) != NULL)
16542 *end_str = NULLCHAR;
16544 if (appData.debugMode) {
16545 TimeMark now; int print = 1;
16546 char *quote = ""; char c; int i;
16548 if(appData.engineComments != 1) { /* [HGM] debug: decide if protocol-violating output is written */
16549 char start = message[0];
16550 if(start >='A' && start <= 'Z') start += 'a' - 'A'; // be tolerant to capitalizing
16551 if(sscanf(message, "%d%c%d%d%d", &i, &c, &i, &i, &i) != 5 &&
16552 sscanf(message, "move %c", &c)!=1 && sscanf(message, "offer%c", &c)!=1 &&
16553 sscanf(message, "resign%c", &c)!=1 && sscanf(message, "feature %c", &c)!=1 &&
16554 sscanf(message, "error %c", &c)!=1 && sscanf(message, "illegal %c", &c)!=1 &&
16555 sscanf(message, "tell%c", &c)!=1 && sscanf(message, "0-1 %c", &c)!=1 &&
16556 sscanf(message, "1-0 %c", &c)!=1 && sscanf(message, "1/2-1/2 %c", &c)!=1 &&
16557 sscanf(message, "setboard %c", &c)!=1 && sscanf(message, "setup %c", &c)!=1 &&
16558 sscanf(message, "hint: %c", &c)!=1 &&
16559 sscanf(message, "pong %c", &c)!=1 && start != '#') {
16560 quote = appData.engineComments == 2 ? "# " : "### NON-COMPLIANT! ### ";
16561 print = (appData.engineComments >= 2);
16563 message[0] = start; // restore original message
16567 fprintf(debugFP, "%ld <%-6s: %s%s\n",
16568 SubtractTimeMarks(&now, &programStartTime), cps->which,
16572 fprintf(serverFP, "%ld <%-6s: %s%s\n",
16573 SubtractTimeMarks(&now, &programStartTime), cps->which,
16575 message), fflush(serverFP);
16579 /* [DM] if icsEngineAnalyze is active we block all whisper and kibitz output, because nobody want to see this */
16580 if (appData.icsEngineAnalyze) {
16581 if (strstr(message, "whisper") != NULL ||
16582 strstr(message, "kibitz") != NULL ||
16583 strstr(message, "tellics") != NULL) return;
16586 HandleMachineMove(message, cps);
16591 SendTimeControl (ChessProgramState *cps, int mps, long tc, int inc, int sd, int st)
16596 if( timeControl_2 > 0 ) {
16597 if( (gameMode == MachinePlaysBlack) || (gameMode == TwoMachinesPlay && cps->twoMachinesColor[0] == 'b') ) {
16598 tc = timeControl_2;
16601 tc /= cps->timeOdds; /* [HGM] time odds: apply before telling engine */
16602 inc /= cps->timeOdds;
16603 st /= cps->timeOdds;
16605 seconds = (tc / 1000) % 60; /* [HGM] displaced to after applying odds */
16608 /* Set exact time per move, normally using st command */
16609 if (cps->stKludge) {
16610 /* GNU Chess 4 has no st command; uses level in a nonstandard way */
16612 if (seconds == 0) {
16613 snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60);
16615 snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds);
16618 snprintf(buf, MSG_SIZ, "st %d\n", st);
16621 /* Set conventional or incremental time control, using level command */
16622 if (seconds == 0) {
16623 /* Note old gnuchess bug -- minutes:seconds used to not work.
16624 Fixed in later versions, but still avoid :seconds
16625 when seconds is 0. */
16626 snprintf(buf, MSG_SIZ, "level %d %ld %g\n", mps, tc/60000, inc/1000.);
16628 snprintf(buf, MSG_SIZ, "level %d %ld:%02d %g\n", mps, tc/60000,
16629 seconds, inc/1000.);
16632 SendToProgram(buf, cps);
16634 /* Orthoganally (except for GNU Chess 4), limit time to st seconds */
16635 /* Orthogonally, limit search to given depth */
16637 if (cps->sdKludge) {
16638 snprintf(buf, MSG_SIZ, "depth\n%d\n", sd);
16640 snprintf(buf, MSG_SIZ, "sd %d\n", sd);
16642 SendToProgram(buf, cps);
16645 if(cps->nps >= 0) { /* [HGM] nps */
16646 if(cps->supportsNPS == FALSE)
16647 cps->nps = -1; // don't use if engine explicitly says not supported!
16649 snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps);
16650 SendToProgram(buf, cps);
16655 ChessProgramState *
16657 /* [HGM] return pointer to 'first' or 'second', depending on who plays white */
16659 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b' ||
16660 gameMode == BeginningOfGame || gameMode == MachinePlaysBlack)
16666 SendTimeRemaining (ChessProgramState *cps, int machineWhite)
16668 char message[MSG_SIZ];
16671 /* Note: this routine must be called when the clocks are stopped
16672 or when they have *just* been set or switched; otherwise
16673 it will be off by the time since the current tick started.
16675 if (machineWhite) {
16676 time = whiteTimeRemaining / 10;
16677 otime = blackTimeRemaining / 10;
16679 time = blackTimeRemaining / 10;
16680 otime = whiteTimeRemaining / 10;
16682 /* [HGM] translate opponent's time by time-odds factor */
16683 otime = (otime * cps->other->timeOdds) / cps->timeOdds;
16685 if (time <= 0) time = 1;
16686 if (otime <= 0) otime = 1;
16688 snprintf(message, MSG_SIZ, "time %ld\n", time);
16689 SendToProgram(message, cps);
16691 snprintf(message, MSG_SIZ, "otim %ld\n", otime);
16692 SendToProgram(message, cps);
16696 EngineDefinedVariant (ChessProgramState *cps, int n)
16697 { // return name of n-th unknown variant that engine supports
16698 static char buf[MSG_SIZ];
16699 char *p, *s = cps->variants;
16700 if(!s) return NULL;
16701 do { // parse string from variants feature
16703 p = strchr(s, ',');
16704 if(p) *p = NULLCHAR;
16705 v = StringToVariant(s);
16706 if(v == VariantNormal && strcmp(s, "normal") && !strstr(s, "_normal")) v = VariantUnknown; // garbage is recognized as normal
16707 if(v == VariantUnknown) { // non-standard variant in list of engine-supported variants
16708 if(!strcmp(s, "tenjiku") || !strcmp(s, "dai") || !strcmp(s, "dada") || // ignore Alien-Edition variants
16709 !strcmp(s, "maka") || !strcmp(s, "tai") || !strcmp(s, "kyoku") ||
16710 !strcmp(s, "checkers") || !strcmp(s, "go") || !strcmp(s, "reversi") ||
16711 !strcmp(s, "dark") || !strcmp(s, "alien") || !strcmp(s, "multi") || !strcmp(s, "amazons") ) n++;
16712 if(--n < 0) safeStrCpy(buf, s, MSG_SIZ);
16715 if(n < 0) return buf;
16721 BoolFeature (char **p, char *name, int *loc, ChessProgramState *cps)
16724 int len = strlen(name);
16727 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
16729 sscanf(*p, "%d", &val);
16731 while (**p && **p != ' ')
16733 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
16734 SendToProgram(buf, cps);
16741 IntFeature (char **p, char *name, int *loc, ChessProgramState *cps)
16744 int len = strlen(name);
16745 if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') {
16747 sscanf(*p, "%d", loc);
16748 while (**p && **p != ' ') (*p)++;
16749 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
16750 SendToProgram(buf, cps);
16757 StringFeature (char **p, char *name, char **loc, ChessProgramState *cps)
16760 int len = strlen(name);
16761 if (strncmp((*p), name, len) == 0
16762 && (*p)[len] == '=' && (*p)[len+1] == '\"') {
16764 ASSIGN(*loc, *p); // kludge alert: assign rest of line just to be sure allocation is large enough so that sscanf below always fits
16765 sscanf(*p, "%[^\"]", *loc);
16766 while (**p && **p != '\"') (*p)++;
16767 if (**p == '\"') (*p)++;
16768 snprintf(buf, MSG_SIZ, "accepted %s\n", name);
16769 SendToProgram(buf, cps);
16776 ParseOption (Option *opt, ChessProgramState *cps)
16777 // [HGM] options: process the string that defines an engine option, and determine
16778 // name, type, default value, and allowed value range
16780 char *p, *q, buf[MSG_SIZ];
16781 int n, min = (-1)<<31, max = 1<<31, def;
16783 if(p = strstr(opt->name, " -spin ")) {
16784 if((n = sscanf(p, " -spin %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
16785 if(max < min) max = min; // enforce consistency
16786 if(def < min) def = min;
16787 if(def > max) def = max;
16792 } else if((p = strstr(opt->name, " -slider "))) {
16793 // for now -slider is a synonym for -spin, to already provide compatibility with future polyglots
16794 if((n = sscanf(p, " -slider %d %d %d", &def, &min, &max)) < 3 ) return FALSE;
16795 if(max < min) max = min; // enforce consistency
16796 if(def < min) def = min;
16797 if(def > max) def = max;
16801 opt->type = Spin; // Slider;
16802 } else if((p = strstr(opt->name, " -string "))) {
16803 opt->textValue = p+9;
16804 opt->type = TextBox;
16805 } else if((p = strstr(opt->name, " -file "))) {
16806 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
16807 opt->textValue = p+7;
16808 opt->type = FileName; // FileName;
16809 } else if((p = strstr(opt->name, " -path "))) {
16810 // for now -file is a synonym for -string, to already provide compatibility with future polyglots
16811 opt->textValue = p+7;
16812 opt->type = PathName; // PathName;
16813 } else if(p = strstr(opt->name, " -check ")) {
16814 if(sscanf(p, " -check %d", &def) < 1) return FALSE;
16815 opt->value = (def != 0);
16816 opt->type = CheckBox;
16817 } else if(p = strstr(opt->name, " -combo ")) {
16818 opt->textValue = (char*) (opt->choice = &cps->comboList[cps->comboCnt]); // cheat with pointer type
16819 cps->comboList[cps->comboCnt++] = q = p+8; // holds possible choices
16820 if(*q == '*') cps->comboList[cps->comboCnt-1]++;
16821 opt->value = n = 0;
16822 while(q = StrStr(q, " /// ")) {
16823 n++; *q = 0; // count choices, and null-terminate each of them
16825 if(*q == '*') { // remember default, which is marked with * prefix
16829 cps->comboList[cps->comboCnt++] = q;
16831 cps->comboList[cps->comboCnt++] = NULL;
16833 opt->type = ComboBox;
16834 } else if(p = strstr(opt->name, " -button")) {
16835 opt->type = Button;
16836 } else if(p = strstr(opt->name, " -save")) {
16837 opt->type = SaveButton;
16838 } else return FALSE;
16839 *p = 0; // terminate option name
16840 // now look if the command-line options define a setting for this engine option.
16841 if(cps->optionSettings && cps->optionSettings[0])
16842 p = strstr(cps->optionSettings, opt->name); else p = NULL;
16843 if(p && (p == cps->optionSettings || p[-1] == ',')) {
16844 snprintf(buf, MSG_SIZ, "option %s", p);
16845 if(p = strstr(buf, ",")) *p = 0;
16846 if(q = strchr(buf, '=')) switch(opt->type) {
16848 for(n=0; n<opt->max; n++)
16849 if(!strcmp(((char**)opt->textValue)[n], q+1)) opt->value = n;
16852 safeStrCpy(opt->textValue, q+1, MSG_SIZ - (opt->textValue - opt->name));
16856 opt->value = atoi(q+1);
16861 SendToProgram(buf, cps);
16867 FeatureDone (ChessProgramState *cps, int val)
16869 DelayedEventCallback cb = GetDelayedEvent();
16870 if ((cb == InitBackEnd3 && cps == &first) ||
16871 (cb == SettingsMenuIfReady && cps == &second) ||
16872 (cb == LoadEngine) ||
16873 (cb == TwoMachinesEventIfReady)) {
16874 CancelDelayedEvent();
16875 ScheduleDelayedEvent(cb, val ? 1 : 3600000);
16877 cps->initDone = val;
16878 if(val) cps->reload = FALSE;
16881 /* Parse feature command from engine */
16883 ParseFeatures (char *args, ChessProgramState *cps)
16891 while (*p == ' ') p++;
16892 if (*p == NULLCHAR) return;
16894 if (BoolFeature(&p, "setboard", &cps->useSetboard, cps)) continue;
16895 if (BoolFeature(&p, "xedit", &cps->extendedEdit, cps)) continue;
16896 if (BoolFeature(&p, "time", &cps->sendTime, cps)) continue;
16897 if (BoolFeature(&p, "draw", &cps->sendDrawOffers, cps)) continue;
16898 if (BoolFeature(&p, "sigint", &cps->useSigint, cps)) continue;
16899 if (BoolFeature(&p, "sigterm", &cps->useSigterm, cps)) continue;
16900 if (BoolFeature(&p, "reuse", &val, cps)) {
16901 /* Engine can disable reuse, but can't enable it if user said no */
16902 if (!val) cps->reuse = FALSE;
16905 if (BoolFeature(&p, "analyze", &cps->analysisSupport, cps)) continue;
16906 if (StringFeature(&p, "myname", &cps->tidy, cps)) {
16907 if (gameMode == TwoMachinesPlay) {
16908 DisplayTwoMachinesTitle();
16914 if (StringFeature(&p, "variants", &cps->variants, cps)) continue;
16915 if (BoolFeature(&p, "san", &cps->useSAN, cps)) continue;
16916 if (BoolFeature(&p, "ping", &cps->usePing, cps)) continue;
16917 if (BoolFeature(&p, "playother", &cps->usePlayother, cps)) continue;
16918 if (BoolFeature(&p, "colors", &cps->useColors, cps)) continue;
16919 if (BoolFeature(&p, "usermove", &cps->useUsermove, cps)) continue;
16920 if (BoolFeature(&p, "exclude", &cps->excludeMoves, cps)) continue;
16921 if (BoolFeature(&p, "ics", &cps->sendICS, cps)) continue;
16922 if (BoolFeature(&p, "name", &cps->sendName, cps)) continue;
16923 if (BoolFeature(&p, "pause", &cps->pause, cps)) continue; // [HGM] pause
16924 if (IntFeature(&p, "done", &val, cps)) {
16925 FeatureDone(cps, val);
16928 /* Added by Tord: */
16929 if (BoolFeature(&p, "fen960", &cps->useFEN960, cps)) continue;
16930 if (BoolFeature(&p, "oocastle", &cps->useOOCastle, cps)) continue;
16931 /* End of additions by Tord */
16933 /* [HGM] added features: */
16934 if (BoolFeature(&p, "highlight", &cps->highlight, cps)) continue;
16935 if (BoolFeature(&p, "debug", &cps->debug, cps)) continue;
16936 if (BoolFeature(&p, "nps", &cps->supportsNPS, cps)) continue;
16937 if (IntFeature(&p, "level", &cps->maxNrOfSessions, cps)) continue;
16938 if (BoolFeature(&p, "memory", &cps->memSize, cps)) continue;
16939 if (BoolFeature(&p, "smp", &cps->maxCores, cps)) continue;
16940 if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue;
16941 if (StringFeature(&p, "option", &q, cps)) { // read to freshly allocated temp buffer first
16942 if(cps->reload) { FREE(q); q = NULL; continue; } // we are reloading because of xreuse
16943 FREE(cps->option[cps->nrOptions].name);
16944 cps->option[cps->nrOptions].name = q; q = NULL;
16945 if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature
16946 snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name);
16947 SendToProgram(buf, cps);
16950 if(cps->nrOptions >= MAX_OPTIONS) {
16952 snprintf(buf, MSG_SIZ, _("%s engine has too many options\n"), _(cps->which));
16953 DisplayError(buf, 0);
16957 /* End of additions by HGM */
16959 /* unknown feature: complain and skip */
16961 while (*q && *q != '=') q++;
16962 snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p);
16963 SendToProgram(buf, cps);
16969 while (*p && *p != '\"') p++;
16970 if (*p == '\"') p++;
16972 while (*p && *p != ' ') p++;
16980 PeriodicUpdatesEvent (int newState)
16982 if (newState == appData.periodicUpdates)
16985 appData.periodicUpdates=newState;
16987 /* Display type changes, so update it now */
16988 // DisplayAnalysis();
16990 /* Get the ball rolling again... */
16992 AnalysisPeriodicEvent(1);
16993 StartAnalysisClock();
16998 PonderNextMoveEvent (int newState)
17000 if (newState == appData.ponderNextMove) return;
17001 if (gameMode == EditPosition) EditPositionDone(TRUE);
17003 SendToProgram("hard\n", &first);
17004 if (gameMode == TwoMachinesPlay) {
17005 SendToProgram("hard\n", &second);
17008 SendToProgram("easy\n", &first);
17009 thinkOutput[0] = NULLCHAR;
17010 if (gameMode == TwoMachinesPlay) {
17011 SendToProgram("easy\n", &second);
17014 appData.ponderNextMove = newState;
17018 NewSettingEvent (int option, int *feature, char *command, int value)
17022 if (gameMode == EditPosition) EditPositionDone(TRUE);
17023 snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value);
17024 if(feature == NULL || *feature) SendToProgram(buf, &first);
17025 if (gameMode == TwoMachinesPlay) {
17026 if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second);
17031 ShowThinkingEvent ()
17032 // [HGM] thinking: this routine is now also called from "Options -> Engine..." popup
17034 static int oldState = 2; // kludge alert! Neither true nor fals, so first time oldState is always updated
17035 int newState = appData.showThinking
17036 // [HGM] thinking: other features now need thinking output as well
17037 || !appData.hideThinkingFromHuman || appData.adjudicateLossThreshold != 0 || EngineOutputIsUp();
17039 if (oldState == newState) return;
17040 oldState = newState;
17041 if (gameMode == EditPosition) EditPositionDone(TRUE);
17043 SendToProgram("post\n", &first);
17044 if (gameMode == TwoMachinesPlay) {
17045 SendToProgram("post\n", &second);
17048 SendToProgram("nopost\n", &first);
17049 thinkOutput[0] = NULLCHAR;
17050 if (gameMode == TwoMachinesPlay) {
17051 SendToProgram("nopost\n", &second);
17054 // appData.showThinking = newState; // [HGM] thinking: responsible option should already have be changed when calling this routine!
17058 AskQuestionEvent (char *title, char *question, char *replyPrefix, char *which)
17060 ProcRef pr = (which[0] == '1') ? first.pr : second.pr;
17061 if (pr == NoProc) return;
17062 AskQuestion(title, question, replyPrefix, pr);
17066 TypeInEvent (char firstChar)
17068 if ((gameMode == BeginningOfGame && !appData.icsActive) ||
17069 gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack ||
17070 gameMode == AnalyzeMode || gameMode == EditGame ||
17071 gameMode == EditPosition || gameMode == IcsExamining ||
17072 gameMode == IcsPlayingWhite || gameMode == IcsPlayingBlack ||
17073 isdigit(firstChar) && // [HGM] movenum: allow typing in of move nr in 'passive' modes
17074 ( gameMode == AnalyzeFile || gameMode == PlayFromGameFile ||
17075 gameMode == IcsObserving || gameMode == TwoMachinesPlay ) ||
17076 gameMode == Training) PopUpMoveDialog(firstChar);
17080 TypeInDoneEvent (char *move)
17083 int n, fromX, fromY, toX, toY;
17085 ChessMove moveType;
17088 if(gameMode == EditPosition && ParseFEN(board, &n, move, TRUE) ) {
17089 EditPositionPasteFEN(move);
17092 // [HGM] movenum: allow move number to be typed in any mode
17093 if(sscanf(move, "%d", &n) == 1 && n != 0 ) {
17097 // undocumented kludge: allow command-line option to be typed in!
17098 // (potentially fatal, and does not implement the effect of the option.)
17099 // should only be used for options that are values on which future decisions will be made,
17100 // and definitely not on options that would be used during initialization.
17101 if(strstr(move, "!!! -") == move) {
17102 ParseArgsFromString(move+4);
17106 if (gameMode != EditGame && currentMove != forwardMostMove &&
17107 gameMode != Training) {
17108 DisplayMoveError(_("Displayed move is not current"));
17110 int ok = ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
17111 &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
17112 if(!ok && move[0] >= 'a') { move[0] += 'A' - 'a'; ok = 2; } // [HGM] try also capitalized
17113 if (ok==1 || ok && ParseOneMove(move, gameMode == EditPosition ? blackPlaysFirst : currentMove,
17114 &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) {
17115 UserMoveEvent(fromX, fromY, toX, toY, promoChar);
17117 DisplayMoveError(_("Could not parse move"));
17123 DisplayMove (int moveNumber)
17125 char message[MSG_SIZ];
17127 char cpThinkOutput[MSG_SIZ];
17129 if(appData.noGUI) return; // [HGM] fast: suppress display of moves
17131 if (moveNumber == forwardMostMove - 1 ||
17132 gameMode == AnalyzeMode || gameMode == AnalyzeFile) {
17134 safeStrCpy(cpThinkOutput, thinkOutput, sizeof(cpThinkOutput)/sizeof(cpThinkOutput[0]));
17136 if (strchr(cpThinkOutput, '\n')) {
17137 *strchr(cpThinkOutput, '\n') = NULLCHAR;
17140 *cpThinkOutput = NULLCHAR;
17143 /* [AS] Hide thinking from human user */
17144 if( appData.hideThinkingFromHuman && gameMode != TwoMachinesPlay ) {
17145 *cpThinkOutput = NULLCHAR;
17146 if( thinkOutput[0] != NULLCHAR ) {
17149 for( i=0; i<=hiddenThinkOutputState; i++ ) {
17150 cpThinkOutput[i] = '.';
17152 cpThinkOutput[i] = NULLCHAR;
17153 hiddenThinkOutputState = (hiddenThinkOutputState + 1) % 3;
17157 if (moveNumber == forwardMostMove - 1 &&
17158 gameInfo.resultDetails != NULL) {
17159 if (gameInfo.resultDetails[0] == NULLCHAR) {
17160 snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result));
17162 snprintf(res, MSG_SIZ, " {%s} %s",
17163 T_(gameInfo.resultDetails), PGNResult(gameInfo.result));
17169 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
17170 DisplayMessage(res, cpThinkOutput);
17172 snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1,
17173 WhiteOnMove(moveNumber) ? " " : ".. ",
17174 parseList[moveNumber], res);
17175 DisplayMessage(message, cpThinkOutput);
17180 DisplayComment (int moveNumber, char *text)
17182 char title[MSG_SIZ];
17184 if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) {
17185 safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0]));
17187 snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1,
17188 WhiteOnMove(moveNumber) ? " " : ".. ",
17189 parseList[moveNumber]);
17191 if (text != NULL && (appData.autoDisplayComment || commentUp))
17192 CommentPopUp(title, text);
17195 /* This routine sends a ^C interrupt to gnuchess, to awaken it if it
17196 * might be busy thinking or pondering. It can be omitted if your
17197 * gnuchess is configured to stop thinking immediately on any user
17198 * input. However, that gnuchess feature depends on the FIONREAD
17199 * ioctl, which does not work properly on some flavors of Unix.
17202 Attention (ChessProgramState *cps)
17205 if (!cps->useSigint) return;
17206 if (appData.noChessProgram || (cps->pr == NoProc)) return;
17207 switch (gameMode) {
17208 case MachinePlaysWhite:
17209 case MachinePlaysBlack:
17210 case TwoMachinesPlay:
17211 case IcsPlayingWhite:
17212 case IcsPlayingBlack:
17215 /* Skip if we know it isn't thinking */
17216 if (!cps->maybeThinking) return;
17217 if (appData.debugMode)
17218 fprintf(debugFP, "Interrupting %s\n", cps->which);
17219 InterruptChildProcess(cps->pr);
17220 cps->maybeThinking = FALSE;
17225 #endif /*ATTENTION*/
17231 if (whiteTimeRemaining <= 0) {
17234 if (appData.icsActive) {
17235 if (appData.autoCallFlag &&
17236 gameMode == IcsPlayingBlack && !blackFlag) {
17237 SendToICS(ics_prefix);
17238 SendToICS("flag\n");
17242 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
17244 if(gameMode != TwoMachinesPlay) DisplayTitle(_("White's flag fell"));
17245 if (appData.autoCallFlag) {
17246 GameEnds(BlackWins, "Black wins on time", GE_XBOARD);
17253 if (blackTimeRemaining <= 0) {
17256 if (appData.icsActive) {
17257 if (appData.autoCallFlag &&
17258 gameMode == IcsPlayingWhite && !whiteFlag) {
17259 SendToICS(ics_prefix);
17260 SendToICS("flag\n");
17264 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Both flags fell"));
17266 if(gameMode != TwoMachinesPlay) DisplayTitle(_("Black's flag fell"));
17267 if (appData.autoCallFlag) {
17268 GameEnds(WhiteWins, "White wins on time", GE_XBOARD);
17279 CheckTimeControl ()
17281 if (!appData.clockMode || appData.icsActive || searchTime || // [HGM] st: no inc in st mode
17282 gameMode == PlayFromGameFile || forwardMostMove == 0) return;
17285 * add time to clocks when time control is achieved ([HGM] now also used for increment)
17287 if ( !WhiteOnMove(forwardMostMove) ) {
17288 /* White made time control */
17289 lastWhite -= whiteTimeRemaining; // [HGM] contains start time, socalculate thinking time
17290 whiteTimeRemaining += GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, lastWhite, whiteTC)
17291 /* [HGM] time odds: correct new time quota for time odds! */
17292 / WhitePlayer()->timeOdds;
17293 lastBlack = blackTimeRemaining; // [HGM] leave absolute time (after quota), so next switch we can us it to calculate thinking time
17295 lastBlack -= blackTimeRemaining;
17296 /* Black made time control */
17297 blackTimeRemaining += GetTimeQuota((forwardMostMove-blackStartMove-1)/2, lastBlack, blackTC)
17298 / WhitePlayer()->other->timeOdds;
17299 lastWhite = whiteTimeRemaining;
17304 DisplayBothClocks ()
17306 int wom = gameMode == EditPosition ?
17307 !blackPlaysFirst : WhiteOnMove(currentMove);
17308 DisplayWhiteClock(whiteTimeRemaining, wom);
17309 DisplayBlackClock(blackTimeRemaining, !wom);
17313 /* Timekeeping seems to be a portability nightmare. I think everyone
17314 has ftime(), but I'm really not sure, so I'm including some ifdefs
17315 to use other calls if you don't. Clocks will be less accurate if
17316 you have neither ftime nor gettimeofday.
17319 /* VS 2008 requires the #include outside of the function */
17320 #if !HAVE_GETTIMEOFDAY && HAVE_FTIME
17321 #include <sys/timeb.h>
17324 /* Get the current time as a TimeMark */
17326 GetTimeMark (TimeMark *tm)
17328 #if HAVE_GETTIMEOFDAY
17330 struct timeval timeVal;
17331 struct timezone timeZone;
17333 gettimeofday(&timeVal, &timeZone);
17334 tm->sec = (long) timeVal.tv_sec;
17335 tm->ms = (int) (timeVal.tv_usec / 1000L);
17337 #else /*!HAVE_GETTIMEOFDAY*/
17340 // include <sys/timeb.h> / moved to just above start of function
17341 struct timeb timeB;
17344 tm->sec = (long) timeB.time;
17345 tm->ms = (int) timeB.millitm;
17347 #else /*!HAVE_FTIME && !HAVE_GETTIMEOFDAY*/
17348 tm->sec = (long) time(NULL);
17354 /* Return the difference in milliseconds between two
17355 time marks. We assume the difference will fit in a long!
17358 SubtractTimeMarks (TimeMark *tm2, TimeMark *tm1)
17360 return 1000L*(tm2->sec - tm1->sec) +
17361 (long) (tm2->ms - tm1->ms);
17366 * Code to manage the game clocks.
17368 * In tournament play, black starts the clock and then white makes a move.
17369 * We give the human user a slight advantage if he is playing white---the
17370 * clocks don't run until he makes his first move, so it takes zero time.
17371 * Also, we don't account for network lag, so we could get out of sync
17372 * with GNU Chess's clock -- but then, referees are always right.
17375 static TimeMark tickStartTM;
17376 static long intendedTickLength;
17379 NextTickLength (long timeRemaining)
17381 long nominalTickLength, nextTickLength;
17383 if (timeRemaining > 0L && timeRemaining <= 10000L)
17384 nominalTickLength = 100L;
17386 nominalTickLength = 1000L;
17387 nextTickLength = timeRemaining % nominalTickLength;
17388 if (nextTickLength <= 0) nextTickLength += nominalTickLength;
17390 return nextTickLength;
17393 /* Adjust clock one minute up or down */
17395 AdjustClock (Boolean which, int dir)
17397 if(appData.autoCallFlag) { DisplayError(_("Clock adjustment not allowed in auto-flag mode"), 0); return; }
17398 if(which) blackTimeRemaining += 60000*dir;
17399 else whiteTimeRemaining += 60000*dir;
17400 DisplayBothClocks();
17401 adjustedClock = TRUE;
17404 /* Stop clocks and reset to a fresh time control */
17408 (void) StopClockTimer();
17409 if (appData.icsActive) {
17410 whiteTimeRemaining = blackTimeRemaining = 0;
17411 } else if (searchTime) {
17412 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
17413 blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
17414 } else { /* [HGM] correct new time quote for time odds */
17415 whiteTC = blackTC = fullTimeControlString;
17416 whiteTimeRemaining = GetTimeQuota(-1, 0, whiteTC) / WhitePlayer()->timeOdds;
17417 blackTimeRemaining = GetTimeQuota(-1, 0, blackTC) / WhitePlayer()->other->timeOdds;
17419 if (whiteFlag || blackFlag) {
17421 whiteFlag = blackFlag = FALSE;
17423 lastWhite = lastBlack = whiteStartMove = blackStartMove = 0;
17424 DisplayBothClocks();
17425 adjustedClock = FALSE;
17428 #define FUDGE 25 /* 25ms = 1/40 sec; should be plenty even for 50 Hz clocks */
17430 /* Decrement running clock by amount of time that has passed */
17434 long timeRemaining;
17435 long lastTickLength, fudge;
17438 if (!appData.clockMode) return;
17439 if (gameMode==AnalyzeMode || gameMode == AnalyzeFile) return;
17443 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
17445 /* Fudge if we woke up a little too soon */
17446 fudge = intendedTickLength - lastTickLength;
17447 if (fudge < 0 || fudge > FUDGE) fudge = 0;
17449 if (WhiteOnMove(forwardMostMove)) {
17450 if(whiteNPS >= 0) lastTickLength = 0;
17451 timeRemaining = whiteTimeRemaining -= lastTickLength;
17452 if(timeRemaining < 0 && !appData.icsActive) {
17453 GetTimeQuota((forwardMostMove-whiteStartMove-1)/2, 0, whiteTC); // sets suddenDeath & nextSession;
17454 if(suddenDeath) { // [HGM] if we run out of a non-last incremental session, go to the next
17455 whiteStartMove = forwardMostMove; whiteTC = nextSession;
17456 lastWhite= timeRemaining = whiteTimeRemaining += GetTimeQuota(-1, 0, whiteTC);
17459 DisplayWhiteClock(whiteTimeRemaining - fudge,
17460 WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
17462 if(blackNPS >= 0) lastTickLength = 0;
17463 timeRemaining = blackTimeRemaining -= lastTickLength;
17464 if(timeRemaining < 0 && !appData.icsActive) { // [HGM] if we run out of a non-last incremental session, go to the next
17465 GetTimeQuota((forwardMostMove-blackStartMove-1)/2, 0, blackTC);
17467 blackStartMove = forwardMostMove;
17468 lastBlack = timeRemaining = blackTimeRemaining += GetTimeQuota(-1, 0, blackTC=nextSession);
17471 DisplayBlackClock(blackTimeRemaining - fudge,
17472 !WhiteOnMove(currentMove < forwardMostMove ? currentMove : forwardMostMove));
17474 if (CheckFlags()) return;
17476 if(twoBoards) { // count down secondary board's clocks as well
17477 activePartnerTime -= lastTickLength;
17479 if(activePartner == 'W')
17480 DisplayWhiteClock(activePartnerTime, TRUE); // the counting clock is always the highlighted one!
17482 DisplayBlackClock(activePartnerTime, TRUE);
17487 intendedTickLength = NextTickLength(timeRemaining - fudge) + fudge;
17488 StartClockTimer(intendedTickLength);
17490 /* if the time remaining has fallen below the alarm threshold, sound the
17491 * alarm. if the alarm has sounded and (due to a takeback or time control
17492 * with increment) the time remaining has increased to a level above the
17493 * threshold, reset the alarm so it can sound again.
17496 if (appData.icsActive && appData.icsAlarm) {
17498 /* make sure we are dealing with the user's clock */
17499 if (!( ((gameMode == IcsPlayingWhite) && WhiteOnMove(currentMove)) ||
17500 ((gameMode == IcsPlayingBlack) && !WhiteOnMove(currentMove))
17503 if (alarmSounded && (timeRemaining > appData.icsAlarmTime)) {
17504 alarmSounded = FALSE;
17505 } else if (!alarmSounded && (timeRemaining <= appData.icsAlarmTime)) {
17507 alarmSounded = TRUE;
17513 /* A player has just moved, so stop the previously running
17514 clock and (if in clock mode) start the other one.
17515 We redisplay both clocks in case we're in ICS mode, because
17516 ICS gives us an update to both clocks after every move.
17517 Note that this routine is called *after* forwardMostMove
17518 is updated, so the last fractional tick must be subtracted
17519 from the color that is *not* on move now.
17522 SwitchClocks (int newMoveNr)
17524 long lastTickLength;
17526 int flagged = FALSE;
17530 if (StopClockTimer() && appData.clockMode) {
17531 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
17532 if (!WhiteOnMove(forwardMostMove)) {
17533 if(blackNPS >= 0) lastTickLength = 0;
17534 blackTimeRemaining -= lastTickLength;
17535 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
17536 // if(pvInfoList[forwardMostMove].time == -1)
17537 pvInfoList[forwardMostMove].time = // use GUI time
17538 (timeRemaining[1][forwardMostMove-1] - blackTimeRemaining)/10;
17540 if(whiteNPS >= 0) lastTickLength = 0;
17541 whiteTimeRemaining -= lastTickLength;
17542 /* [HGM] PGNtime: save time for PGN file if engine did not give it */
17543 // if(pvInfoList[forwardMostMove].time == -1)
17544 pvInfoList[forwardMostMove].time =
17545 (timeRemaining[0][forwardMostMove-1] - whiteTimeRemaining)/10;
17547 flagged = CheckFlags();
17549 forwardMostMove = newMoveNr; // [HGM] race: change stm when no timer interrupt scheduled
17550 CheckTimeControl();
17552 if (flagged || !appData.clockMode) return;
17554 switch (gameMode) {
17555 case MachinePlaysBlack:
17556 case MachinePlaysWhite:
17557 case BeginningOfGame:
17558 if (pausing) return;
17562 case PlayFromGameFile:
17570 if (searchTime) { // [HGM] st: set clock of player that has to move to max time
17571 if(WhiteOnMove(forwardMostMove))
17572 whiteTimeRemaining = 1000*searchTime / WhitePlayer()->timeOdds;
17573 else blackTimeRemaining = 1000*searchTime / WhitePlayer()->other->timeOdds;
17577 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
17578 whiteTimeRemaining : blackTimeRemaining);
17579 StartClockTimer(intendedTickLength);
17583 /* Stop both clocks */
17587 long lastTickLength;
17590 if (!StopClockTimer()) return;
17591 if (!appData.clockMode) return;
17595 lastTickLength = SubtractTimeMarks(&now, &tickStartTM);
17596 if (WhiteOnMove(forwardMostMove)) {
17597 if(whiteNPS >= 0) lastTickLength = 0;
17598 whiteTimeRemaining -= lastTickLength;
17599 DisplayWhiteClock(whiteTimeRemaining, WhiteOnMove(currentMove));
17601 if(blackNPS >= 0) lastTickLength = 0;
17602 blackTimeRemaining -= lastTickLength;
17603 DisplayBlackClock(blackTimeRemaining, !WhiteOnMove(currentMove));
17608 /* Start clock of player on move. Time may have been reset, so
17609 if clock is already running, stop and restart it. */
17613 (void) StopClockTimer(); /* in case it was running already */
17614 DisplayBothClocks();
17615 if (CheckFlags()) return;
17617 if (!appData.clockMode) return;
17618 if (gameMode == AnalyzeMode || gameMode == AnalyzeFile) return;
17620 GetTimeMark(&tickStartTM);
17621 intendedTickLength = NextTickLength(WhiteOnMove(forwardMostMove) ?
17622 whiteTimeRemaining : blackTimeRemaining);
17624 /* [HGM] nps: figure out nps factors, by determining which engine plays white and/or black once and for all */
17625 whiteNPS = blackNPS = -1;
17626 if(gameMode == MachinePlaysWhite || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w'
17627 || appData.zippyPlay && gameMode == IcsPlayingBlack) // first (perhaps only) engine has white
17628 whiteNPS = first.nps;
17629 if(gameMode == MachinePlaysBlack || gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b'
17630 || appData.zippyPlay && gameMode == IcsPlayingWhite) // first (perhaps only) engine has black
17631 blackNPS = first.nps;
17632 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'b') // second only used in Two-Machines mode
17633 whiteNPS = second.nps;
17634 if(gameMode == TwoMachinesPlay && first.twoMachinesColor[0] == 'w')
17635 blackNPS = second.nps;
17636 if(appData.debugMode) fprintf(debugFP, "nps: w=%d, b=%d\n", whiteNPS, blackNPS);
17638 StartClockTimer(intendedTickLength);
17642 TimeString (long ms)
17644 long second, minute, hour, day;
17646 static char buf[32];
17648 if (ms > 0 && ms <= 9900) {
17649 /* convert milliseconds to tenths, rounding up */
17650 double tenths = floor( ((double)(ms + 99L)) / 100.00 );
17652 snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0);
17656 /* convert milliseconds to seconds, rounding up */
17657 /* use floating point to avoid strangeness of integer division
17658 with negative dividends on many machines */
17659 second = (long) floor(((double) (ms + 999L)) / 1000.0);
17666 day = second / (60 * 60 * 24);
17667 second = second % (60 * 60 * 24);
17668 hour = second / (60 * 60);
17669 second = second % (60 * 60);
17670 minute = second / 60;
17671 second = second % 60;
17674 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ",
17675 sign, day, hour, minute, second);
17677 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second);
17679 snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second);
17686 * This is necessary because some C libraries aren't ANSI C compliant yet.
17689 StrStr (char *string, char *match)
17693 length = strlen(match);
17695 for (i = strlen(string) - length; i >= 0; i--, string++)
17696 if (!strncmp(match, string, length))
17703 StrCaseStr (char *string, char *match)
17707 length = strlen(match);
17709 for (i = strlen(string) - length; i >= 0; i--, string++) {
17710 for (j = 0; j < length; j++) {
17711 if (ToLower(match[j]) != ToLower(string[j]))
17714 if (j == length) return string;
17722 StrCaseCmp (char *s1, char *s2)
17727 c1 = ToLower(*s1++);
17728 c2 = ToLower(*s2++);
17729 if (c1 > c2) return 1;
17730 if (c1 < c2) return -1;
17731 if (c1 == NULLCHAR) return 0;
17739 return isupper(c) ? tolower(c) : c;
17746 return islower(c) ? toupper(c) : c;
17748 #endif /* !_amigados */
17755 if ((ret = (char *) malloc(strlen(s) + 1)))
17757 safeStrCpy(ret, s, strlen(s)+1);
17763 StrSavePtr (char *s, char **savePtr)
17768 if ((*savePtr = (char *) malloc(strlen(s) + 1))) {
17769 safeStrCpy(*savePtr, s, strlen(s)+1);
17781 clock = time((time_t *)NULL);
17782 tm = localtime(&clock);
17783 snprintf(buf, MSG_SIZ, "%04d.%02d.%02d",
17784 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday);
17785 return StrSave(buf);
17790 PositionToFEN (int move, char *overrideCastling, int moveCounts)
17792 int i, j, fromX, fromY, toX, toY;
17799 whiteToPlay = (gameMode == EditPosition) ?
17800 !blackPlaysFirst : (move % 2 == 0);
17803 /* Piece placement data */
17804 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
17805 if(MSG_SIZ - (p - buf) < BOARD_RGHT - BOARD_LEFT + 20) { *p = 0; return StrSave(buf); }
17807 for (j = BOARD_LEFT; j < BOARD_RGHT; j++) {
17808 if (boards[move][i][j] == EmptySquare) {
17810 } else { ChessSquare piece = boards[move][i][j];
17811 if (emptycount > 0) {
17812 if(emptycount<10) /* [HGM] can be >= 10 */
17813 *p++ = '0' + emptycount;
17814 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
17817 if(PieceToChar(piece) == '+') {
17818 /* [HGM] write promoted pieces as '+<unpromoted>' (Shogi) */
17820 piece = (ChessSquare)(CHUDEMOTED piece);
17822 *p++ = (piece == DarkSquare ? '*' : PieceToChar(piece));
17824 /* [HGM] flag promoted pieces as '<promoted>~' (Crazyhouse) */
17825 p[-1] = PieceToChar((ChessSquare)(CHUDEMOTED piece));
17830 if (emptycount > 0) {
17831 if(emptycount<10) /* [HGM] can be >= 10 */
17832 *p++ = '0' + emptycount;
17833 else { *p++ = '0' + emptycount/10; *p++ = '0' + emptycount%10; }
17840 /* [HGM] print Crazyhouse or Shogi holdings */
17841 if( gameInfo.holdingsWidth ) {
17842 *(p-1) = '['; /* if we wanted to support BFEN, this could be '/' */
17844 for(i=0; i<gameInfo.holdingsSize; i++) { /* white holdings */
17845 piece = boards[move][i][BOARD_WIDTH-1];
17846 if( piece != EmptySquare )
17847 for(j=0; j<(int) boards[move][i][BOARD_WIDTH-2]; j++)
17848 *p++ = PieceToChar(piece);
17850 for(i=0; i<gameInfo.holdingsSize; i++) { /* black holdings */
17851 piece = boards[move][BOARD_HEIGHT-i-1][0];
17852 if( piece != EmptySquare )
17853 for(j=0; j<(int) boards[move][BOARD_HEIGHT-i-1][1]; j++)
17854 *p++ = PieceToChar(piece);
17857 if( q == p ) *p++ = '-';
17863 *p++ = whiteToPlay ? 'w' : 'b';
17866 if(q = overrideCastling) { // [HGM] FRC: override castling & e.p fields for non-compliant engines
17867 while(*p++ = *q++); if(q != overrideCastling+1) p[-1] = ' '; else --p;
17869 if(nrCastlingRights) {
17870 int handW=0, handB=0;
17871 if(gameInfo.variant == VariantSChess) { // for S-Chess, all virgin backrank pieces must be listed
17872 for(i=0; i<BOARD_HEIGHT; i++) handW += boards[move][i][BOARD_RGHT]; // count white held pieces
17873 for(i=0; i<BOARD_HEIGHT; i++) handB += boards[move][i][BOARD_LEFT-1]; // count black held pieces
17876 if(appData.fischerCastling) {
17877 if(handW) { // in shuffle S-Chess simply dump all virgin pieces
17878 for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--)
17879 if(boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
17881 /* [HGM] write directly from rights */
17882 if(boards[move][CASTLING][2] != NoRights &&
17883 boards[move][CASTLING][0] != NoRights )
17884 *p++ = boards[move][CASTLING][0] + AAA + 'A' - 'a';
17885 if(boards[move][CASTLING][2] != NoRights &&
17886 boards[move][CASTLING][1] != NoRights )
17887 *p++ = boards[move][CASTLING][1] + AAA + 'A' - 'a';
17890 for(i=BOARD_RGHT-1; i>=BOARD_LEFT; i--)
17891 if(boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
17893 if(boards[move][CASTLING][5] != NoRights &&
17894 boards[move][CASTLING][3] != NoRights )
17895 *p++ = boards[move][CASTLING][3] + AAA;
17896 if(boards[move][CASTLING][5] != NoRights &&
17897 boards[move][CASTLING][4] != NoRights )
17898 *p++ = boards[move][CASTLING][4] + AAA;
17902 /* [HGM] write true castling rights */
17903 if( nrCastlingRights == 6 ) {
17905 if(boards[move][CASTLING][0] == BOARD_RGHT-1 &&
17906 boards[move][CASTLING][2] != NoRights ) k = 1, *p++ = 'K';
17907 q = (boards[move][CASTLING][1] == BOARD_LEFT &&
17908 boards[move][CASTLING][2] != NoRights );
17909 if(handW) { // for S-Chess with pieces in hand, list virgin pieces between K and Q
17910 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q; i--)
17911 if((boards[move][0][i] != WhiteKing || k+q == 0) &&
17912 boards[move][VIRGIN][i] & VIRGIN_W) *p++ = i + AAA + 'A' - 'a';
17916 if(boards[move][CASTLING][3] == BOARD_RGHT-1 &&
17917 boards[move][CASTLING][5] != NoRights ) k = 1, *p++ = 'k';
17918 q = (boards[move][CASTLING][4] == BOARD_LEFT &&
17919 boards[move][CASTLING][5] != NoRights );
17921 for(i=BOARD_RGHT-1-k; i>=BOARD_LEFT+q; i--)
17922 if((boards[move][BOARD_HEIGHT-1][i] != BlackKing || k+q == 0) &&
17923 boards[move][VIRGIN][i] & VIRGIN_B) *p++ = i + AAA;
17928 if (q == p) *p++ = '-'; /* No castling rights */
17932 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
17933 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier &&
17934 gameInfo.variant != VariantMakruk && gameInfo.variant != VariantASEAN ) {
17935 /* En passant target square */
17936 if (move > backwardMostMove) {
17937 fromX = moveList[move - 1][0] - AAA;
17938 fromY = moveList[move - 1][1] - ONE;
17939 toX = moveList[move - 1][2] - AAA;
17940 toY = moveList[move - 1][3] - ONE;
17941 if (fromY == (whiteToPlay ? BOARD_HEIGHT-2 : 1) &&
17942 toY == (whiteToPlay ? BOARD_HEIGHT-4 : 3) &&
17943 boards[move][toY][toX] == (whiteToPlay ? BlackPawn : WhitePawn) &&
17945 /* 2-square pawn move just happened */
17947 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
17951 } else if(move == backwardMostMove) {
17952 // [HGM] perhaps we should always do it like this, and forget the above?
17953 if((signed char)boards[move][EP_STATUS] >= 0) {
17954 *p++ = boards[move][EP_STATUS] + AAA;
17955 *p++ = whiteToPlay ? '6'+BOARD_HEIGHT-8 : '3';
17967 { int i = 0, j=move;
17969 /* [HGM] find reversible plies */
17970 if (appData.debugMode) { int k;
17971 fprintf(debugFP, "write FEN 50-move: %d %d %d\n", initialRulePlies, forwardMostMove, backwardMostMove);
17972 for(k=backwardMostMove; k<=forwardMostMove; k++)
17973 fprintf(debugFP, "e%d. p=%d\n", k, (signed char)boards[k][EP_STATUS]);
17977 while(j > backwardMostMove && (signed char)boards[j][EP_STATUS] <= EP_NONE) j--,i++;
17978 if( j == backwardMostMove ) i += initialRulePlies;
17979 sprintf(p, "%d ", i);
17980 p += i>=100 ? 4 : i >= 10 ? 3 : 2;
17982 /* Fullmove number */
17983 sprintf(p, "%d", (move / 2) + 1);
17984 } else *--p = NULLCHAR;
17986 return StrSave(buf);
17990 ParseFEN (Board board, int *blackPlaysFirst, char *fen, Boolean autoSize)
17992 int i, j, k, w=0, subst=0, shuffle=0;
17994 int emptycount, virgin[BOARD_FILES];
17999 /* Piece placement data */
18000 for (i = BOARD_HEIGHT - 1; i >= 0; i--) {
18003 if (*p == '/' || *p == ' ' || *p == '[' ) {
18005 emptycount = gameInfo.boardWidth - j;
18006 while (emptycount--)
18007 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
18008 if (*p == '/') p++;
18009 else if(autoSize) { // we stumbled unexpectedly into end of board
18010 for(k=i; k<BOARD_HEIGHT; k++) { // too few ranks; shift towards bottom
18011 for(j=0; j<BOARD_WIDTH; j++) board[k-i][j] = board[k][j];
18013 appData.NrRanks = gameInfo.boardHeight - i; i=0;
18016 #if(BOARD_FILES >= 10)*0
18017 } else if(*p=='x' || *p=='X') { /* [HGM] X means 10 */
18018 p++; emptycount=10;
18019 if (j + emptycount > gameInfo.boardWidth) return FALSE;
18020 while (emptycount--)
18021 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
18023 } else if (*p == '*') {
18024 board[i][(j++)+gameInfo.holdingsWidth] = DarkSquare; p++;
18025 } else if (isdigit(*p)) {
18026 emptycount = *p++ - '0';
18027 while(isdigit(*p)) emptycount = 10*emptycount + *p++ - '0'; /* [HGM] allow > 9 */
18028 if (j + emptycount > gameInfo.boardWidth) return FALSE;
18029 while (emptycount--)
18030 board[i][(j++)+gameInfo.holdingsWidth] = EmptySquare;
18031 } else if (*p == '<') {
18032 if(i == BOARD_HEIGHT-1) shuffle = 1;
18033 else if (i != 0 || !shuffle) return FALSE;
18035 } else if (shuffle && *p == '>') {
18036 p++; // for now ignore closing shuffle range, and assume rank-end
18037 } else if (*p == '?') {
18038 if (j >= gameInfo.boardWidth) return FALSE;
18039 if (i != 0 && i != BOARD_HEIGHT-1) return FALSE; // only on back-rank
18040 board[i][(j++)+gameInfo.holdingsWidth] = ClearBoard; p++; subst++; // placeHolder
18041 } else if (*p == '+' || isalpha(*p)) {
18042 if (j >= gameInfo.boardWidth) return FALSE;
18044 piece = CharToPiece(*++p);
18045 if(piece == EmptySquare) return FALSE; /* unknown piece */
18046 piece = (ChessSquare) (CHUPROMOTED piece ); p++;
18047 if(PieceToChar(piece) != '+') return FALSE; /* unpromotable piece */
18048 } else piece = CharToPiece(*p++);
18050 if(piece==EmptySquare) return FALSE; /* unknown piece */
18051 if(*p == '~') { /* [HGM] make it a promoted piece for Crazyhouse */
18052 piece = (ChessSquare) (PROMOTED piece);
18053 if(PieceToChar(piece) != '~') return FALSE; /* cannot be a promoted piece */
18056 board[i][(j++)+gameInfo.holdingsWidth] = piece;
18062 while (*p == '/' || *p == ' ') p++;
18064 if(autoSize) appData.NrFiles = w, InitPosition(TRUE);
18066 /* [HGM] by default clear Crazyhouse holdings, if present */
18067 if(gameInfo.holdingsWidth) {
18068 for(i=0; i<BOARD_HEIGHT; i++) {
18069 board[i][0] = EmptySquare; /* black holdings */
18070 board[i][BOARD_WIDTH-1] = EmptySquare; /* white holdings */
18071 board[i][1] = (ChessSquare) 0; /* black counts */
18072 board[i][BOARD_WIDTH-2] = (ChessSquare) 0; /* white counts */
18076 /* [HGM] look for Crazyhouse holdings here */
18077 while(*p==' ') p++;
18078 if( gameInfo.holdingsWidth && p[-1] == '/' || *p == '[') {
18079 int swap=0, wcnt=0, bcnt=0;
18081 if(*p == '<') swap++, p++;
18082 if(*p == '-' ) p++; /* empty holdings */ else {
18083 if( !gameInfo.holdingsWidth ) return FALSE; /* no room to put holdings! */
18084 /* if we would allow FEN reading to set board size, we would */
18085 /* have to add holdings and shift the board read so far here */
18086 while( (piece = CharToPiece(*p) ) != EmptySquare ) {
18088 if((int) piece >= (int) BlackPawn ) {
18089 i = (int)piece - (int)BlackPawn;
18090 i = PieceToNumber((ChessSquare)i);
18091 if( i >= gameInfo.holdingsSize ) return FALSE;
18092 board[BOARD_HEIGHT-1-i][0] = piece; /* black holdings */
18093 board[BOARD_HEIGHT-1-i][1]++; /* black counts */
18096 i = (int)piece - (int)WhitePawn;
18097 i = PieceToNumber((ChessSquare)i);
18098 if( i >= gameInfo.holdingsSize ) return FALSE;
18099 board[i][BOARD_WIDTH-1] = piece; /* white holdings */
18100 board[i][BOARD_WIDTH-2]++; /* black holdings */
18104 if(subst) { // substitute back-rank question marks by holdings pieces
18105 for(j=BOARD_LEFT; j<BOARD_RGHT; j++) {
18106 int k, m, n = bcnt + 1;
18107 if(board[0][j] == ClearBoard) {
18108 if(!wcnt) return FALSE;
18110 for(k=0, m=n; k<gameInfo.holdingsSize; k++) if((m -= board[k][BOARD_WIDTH-2]) < 0) {
18111 board[0][j] = board[k][BOARD_WIDTH-1]; wcnt--;
18112 if(--board[k][BOARD_WIDTH-2] == 0) board[k][BOARD_WIDTH-1] = EmptySquare;
18116 if(board[BOARD_HEIGHT-1][j] == ClearBoard) {
18117 if(!bcnt) return FALSE;
18118 if(n >= bcnt) n = rand() % bcnt; // use same randomization for black and white if possible
18119 for(k=0, m=n; k<gameInfo.holdingsSize; k++) if((n -= board[BOARD_HEIGHT-1-k][1]) < 0) {
18120 board[BOARD_HEIGHT-1][j] = board[BOARD_HEIGHT-1-k][0]; bcnt--;
18121 if(--board[BOARD_HEIGHT-1-k][1] == 0) board[BOARD_HEIGHT-1-k][0] = EmptySquare;
18132 if(subst) return FALSE; // substitution requested, but no holdings
18134 while(*p == ' ') p++;
18138 if(appData.colorNickNames) {
18139 if( c == appData.colorNickNames[0] ) c = 'w'; else
18140 if( c == appData.colorNickNames[1] ) c = 'b';
18144 *blackPlaysFirst = FALSE;
18147 *blackPlaysFirst = TRUE;
18153 /* [HGM] We NO LONGER ignore the rest of the FEN notation */
18154 /* return the extra info in global variiables */
18156 /* set defaults in case FEN is incomplete */
18157 board[EP_STATUS] = EP_UNKNOWN;
18158 for(i=0; i<nrCastlingRights; i++ ) {
18159 board[CASTLING][i] =
18160 appData.fischerCastling ? NoRights : initialRights[i];
18161 } /* assume possible unless obviously impossible */
18162 if(initialRights[0]!=NoRights && board[castlingRank[0]][initialRights[0]] != WhiteRook) board[CASTLING][0] = NoRights;
18163 if(initialRights[1]!=NoRights && board[castlingRank[1]][initialRights[1]] != WhiteRook) board[CASTLING][1] = NoRights;
18164 if(initialRights[2]!=NoRights && board[castlingRank[2]][initialRights[2]] != WhiteUnicorn
18165 && board[castlingRank[2]][initialRights[2]] != WhiteKing) board[CASTLING][2] = NoRights;
18166 if(initialRights[3]!=NoRights && board[castlingRank[3]][initialRights[3]] != BlackRook) board[CASTLING][3] = NoRights;
18167 if(initialRights[4]!=NoRights && board[castlingRank[4]][initialRights[4]] != BlackRook) board[CASTLING][4] = NoRights;
18168 if(initialRights[5]!=NoRights && board[castlingRank[5]][initialRights[5]] != BlackUnicorn
18169 && board[castlingRank[5]][initialRights[5]] != BlackKing) board[CASTLING][5] = NoRights;
18172 while(*p==' ') p++;
18173 if(nrCastlingRights) {
18175 if(gameInfo.variant == VariantSChess) for(i=0; i<BOARD_FILES; i++) virgin[i] = 0;
18176 if(*p >= 'A' && *p <= 'Z' || *p >= 'a' && *p <= 'z' || *p=='-') {
18177 /* castling indicator present, so default becomes no castlings */
18178 for(i=0; i<nrCastlingRights; i++ ) {
18179 board[CASTLING][i] = NoRights;
18182 while(*p=='K' || *p=='Q' || *p=='k' || *p=='q' || *p=='-' ||
18183 (appData.fischerCastling || gameInfo.variant == VariantSChess) &&
18184 ( *p >= 'a' && *p < 'a' + gameInfo.boardWidth) ||
18185 ( *p >= 'A' && *p < 'A' + gameInfo.boardWidth) ) {
18186 int c = *p++, whiteKingFile=NoRights, blackKingFile=NoRights;
18188 for(i=BOARD_LEFT; i<BOARD_RGHT; i++) {
18189 if(board[BOARD_HEIGHT-1][i] == BlackKing) blackKingFile = i;
18190 if(board[0 ][i] == WhiteKing) whiteKingFile = i;
18192 if(gameInfo.variant == VariantTwoKings || gameInfo.variant == VariantKnightmate)
18193 whiteKingFile = blackKingFile = BOARD_WIDTH >> 1; // for these variant scanning fails
18194 if(whiteKingFile == NoRights || board[0][whiteKingFile] != WhiteUnicorn
18195 && board[0][whiteKingFile] != WhiteKing) whiteKingFile = NoRights;
18196 if(blackKingFile == NoRights || board[BOARD_HEIGHT-1][blackKingFile] != BlackUnicorn
18197 && board[BOARD_HEIGHT-1][blackKingFile] != BlackKing) blackKingFile = NoRights;
18200 for(i=BOARD_RGHT-1; board[0][i]!=WhiteRook && i>whiteKingFile; i--);
18201 board[CASTLING][0] = i != whiteKingFile ? i : NoRights;
18202 board[CASTLING][2] = whiteKingFile;
18203 if(board[CASTLING][0] != NoRights) virgin[board[CASTLING][0]] |= VIRGIN_W;
18204 if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
18205 if(whiteKingFile != BOARD_WIDTH>>1|| i != BOARD_RGHT-1) fischer = 1;
18208 for(i=BOARD_LEFT; i<BOARD_RGHT && board[0][i]!=WhiteRook && i<whiteKingFile; i++);
18209 board[CASTLING][1] = i != whiteKingFile ? i : NoRights;
18210 board[CASTLING][2] = whiteKingFile;
18211 if(board[CASTLING][1] != NoRights) virgin[board[CASTLING][1]] |= VIRGIN_W;
18212 if(board[CASTLING][2] != NoRights) virgin[board[CASTLING][2]] |= VIRGIN_W;
18213 if(whiteKingFile != BOARD_WIDTH>>1|| i != BOARD_LEFT) fischer = 1;
18216 for(i=BOARD_RGHT-1; board[BOARD_HEIGHT-1][i]!=BlackRook && i>blackKingFile; i--);
18217 board[CASTLING][3] = i != blackKingFile ? i : NoRights;
18218 board[CASTLING][5] = blackKingFile;
18219 if(board[CASTLING][3] != NoRights) virgin[board[CASTLING][3]] |= VIRGIN_B;
18220 if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
18221 if(blackKingFile != BOARD_WIDTH>>1|| i != BOARD_RGHT-1) fischer = 1;
18224 for(i=BOARD_LEFT; i<BOARD_RGHT && board[BOARD_HEIGHT-1][i]!=BlackRook && i<blackKingFile; i++);
18225 board[CASTLING][4] = i != blackKingFile ? i : NoRights;
18226 board[CASTLING][5] = blackKingFile;
18227 if(board[CASTLING][4] != NoRights) virgin[board[CASTLING][4]] |= VIRGIN_B;
18228 if(board[CASTLING][5] != NoRights) virgin[board[CASTLING][5]] |= VIRGIN_B;
18229 if(blackKingFile != BOARD_WIDTH>>1|| i != BOARD_LEFT) fischer = 1;
18232 default: /* FRC castlings */
18233 if(c >= 'a') { /* black rights */
18234 if(gameInfo.variant == VariantSChess) { virgin[c-AAA] |= VIRGIN_B; break; } // in S-Chess castlings are always kq, so just virginity
18235 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
18236 if(board[BOARD_HEIGHT-1][i] == BlackKing) break;
18237 if(i == BOARD_RGHT) break;
18238 board[CASTLING][5] = i;
18240 if(board[BOARD_HEIGHT-1][c] < BlackPawn ||
18241 board[BOARD_HEIGHT-1][c] >= BlackKing ) break;
18243 board[CASTLING][3] = c;
18245 board[CASTLING][4] = c;
18246 } else { /* white rights */
18247 if(gameInfo.variant == VariantSChess) { virgin[c-AAA-'A'+'a'] |= VIRGIN_W; break; } // in S-Chess castlings are always KQ
18248 for(i=BOARD_LEFT; i<BOARD_RGHT; i++)
18249 if(board[0][i] == WhiteKing) break;
18250 if(i == BOARD_RGHT) break;
18251 board[CASTLING][2] = i;
18252 c -= AAA - 'a' + 'A';
18253 if(board[0][c] >= WhiteKing) break;
18255 board[CASTLING][0] = c;
18257 board[CASTLING][1] = c;
18261 for(i=0; i<nrCastlingRights; i++)
18262 if(board[CASTLING][i] != NoRights) initialRights[i] = board[CASTLING][i];
18263 if(gameInfo.variant == VariantSChess)
18264 for(i=0; i<BOARD_FILES; i++) board[VIRGIN][i] = shuffle ? VIRGIN_W | VIRGIN_B : virgin[i]; // when shuffling assume all virgin
18265 if(fischer && shuffle) appData.fischerCastling = TRUE;
18266 if (appData.debugMode) {
18267 fprintf(debugFP, "FEN castling rights:");
18268 for(i=0; i<nrCastlingRights; i++)
18269 fprintf(debugFP, " %d", board[CASTLING][i]);
18270 fprintf(debugFP, "\n");
18273 while(*p==' ') p++;
18276 if(shuffle) SetUpShuffle(board, appData.defaultFrcPosition);
18278 /* read e.p. field in games that know e.p. capture */
18279 if(gameInfo.variant != VariantShogi && gameInfo.variant != VariantXiangqi &&
18280 gameInfo.variant != VariantShatranj && gameInfo.variant != VariantCourier &&
18281 gameInfo.variant != VariantMakruk && gameInfo.variant != VariantASEAN ) {
18283 p++; board[EP_STATUS] = EP_NONE;
18285 char c = *p++ - AAA;
18287 if(c < BOARD_LEFT || c >= BOARD_RGHT) return TRUE;
18288 if(*p >= '0' && *p <='9') p++;
18289 board[EP_STATUS] = c;
18294 if(sscanf(p, "%d", &i) == 1) {
18295 FENrulePlies = i; /* 50-move ply counter */
18296 /* (The move number is still ignored) */
18303 EditPositionPasteFEN (char *fen)
18306 Board initial_position;
18308 if (!ParseFEN(initial_position, &blackPlaysFirst, fen, TRUE)) {
18309 DisplayError(_("Bad FEN position in clipboard"), 0);
18312 int savedBlackPlaysFirst = blackPlaysFirst;
18313 EditPositionEvent();
18314 blackPlaysFirst = savedBlackPlaysFirst;
18315 CopyBoard(boards[0], initial_position);
18316 initialRulePlies = FENrulePlies; /* [HGM] copy FEN attributes as well */
18317 EditPositionDone(FALSE); // [HGM] fake: do not fake rights if we had FEN
18318 DisplayBothClocks();
18319 DrawPosition(FALSE, boards[currentMove]);
18324 static char cseq[12] = "\\ ";
18327 set_cont_sequence (char *new_seq)
18332 // handle bad attempts to set the sequence
18334 return 0; // acceptable error - no debug
18336 len = strlen(new_seq);
18337 ret = (len > 0) && (len < sizeof(cseq));
18339 safeStrCpy(cseq, new_seq, sizeof(cseq)/sizeof(cseq[0]));
18340 else if (appData.debugMode)
18341 fprintf(debugFP, "Invalid continuation sequence \"%s\" (maximum length is: %u)\n", new_seq, (unsigned) sizeof(cseq)-1);
18346 reformat a source message so words don't cross the width boundary. internal
18347 newlines are not removed. returns the wrapped size (no null character unless
18348 included in source message). If dest is NULL, only calculate the size required
18349 for the dest buffer. lp argument indicats line position upon entry, and it's
18350 passed back upon exit.
18353 wrap (char *dest, char *src, int count, int width, int *lp)
18355 int len, i, ansi, cseq_len, line, old_line, old_i, old_len, clen;
18357 cseq_len = strlen(cseq);
18358 old_line = line = *lp;
18359 ansi = len = clen = 0;
18361 for (i=0; i < count; i++)
18363 if (src[i] == '\033')
18366 // if we hit the width, back up
18367 if (!ansi && (line >= width) && src[i] != '\n' && src[i] != ' ')
18369 // store i & len in case the word is too long
18370 old_i = i, old_len = len;
18372 // find the end of the last word
18373 while (i && src[i] != ' ' && src[i] != '\n')
18379 // word too long? restore i & len before splitting it
18380 if ((old_i-i+clen) >= width)
18387 if (i && src[i-1] == ' ')
18390 if (src[i] != ' ' && src[i] != '\n')
18397 // now append the newline and continuation sequence
18402 strncpy(dest+len, cseq, cseq_len);
18410 dest[len] = src[i];
18414 if (src[i] == '\n')
18419 if (dest && appData.debugMode)
18421 fprintf(debugFP, "wrap(count:%d,width:%d,line:%d,len:%d,*lp:%d,src: ",
18422 count, width, line, len, *lp);
18423 show_bytes(debugFP, src, count);
18424 fprintf(debugFP, "\ndest: ");
18425 show_bytes(debugFP, dest, len);
18426 fprintf(debugFP, "\n");
18428 *lp = dest ? line : old_line;
18433 // [HGM] vari: routines for shelving variations
18434 Boolean modeRestore = FALSE;
18437 PushInner (int firstMove, int lastMove)
18439 int i, j, nrMoves = lastMove - firstMove;
18441 // push current tail of game on stack
18442 savedResult[storedGames] = gameInfo.result;
18443 savedDetails[storedGames] = gameInfo.resultDetails;
18444 gameInfo.resultDetails = NULL;
18445 savedFirst[storedGames] = firstMove;
18446 savedLast [storedGames] = lastMove;
18447 savedFramePtr[storedGames] = framePtr;
18448 framePtr -= nrMoves; // reserve space for the boards
18449 for(i=nrMoves; i>=1; i--) { // copy boards to stack, working downwards, in case of overlap
18450 CopyBoard(boards[framePtr+i], boards[firstMove+i]);
18451 for(j=0; j<MOVE_LEN; j++)
18452 moveList[framePtr+i][j] = moveList[firstMove+i-1][j];
18453 for(j=0; j<2*MOVE_LEN; j++)
18454 parseList[framePtr+i][j] = parseList[firstMove+i-1][j];
18455 timeRemaining[0][framePtr+i] = timeRemaining[0][firstMove+i];
18456 timeRemaining[1][framePtr+i] = timeRemaining[1][firstMove+i];
18457 pvInfoList[framePtr+i] = pvInfoList[firstMove+i-1];
18458 pvInfoList[firstMove+i-1].depth = 0;
18459 commentList[framePtr+i] = commentList[firstMove+i];
18460 commentList[firstMove+i] = NULL;
18464 forwardMostMove = firstMove; // truncate game so we can start variation
18468 PushTail (int firstMove, int lastMove)
18470 if(appData.icsActive) { // only in local mode
18471 forwardMostMove = currentMove; // mimic old ICS behavior
18474 if(storedGames >= MAX_VARIATIONS-2) return; // leave one for PV-walk
18476 PushInner(firstMove, lastMove);
18477 if(storedGames == 1) GreyRevert(FALSE);
18478 if(gameMode == PlayFromGameFile) gameMode = EditGame, modeRestore = TRUE;
18482 PopInner (Boolean annotate)
18485 char buf[8000], moveBuf[20];
18487 ToNrEvent(savedFirst[storedGames-1]); // sets currentMove
18488 storedGames--; // do this after ToNrEvent, to make sure HistorySet will refresh entire game after PopInner returns
18489 nrMoves = savedLast[storedGames] - currentMove;
18492 if(!WhiteOnMove(currentMove))
18493 snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", (currentMove+2)>>1);
18494 else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0]));
18495 for(i=currentMove; i<forwardMostMove; i++) {
18497 snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", (i+2)>>1, SavePart(parseList[i]));
18498 else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i]));
18499 strcat(buf, moveBuf);
18500 if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); }
18501 if(!--cnt) { strcat(buf, "\n"); cnt = 10; }
18505 for(i=1; i<=nrMoves; i++) { // copy last variation back
18506 CopyBoard(boards[currentMove+i], boards[framePtr+i]);
18507 for(j=0; j<MOVE_LEN; j++)
18508 moveList[currentMove+i-1][j] = moveList[framePtr+i][j];
18509 for(j=0; j<2*MOVE_LEN; j++)
18510 parseList[currentMove+i-1][j] = parseList[framePtr+i][j];
18511 timeRemaining[0][currentMove+i] = timeRemaining[0][framePtr+i];
18512 timeRemaining[1][currentMove+i] = timeRemaining[1][framePtr+i];
18513 pvInfoList[currentMove+i-1] = pvInfoList[framePtr+i];
18514 if(commentList[currentMove+i]) free(commentList[currentMove+i]);
18515 commentList[currentMove+i] = commentList[framePtr+i];
18516 commentList[framePtr+i] = NULL;
18518 if(annotate) AppendComment(currentMove+1, buf, FALSE);
18519 framePtr = savedFramePtr[storedGames];
18520 gameInfo.result = savedResult[storedGames];
18521 if(gameInfo.resultDetails != NULL) {
18522 free(gameInfo.resultDetails);
18524 gameInfo.resultDetails = savedDetails[storedGames];
18525 forwardMostMove = currentMove + nrMoves;
18529 PopTail (Boolean annotate)
18531 if(appData.icsActive) return FALSE; // only in local mode
18532 if(!storedGames) return FALSE; // sanity
18533 CommentPopDown(); // make sure no stale variation comments to the destroyed line can remain open
18535 PopInner(annotate);
18536 if(currentMove < forwardMostMove) ForwardEvent(); else
18537 HistorySet(parseList, backwardMostMove, forwardMostMove, currentMove-1);
18539 if(storedGames == 0) { GreyRevert(TRUE); if(modeRestore) modeRestore = FALSE, gameMode = PlayFromGameFile; }
18545 { // remove all shelved variations
18547 for(i=0; i<storedGames; i++) {
18548 if(savedDetails[i])
18549 free(savedDetails[i]);
18550 savedDetails[i] = NULL;
18552 for(i=framePtr; i<MAX_MOVES; i++) {
18553 if(commentList[i]) free(commentList[i]);
18554 commentList[i] = NULL;
18556 framePtr = MAX_MOVES-1;
18561 LoadVariation (int index, char *text)
18562 { // [HGM] vari: shelve previous line and load new variation, parsed from text around text[index]
18563 char *p = text, *start = NULL, *end = NULL, wait = NULLCHAR;
18564 int level = 0, move;
18566 if(gameMode != EditGame && gameMode != AnalyzeMode && gameMode != PlayFromGameFile) return;
18567 // first find outermost bracketing variation
18568 while(*p) { // hope I got this right... Non-nesting {} and [] can screen each other and nesting ()
18569 if(!wait) { // while inside [] pr {}, ignore everyting except matching closing ]}
18570 if(*p == '{') wait = '}'; else
18571 if(*p == '[') wait = ']'; else
18572 if(*p == '(' && level++ == 0 && p-text < index) start = p+1;
18573 if(*p == ')' && level > 0 && --level == 0 && p-text > index && end == NULL) end = p-1;
18575 if(*p == wait) wait = NULLCHAR; // closing ]} found
18578 if(!start || !end) return; // no variation found, or syntax error in PGN: ignore click
18579 if(appData.debugMode) fprintf(debugFP, "at move %d load variation '%s'\n", currentMove, start);
18580 end[1] = NULLCHAR; // clip off comment beyond variation
18581 ToNrEvent(currentMove-1);
18582 PushTail(currentMove, forwardMostMove); // shelve main variation. This truncates game
18583 // kludge: use ParsePV() to append variation to game
18584 move = currentMove;
18585 ParsePV(start, TRUE, TRUE);
18586 forwardMostMove = endPV; endPV = -1; currentMove = move; // cleanup what ParsePV did
18587 ClearPremoveHighlights();
18589 ToNrEvent(currentMove+1);
18595 char *p, *q, buf[MSG_SIZ];
18596 if(engineLine && engineLine[0]) { // a theme was selected from the listbox
18597 snprintf(buf, MSG_SIZ, "-theme %s", engineLine);
18598 ParseArgsFromString(buf);
18599 ActivateTheme(TRUE); // also redo colors
18603 if(*p && !strchr(p, '"')) // theme name specified and well-formed; add settings to theme list
18606 q = appData.themeNames;
18607 snprintf(buf, MSG_SIZ, "\"%s\"", nickName);
18608 if(appData.useBitmaps) {
18609 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ubt true -lbtf \"%s\" -dbtf \"%s\" -lbtm %d -dbtm %d",
18610 appData.liteBackTextureFile, appData.darkBackTextureFile,
18611 appData.liteBackTextureMode,
18612 appData.darkBackTextureMode );
18614 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ubt false -lsc %s -dsc %s",
18615 Col2Text(2), // lightSquareColor
18616 Col2Text(3) ); // darkSquareColor
18618 if(appData.useBorder) {
18619 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ub true -border \"%s\"",
18622 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -ub false");
18624 if(appData.useFont) {
18625 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -upf true -pf \"%s\" -fptc \"%s\" -fpfcw %s -fpbcb %s",
18626 appData.renderPiecesWithFont,
18627 appData.fontToPieceTable,
18628 Col2Text(9), // appData.fontBackColorWhite
18629 Col2Text(10) ); // appData.fontForeColorBlack
18631 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -upf false -pid \"%s\"",
18632 appData.pieceDirectory);
18633 if(!appData.pieceDirectory[0])
18634 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -wpc %s -bpc %s",
18635 Col2Text(0), // whitePieceColor
18636 Col2Text(1) ); // blackPieceColor
18638 snprintf(buf+strlen(buf), MSG_SIZ-strlen(buf), " -hsc %s -phc %s\n",
18639 Col2Text(4), // highlightSquareColor
18640 Col2Text(5) ); // premoveHighlightColor
18641 appData.themeNames = malloc(len = strlen(q) + strlen(buf) + 1);
18642 if(insert != q) insert[-1] = NULLCHAR;
18643 snprintf(appData.themeNames, len, "%s\n%s%s", q, buf, insert);
18646 ActivateTheme(FALSE);